blob: 23ad4234c876b2854f12922db3072aa2022d482c [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * 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.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
92const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100127 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700145 if (current_streams->find(new_stream->id()) != nullptr) {
146 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100385void NoteKeyProtocolAndMedia(
386 KeyExchangeProtocolType protocol_type,
387 cricket::MediaType media_type,
388 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
389 if (!uma_observer)
390 return;
391 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
392 protocol_type,
393 webrtc::kEnumCounterKeyProtocolMax);
394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
412 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
413 it->second,
414 kEnumCounterKeyProtocolMediaTypeMax);
415 }
416}
417
Steve Anton75737c02017-11-06 10:37:17 -0800418// Checks that each non-rejected content has SDES crypto keys or a DTLS
419// fingerprint, unless it's in a BUNDLE group, in which case only the
420// BUNDLE-tag section (first media section/description in the BUNDLE group)
421// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
422// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
423// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100424RTCError VerifyCrypto(const SessionDescription* desc,
425 bool dtls_enabled,
426 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800431 continue;
432 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Qingsi Wang866e08d2018-03-22 17:54:23 -0700603rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
604 int rtc_configuration_parameter) {
605 if (rtc_configuration_parameter ==
606 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
607 return rtc::nullopt;
608 }
609 return rtc_configuration_parameter;
610}
611
Steve Anton75737c02017-11-06 10:37:17 -0800612} // namespace
613
Henrik Boström31638672017-11-23 17:48:32 +0100614// Upon completion, posts a task to execute the callback of the
615// SetSessionDescriptionObserver asynchronously on the same thread. At this
616// point, the state of the peer connection might no longer reflect the effects
617// of the SetRemoteDescription operation, as the peer connection could have been
618// modified during the post.
619// TODO(hbos): Remove this class once we remove the version of
620// PeerConnectionInterface::SetRemoteDescription() that takes a
621// SetSessionDescriptionObserver as an argument.
622class PeerConnection::SetRemoteDescriptionObserverAdapter
623 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
624 public:
625 SetRemoteDescriptionObserverAdapter(
626 rtc::scoped_refptr<PeerConnection> pc,
627 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
628 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
629
630 // SetRemoteDescriptionObserverInterface implementation.
631 void OnSetRemoteDescriptionComplete(RTCError error) override {
632 if (error.ok())
633 pc_->PostSetSessionDescriptionSuccess(wrapper_);
634 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100635 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100636 }
637
638 private:
639 rtc::scoped_refptr<PeerConnection> pc_;
640 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
641};
642
deadbeef293e9262017-01-11 12:28:30 -0800643bool PeerConnectionInterface::RTCConfiguration::operator==(
644 const PeerConnectionInterface::RTCConfiguration& o) const {
645 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700646 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800647 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000648 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700649 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800650 BundlePolicy bundle_policy;
651 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700652 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
653 int ice_candidate_pool_size;
654 bool disable_ipv6;
655 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700656 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100657 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 bool enable_rtp_data_channel;
659 rtc::Optional<int> screencast_min_bitrate;
660 rtc::Optional<bool> combined_audio_video_bwe;
661 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800662 TcpCandidatePolicy tcp_candidate_policy;
663 CandidateNetworkPolicy candidate_network_policy;
664 int audio_jitter_buffer_max_packets;
665 bool audio_jitter_buffer_fast_accelerate;
666 int ice_connection_receiving_timeout;
667 int ice_backup_candidate_pair_ping_interval;
668 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800669 bool prioritize_most_likely_ice_candidate_pairs;
670 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800671 bool prune_turn_ports;
672 bool presume_writable_when_fully_relayed;
673 bool enable_ice_renomination;
674 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800675 rtc::Optional<int> ice_check_interval_strong_connectivity;
676 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800677 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700678 rtc::Optional<int> ice_unwritable_timeout;
679 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800680 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700681 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200682 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800683 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800684 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800685 };
686 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
687 "Did you add something to RTCConfiguration and forget to "
688 "update operator==?");
689 return type == o.type && servers == o.servers &&
690 bundle_policy == o.bundle_policy &&
691 rtcp_mux_policy == o.rtcp_mux_policy &&
692 tcp_candidate_policy == o.tcp_candidate_policy &&
693 candidate_network_policy == o.candidate_network_policy &&
694 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
695 audio_jitter_buffer_fast_accelerate ==
696 o.audio_jitter_buffer_fast_accelerate &&
697 ice_connection_receiving_timeout ==
698 o.ice_connection_receiving_timeout &&
699 ice_backup_candidate_pair_ping_interval ==
700 o.ice_backup_candidate_pair_ping_interval &&
701 continual_gathering_policy == o.continual_gathering_policy &&
702 certificates == o.certificates &&
703 prioritize_most_likely_ice_candidate_pairs ==
704 o.prioritize_most_likely_ice_candidate_pairs &&
705 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800706 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700707 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100708 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800709 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800710 screencast_min_bitrate == o.screencast_min_bitrate &&
711 combined_audio_video_bwe == o.combined_audio_video_bwe &&
712 enable_dtls_srtp == o.enable_dtls_srtp &&
713 ice_candidate_pool_size == o.ice_candidate_pool_size &&
714 prune_turn_ports == o.prune_turn_ports &&
715 presume_writable_when_fully_relayed ==
716 o.presume_writable_when_fully_relayed &&
717 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800718 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800719 ice_check_interval_strong_connectivity ==
720 o.ice_check_interval_strong_connectivity &&
721 ice_check_interval_weak_connectivity ==
722 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700723 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700724 ice_unwritable_timeout == o.ice_unwritable_timeout &&
725 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800726 stun_candidate_keepalive_interval ==
727 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200728 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800729 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800730 sdp_semantics == o.sdp_semantics &&
731 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800732}
733
734bool PeerConnectionInterface::RTCConfiguration::operator!=(
735 const PeerConnectionInterface::RTCConfiguration& o) const {
736 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800737}
738
zhihuang8f65cdf2016-05-06 18:40:30 -0700739// Generate a RTCP CNAME when a PeerConnection is created.
740std::string GenerateRtcpCname() {
741 std::string cname;
742 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100743 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800744 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700745 }
746 return cname;
747}
748
zhihuang1c378ed2017-08-17 14:10:50 -0700749bool ValidateOfferAnswerOptions(
750 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
751 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
752 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700753}
754
zhihuang1c378ed2017-08-17 14:10:50 -0700755// From |rtc_options|, fill parts of |session_options| shared by all generated
756// m= sections (in other words, nothing that involves a map/array).
757void ExtractSharedMediaSessionOptions(
758 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
759 cricket::MediaSessionOptions* session_options) {
760 session_options->vad_enabled = rtc_options.voice_activity_detection;
761 session_options->bundle_enabled = rtc_options.use_rtp_mux;
762}
zhihuanga77e6bb2017-08-14 18:17:48 -0700763
zhihuang1c378ed2017-08-17 14:10:50 -0700764bool ConvertConstraintsToOfferAnswerOptions(
765 const MediaConstraintsInterface* constraints,
766 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700767 if (!constraints) {
768 return true;
769 }
zhihuang1c378ed2017-08-17 14:10:50 -0700770
771 bool value = false;
772 size_t mandatory_constraints_satisfied = 0;
773
774 if (FindConstraint(constraints,
775 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
776 &mandatory_constraints_satisfied)) {
777 offer_answer_options->offer_to_receive_audio =
778 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
779 kOfferToReceiveMediaTrue
780 : 0;
781 }
782
783 if (FindConstraint(constraints,
784 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
785 &mandatory_constraints_satisfied)) {
786 offer_answer_options->offer_to_receive_video =
787 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
788 kOfferToReceiveMediaTrue
789 : 0;
790 }
791 if (FindConstraint(constraints,
792 MediaConstraintsInterface::kVoiceActivityDetection, &value,
793 &mandatory_constraints_satisfied)) {
794 offer_answer_options->voice_activity_detection = value;
795 }
796 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
797 &mandatory_constraints_satisfied)) {
798 offer_answer_options->use_rtp_mux = value;
799 }
800 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
801 &value, &mandatory_constraints_satisfied)) {
802 offer_answer_options->ice_restart = value;
803 }
804
deadbeefab9b2d12015-10-14 11:33:11 -0700805 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
806}
807
zhihuang38ede132017-06-15 12:52:32 -0700808PeerConnection::PeerConnection(PeerConnectionFactory* factory,
809 std::unique_ptr<RtcEventLog> event_log,
810 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700812 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700813 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700814 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700815 remote_streams_(StreamCollection::Create()),
816 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000817
818PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100819 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800820 RTC_DCHECK_RUN_ON(signaling_thread());
821
Steve Anton8af21862017-12-15 11:20:13 -0800822 // Need to stop transceivers before destroying the stats collector because
823 // AudioRtpSender has a reference to the StatsCollector it will update when
824 // stopping.
825 for (auto transceiver : transceivers_) {
826 transceiver->Stop();
827 }
Steve Anton4171afb2017-11-20 10:20:22 -0800828
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700829 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800830 if (stats_collector_) {
831 stats_collector_->WaitForPendingRequest();
832 stats_collector_ = nullptr;
833 }
Steve Anton75737c02017-11-06 10:37:17 -0800834
Steve Anton8af21862017-12-15 11:20:13 -0800835 // Don't destroy BaseChannels until after stats has been cleaned up so that
836 // the last stats request can still read from the channels.
837 DestroyAllChannels();
838
Mirko Bonadei675513b2017-11-09 11:09:25 +0100839 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800840
841 webrtc_session_desc_factory_.reset();
842 sctp_invoker_.reset();
843 sctp_factory_.reset();
844 transport_controller_.reset();
845
deadbeef91dd5672016-05-18 16:55:30 -0700846 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700847 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700848 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700849 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700850 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700851 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800852 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700853 event_log_.reset();
854 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855}
856
Steve Anton8af21862017-12-15 11:20:13 -0800857void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800858 // Destroy video channels first since they may have a pointer to a voice
859 // channel.
860 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800861 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800862 DestroyTransceiverChannel(transceiver);
863 }
864 }
865 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800866 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800867 DestroyTransceiverChannel(transceiver);
868 }
869 }
870 DestroyDataChannel();
871}
872
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000873bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000874 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700875 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200876 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800877 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100878 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700879
880 RTCError config_error = ValidateConfiguration(configuration);
881 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100882 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700883 return false;
884 }
885
deadbeef293e9262017-01-11 12:28:30 -0800886 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100887 RTC_LOG(LS_ERROR)
888 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100889 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800890 return false;
891 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200892
deadbeef653b8e02015-11-11 12:55:10 -0800893 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800894 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100896 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800897 return false;
898 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000899 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800900 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800901
deadbeef91dd5672016-05-18 16:55:30 -0700902 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700903 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700904 if (!network_thread()->Invoke<bool>(
905 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
906 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907 return false;
908 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909
Steve Anton75737c02017-11-06 10:37:17 -0800910 // RFC 3264: The numeric value of the session id and version in the
911 // o line MUST be representable with a "64 bit signed integer".
912 // Due to this constraint session id |session_id_| is max limited to
913 // LLONG_MAX.
914 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
915 transport_controller_.reset(factory_->CreateTransportController(
Qingsi Wang93a84392018-01-30 17:13:09 -0800916 port_allocator_.get(), configuration.redetermine_role_on_ice_restart,
917 event_log_.get()));
Steve Anton75737c02017-11-06 10:37:17 -0800918 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
919 transport_controller_->SignalConnectionState.connect(
920 this, &PeerConnection::OnTransportControllerConnectionState);
921 transport_controller_->SignalGatheringState.connect(
922 this, &PeerConnection::OnTransportControllerGatheringState);
923 transport_controller_->SignalCandidatesGathered.connect(
924 this, &PeerConnection::OnTransportControllerCandidatesGathered);
925 transport_controller_->SignalCandidatesRemoved.connect(
926 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
927 transport_controller_->SignalDtlsHandshakeError.connect(
928 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
929
930 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700931
deadbeefab9b2d12015-10-14 11:33:11 -0700932 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700933 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934
Steve Antonba818672017-11-06 10:21:57 -0800935 configuration_ = configuration;
936
Steve Anton75737c02017-11-06 10:37:17 -0800937 const PeerConnectionFactoryInterface::Options& options = factory_->options();
938
939 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
940
941 // Obtain a certificate from RTCConfiguration if any were provided (optional).
942 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
943 if (!configuration.certificates.empty()) {
944 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
945 // just picking the first one. The decision should be made based on the DTLS
946 // handshake. The DTLS negotiations need to know about all certificates.
947 certificate = configuration.certificates[0];
948 }
949
Steve Antond25da372017-11-06 14:50:29 -0800950 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800951
952 if (options.disable_encryption) {
953 dtls_enabled_ = false;
954 } else {
955 // Enable DTLS by default if we have an identity store or a certificate.
956 dtls_enabled_ = (cert_generator || certificate);
957 // |configuration| can override the default |dtls_enabled_| value.
958 if (configuration.enable_dtls_srtp) {
959 dtls_enabled_ = *(configuration.enable_dtls_srtp);
960 }
961 }
962
963 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
964 // It takes precendence over the disable_sctp_data_channels
965 // PeerConnectionFactoryInterface::Options.
966 if (configuration.enable_rtp_data_channel) {
967 data_channel_type_ = cricket::DCT_RTP;
968 } else {
969 // DTLS has to be enabled to use SCTP.
970 if (!options.disable_sctp_data_channels && dtls_enabled_) {
971 data_channel_type_ = cricket::DCT_SCTP;
972 }
973 }
974
975 video_options_.screencast_min_bitrate_kbps =
976 configuration.screencast_min_bitrate;
977 audio_options_.combined_audio_video_bwe =
978 configuration.combined_audio_video_bwe;
979
980 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100981 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800982
983 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100984 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800985
986 // Whether the certificate generator/certificate is null or not determines
987 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
988 // the right instructions by clearing the variables if needed.
989 if (!dtls_enabled_) {
990 cert_generator.reset();
991 certificate = nullptr;
992 } else if (certificate) {
993 // Favor generated certificate over the certificate generator.
994 cert_generator.reset();
995 }
996
997 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
998 signaling_thread(), channel_manager(), this, session_id(),
999 std::move(cert_generator), certificate));
1000 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1001 this, &PeerConnection::OnCertificateReady);
1002
1003 if (options.disable_encryption) {
1004 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1005 }
1006
1007 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1008 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009
Steve Anton4171afb2017-11-20 10:20:22 -08001010 // Add default audio/video transceivers for Plan B SDP.
1011 if (!IsUnifiedPlan()) {
1012 transceivers_.push_back(
1013 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1014 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1015 transceivers_.push_back(
1016 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1017 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1018 }
1019
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020 return true;
1021}
1022
Steve Anton038834f2017-07-14 15:59:59 -07001023RTCError PeerConnection::ValidateConfiguration(
1024 const RTCConfiguration& config) const {
1025 if (config.ice_regather_interval_range &&
1026 config.continual_gathering_policy == GATHER_ONCE) {
1027 return RTCError(RTCErrorType::INVALID_PARAMETER,
1028 "ice_regather_interval_range specified but continual "
1029 "gathering policy is GATHER_ONCE");
1030 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001031 auto result =
1032 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1033 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001034}
1035
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001036rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001038 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1039 "Plan SdpSemantics. Please use GetSenders "
1040 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001041 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042}
1043
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001044rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001046 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1047 "Plan SdpSemantics. Please use GetReceivers "
1048 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001049 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050}
1051
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001052bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001053 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1054 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001055 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001056 if (IsClosed()) {
1057 return false;
1058 }
deadbeefab9b2d12015-10-14 11:33:11 -07001059 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060 return false;
1061 }
deadbeefab9b2d12015-10-14 11:33:11 -07001062
1063 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001064 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1065 observer->SignalAudioTrackAdded.connect(this,
1066 &PeerConnection::OnAudioTrackAdded);
1067 observer->SignalAudioTrackRemoved.connect(
1068 this, &PeerConnection::OnAudioTrackRemoved);
1069 observer->SignalVideoTrackAdded.connect(this,
1070 &PeerConnection::OnVideoTrackAdded);
1071 observer->SignalVideoTrackRemoved.connect(
1072 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001073 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001074
deadbeefab9b2d12015-10-14 11:33:11 -07001075 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001076 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001077 }
1078 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001079 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001080 }
1081
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001082 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 observer_->OnRenegotiationNeeded();
1084 return true;
1085}
1086
1087void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001088 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1089 "Plan SdpSemantics. Please use RemoveTrack "
1090 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001091 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001092 if (!IsClosed()) {
1093 for (const auto& track : local_stream->GetAudioTracks()) {
1094 RemoveAudioTrack(track.get(), local_stream);
1095 }
1096 for (const auto& track : local_stream->GetVideoTracks()) {
1097 RemoveVideoTrack(track.get(), local_stream);
1098 }
deadbeefab9b2d12015-10-14 11:33:11 -07001099 }
deadbeefab9b2d12015-10-14 11:33:11 -07001100 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001101 stream_observers_.erase(
1102 std::remove_if(
1103 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001104 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001105 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001106 }),
1107 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001108
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001109 if (IsClosed()) {
1110 return;
1111 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 observer_->OnRenegotiationNeeded();
1113}
1114
deadbeefe1f9d832016-01-14 15:35:42 -08001115rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1116 MediaStreamTrackInterface* track,
1117 std::vector<MediaStreamInterface*> streams) {
1118 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001119 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001120 for (auto* stream : streams) {
1121 if (!stream) {
1122 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1123 return nullptr;
1124 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001125 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001126 }
Seth Hampson845e8782018-03-02 11:34:10 -08001127 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001128 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001129 return nullptr;
1130 }
Steve Antonf9381f02017-12-14 10:23:57 -08001131 return sender_or_error.MoveValue();
1132}
1133
Steve Anton2d6c76a2018-01-05 17:10:52 -08001134RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001135 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001136 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001137 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001138 if (!track) {
1139 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1140 }
1141 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1142 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1144 "Track has invalid kind: " + track->kind());
1145 }
Steve Antonf9381f02017-12-14 10:23:57 -08001146 if (IsClosed()) {
1147 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1148 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001149 }
Steve Anton4171afb2017-11-20 10:20:22 -08001150 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001151 LOG_AND_RETURN_ERROR(
1152 RTCErrorType::INVALID_PARAMETER,
1153 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001154 }
Steve Antonf9381f02017-12-14 10:23:57 -08001155 auto sender_or_error =
Seth Hampsonf351c342018-03-29 15:45:58 -07001156 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1157 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001158 if (sender_or_error.ok()) {
1159 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001160 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001161 }
1162 return sender_or_error;
1163}
deadbeefe1f9d832016-01-14 15:35:42 -08001164
Steve Antonf9381f02017-12-14 10:23:57 -08001165RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1166PeerConnection::AddTrackPlanB(
1167 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001168 const std::vector<std::string>& stream_ids) {
Seth Hampsonf351c342018-03-29 15:45:58 -07001169 if (stream_ids.size() > 1u) {
1170 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1171 "AddTrack with more than one stream is not "
1172 "supported with Plan B semantics.");
1173 }
1174 std::vector<std::string> adjusted_stream_ids = stream_ids;
1175 if (adjusted_stream_ids.empty()) {
1176 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1177 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001178 cricket::MediaType media_type =
1179 (track->kind() == MediaStreamTrackInterface::kAudioKind
1180 ? cricket::MEDIA_TYPE_AUDIO
1181 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampsonf351c342018-03-29 15:45:58 -07001182 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001183 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001184 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001185 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001186 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001187 FindSenderInfo(local_audio_sender_infos_,
Seth Hampsonf351c342018-03-29 15:45:58 -07001188 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001189 if (sender_info) {
1190 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001191 }
Steve Antonf9381f02017-12-14 10:23:57 -08001192 } else {
1193 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001194 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001195 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001196 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001197 FindSenderInfo(local_video_sender_infos_,
Seth Hampsonf351c342018-03-29 15:45:58 -07001198 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001199 if (sender_info) {
1200 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001201 }
deadbeefe1f9d832016-01-14 15:35:42 -08001202 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001203 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001204}
deadbeefe1f9d832016-01-14 15:35:42 -08001205
Steve Antonf9381f02017-12-14 10:23:57 -08001206RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1207PeerConnection::AddTrackUnifiedPlan(
1208 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001209 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001210 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1211 if (transceiver) {
1212 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001213 transceiver->internal()->set_direction(
1214 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001215 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001216 transceiver->internal()->set_direction(
1217 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001218 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001219 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001220 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001221 } else {
1222 cricket::MediaType media_type =
1223 (track->kind() == MediaStreamTrackInterface::kAudioKind
1224 ? cricket::MEDIA_TYPE_AUDIO
1225 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson845e8782018-03-02 11:34:10 -08001226 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001227 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1228 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001229 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001230 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001231 }
Steve Antonf9381f02017-12-14 10:23:57 -08001232 return transceiver->sender();
1233}
1234
1235rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1236PeerConnection::FindFirstTransceiverForAddedTrack(
1237 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1238 RTC_DCHECK(track);
1239 for (auto transceiver : transceivers_) {
1240 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001241 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001242 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001243 !transceiver->internal()->has_ever_been_used_to_send() &&
1244 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001245 return transceiver;
1246 }
1247 }
1248 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001249}
1250
1251bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1252 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001253 return RemoveTrackInternal(sender).ok();
1254}
1255
1256RTCError PeerConnection::RemoveTrackInternal(
1257 rtc::scoped_refptr<RtpSenderInterface> sender) {
1258 if (!sender) {
1259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1260 }
deadbeefe1f9d832016-01-14 15:35:42 -08001261 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001262 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1263 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001264 }
Steve Antonf9381f02017-12-14 10:23:57 -08001265 if (IsUnifiedPlan()) {
1266 auto transceiver = FindTransceiverBySender(sender);
1267 if (!transceiver || !sender->track()) {
1268 return RTCError::OK();
1269 }
1270 sender->SetTrack(nullptr);
1271 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001272 transceiver->internal()->set_direction(
1273 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001274 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001275 transceiver->internal()->set_direction(
1276 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001277 }
Steve Anton4171afb2017-11-20 10:20:22 -08001278 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001279 bool removed;
1280 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1281 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1282 } else {
1283 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1284 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1285 }
1286 if (!removed) {
1287 LOG_AND_RETURN_ERROR(
1288 RTCErrorType::INVALID_PARAMETER,
1289 "Couldn't find sender " + sender->id() + " to remove.");
1290 }
Steve Anton4171afb2017-11-20 10:20:22 -08001291 }
deadbeefe1f9d832016-01-14 15:35:42 -08001292 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001293 return RTCError::OK();
1294}
1295
1296rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1297PeerConnection::FindTransceiverBySender(
1298 rtc::scoped_refptr<RtpSenderInterface> sender) {
1299 for (auto transceiver : transceivers_) {
1300 if (transceiver->sender() == sender) {
1301 return transceiver;
1302 }
1303 }
1304 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001305}
1306
Steve Anton9158ef62017-11-27 13:01:52 -08001307RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1308PeerConnection::AddTransceiver(
1309 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1310 return AddTransceiver(track, RtpTransceiverInit());
1311}
1312
1313RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1314PeerConnection::AddTransceiver(
1315 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1316 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001317 RTC_CHECK(IsUnifiedPlan())
1318 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001319 if (!track) {
1320 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1321 }
1322 cricket::MediaType media_type;
1323 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1324 media_type = cricket::MEDIA_TYPE_AUDIO;
1325 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1326 media_type = cricket::MEDIA_TYPE_VIDEO;
1327 } else {
1328 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1329 "Track kind is not audio or video");
1330 }
1331 return AddTransceiver(media_type, track, init);
1332}
1333
1334RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1335PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1336 return AddTransceiver(media_type, RtpTransceiverInit());
1337}
1338
1339RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1340PeerConnection::AddTransceiver(cricket::MediaType media_type,
1341 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001342 RTC_CHECK(IsUnifiedPlan())
1343 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001344 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1345 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1347 "media type is not audio or video");
1348 }
1349 return AddTransceiver(media_type, nullptr, init);
1350}
1351
1352RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1353PeerConnection::AddTransceiver(
1354 cricket::MediaType media_type,
1355 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001356 const RtpTransceiverInit& init,
1357 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001358 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1359 media_type == cricket::MEDIA_TYPE_VIDEO));
1360 if (track) {
1361 RTC_DCHECK_EQ(media_type,
1362 (track->kind() == MediaStreamTrackInterface::kAudioKind
1363 ? cricket::MEDIA_TYPE_AUDIO
1364 : cricket::MEDIA_TYPE_VIDEO));
1365 }
1366
1367 // TODO(bugs.webrtc.org/7600): Verify init.
1368
Seth Hampsonf351c342018-03-29 15:45:58 -07001369 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001370 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1371 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1372 transceiver->internal()->set_direction(init.direction);
1373
Steve Anton22da89f2018-01-25 13:58:07 -08001374 if (fire_callback) {
1375 observer_->OnRenegotiationNeeded();
1376 }
Steve Antonf9381f02017-12-14 10:23:57 -08001377
1378 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1379}
1380
Steve Anton02ee47c2018-01-10 16:26:06 -08001381rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1382PeerConnection::CreateSender(
1383 cricket::MediaType media_type,
1384 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001385 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001386 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001387 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1388 RTC_DCHECK(!track ||
1389 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1390 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1391 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001392 new AudioRtpSender(worker_thread(),
1393 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001394 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 } else {
1396 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1397 RTC_DCHECK(!track ||
1398 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1399 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1400 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001401 new VideoRtpSender(worker_thread(),
1402 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001403 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001404 }
Seth Hampson845e8782018-03-02 11:34:10 -08001405 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001406 return sender;
1407}
1408
1409rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1410PeerConnection::CreateReceiver(cricket::MediaType media_type,
1411 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001412 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1413 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001414 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001415 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001416 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001417 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001418 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001419 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001420 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1421 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001422 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001423 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001424 return receiver;
1425}
1426
1427rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1428PeerConnection::CreateAndAddTransceiver(
1429 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1430 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1431 receiver) {
1432 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1433 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001434 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001435 transceiver->internal()->SignalNegotiationNeeded.connect(
1436 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001437 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001438}
1439
Steve Anton52d86772018-02-20 15:48:12 -08001440void PeerConnection::OnNegotiationNeeded() {
1441 RTC_DCHECK_RUN_ON(signaling_thread());
1442 RTC_DCHECK(!IsClosed());
1443 observer_->OnRenegotiationNeeded();
1444}
1445
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001446rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001448 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001449 if (IsClosed()) {
1450 return nullptr;
1451 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001452 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001453 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001454 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001455 }
Steve Anton4171afb2017-11-20 10:20:22 -08001456 auto track_sender = FindSenderForTrack(track);
1457 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001458 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001459 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001460 }
1461
Steve Anton4171afb2017-11-20 10:20:22 -08001462 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001463}
1464
deadbeeffac06552015-11-25 11:26:01 -08001465rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001466 const std::string& kind,
1467 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001468 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1469 "Plan SdpSemantics. Please use AddTransceiver "
1470 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001471 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001472 if (IsClosed()) {
1473 return nullptr;
1474 }
Steve Anton4171afb2017-11-20 10:20:22 -08001475
Seth Hampsonf351c342018-03-29 15:45:58 -07001476 // Internally we need to have one stream with Plan B semantics, so we
1477 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001478 std::vector<std::string> stream_ids;
Seth Hampsonf351c342018-03-29 15:45:58 -07001479 if (stream_id.empty()) {
1480 stream_ids.push_back(rtc::CreateRandomUuid());
1481 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001482 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001483 }
1484
Steve Anton4171afb2017-11-20 10:20:22 -08001485 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001486 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001487 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001488 auto* audio_sender =
1489 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001490 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001491 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001492 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001493 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001494 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001495 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001496 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001497 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001498 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001499 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001500 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001501 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001502 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001503 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001504 }
Steve Anton4171afb2017-11-20 10:20:22 -08001505
deadbeefe1f9d832016-01-14 15:35:42 -08001506 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001507}
1508
deadbeef70ab1a12015-09-28 16:53:55 -07001509std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1510 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001511 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001512 for (auto sender : GetSendersInternal()) {
1513 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001514 }
1515 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001516}
1517
Steve Anton4171afb2017-11-20 10:20:22 -08001518std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1519PeerConnection::GetSendersInternal() const {
1520 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1521 all_senders;
1522 for (auto transceiver : transceivers_) {
1523 auto senders = transceiver->internal()->senders();
1524 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1525 }
1526 return all_senders;
1527}
1528
deadbeef70ab1a12015-09-28 16:53:55 -07001529std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1530PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001531 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001532 for (const auto& receiver : GetReceiversInternal()) {
1533 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001534 }
1535 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001536}
1537
Steve Anton4171afb2017-11-20 10:20:22 -08001538std::vector<
1539 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1540PeerConnection::GetReceiversInternal() const {
1541 std::vector<
1542 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1543 all_receivers;
1544 for (auto transceiver : transceivers_) {
1545 auto receivers = transceiver->internal()->receivers();
1546 all_receivers.insert(all_receivers.end(), receivers.begin(),
1547 receivers.end());
1548 }
1549 return all_receivers;
1550}
1551
Steve Anton9158ef62017-11-27 13:01:52 -08001552std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1553PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001554 RTC_CHECK(IsUnifiedPlan())
1555 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001556 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1557 for (auto transceiver : transceivers_) {
1558 all_transceivers.push_back(transceiver);
1559 }
1560 return all_transceivers;
1561}
1562
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001563bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001564 MediaStreamTrackInterface* track,
1565 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001566 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001567 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001568 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001569 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001570 return false;
1571 }
1572
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001573 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001574 // The StatsCollector is used to tell if a track is valid because it may
1575 // remember tracks that the PeerConnection previously removed.
1576 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001577 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1578 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001579 return false;
1580 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001581 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001582 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583 return true;
1584}
1585
hbos74e1a4f2016-09-15 23:33:01 -07001586void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001587 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001588 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001589 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001590 stats_collector_->GetStatsReport(callback);
1591}
1592
Henrik Boström1df1bf82018-03-20 13:24:20 +01001593void PeerConnection::GetStats(
1594 rtc::scoped_refptr<RtpSenderInterface> selector,
1595 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1596 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1597 RTC_DCHECK(callback);
1598 RTC_DCHECK(stats_collector_);
1599 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1600 if (selector) {
1601 for (const auto& proxy_transceiver : transceivers_) {
1602 for (const auto& proxy_sender :
1603 proxy_transceiver->internal()->senders()) {
1604 if (proxy_sender == selector) {
1605 internal_sender = proxy_sender->internal();
1606 break;
1607 }
1608 }
1609 if (internal_sender)
1610 break;
1611 }
1612 }
1613 // If there is no |internal_sender| then |selector| is either null or does not
1614 // belong to the PeerConnection (in Plan B, senders can be removed from the
1615 // PeerConnection). This means that "all the stats objects representing the
1616 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1617 // produces an empty stats report.
1618 stats_collector_->GetStatsReport(internal_sender, callback);
1619}
1620
1621void PeerConnection::GetStats(
1622 rtc::scoped_refptr<RtpReceiverInterface> selector,
1623 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1624 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1625 RTC_DCHECK(callback);
1626 RTC_DCHECK(stats_collector_);
1627 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1628 if (selector) {
1629 for (const auto& proxy_transceiver : transceivers_) {
1630 for (const auto& proxy_receiver :
1631 proxy_transceiver->internal()->receivers()) {
1632 if (proxy_receiver == selector) {
1633 internal_receiver = proxy_receiver->internal();
1634 break;
1635 }
1636 }
1637 if (internal_receiver)
1638 break;
1639 }
1640 }
1641 // If there is no |internal_receiver| then |selector| is either null or does
1642 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1643 // the PeerConnection). This means that "all the stats objects representing
1644 // the selector" is an empty set. Invoking GetStatsReport() with a null
1645 // selector produces an empty stats report.
1646 stats_collector_->GetStatsReport(internal_receiver, callback);
1647}
1648
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001649PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1650 return signaling_state_;
1651}
1652
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001653PeerConnectionInterface::IceConnectionState
1654PeerConnection::ice_connection_state() {
1655 return ice_connection_state_;
1656}
1657
1658PeerConnectionInterface::IceGatheringState
1659PeerConnection::ice_gathering_state() {
1660 return ice_gathering_state_;
1661}
1662
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001663rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001664PeerConnection::CreateDataChannel(
1665 const std::string& label,
1666 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001667 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001668
deadbeefab9b2d12015-10-14 11:33:11 -07001669 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001670
kwibergd1fe2812016-04-27 06:47:29 -07001671 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001672 if (config) {
1673 internal_config.reset(new InternalDataChannelInit(*config));
1674 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001675 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001676 InternalCreateDataChannel(label, internal_config.get()));
1677 if (!channel.get()) {
1678 return nullptr;
1679 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001681 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1682 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001683 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001684 observer_->OnRenegotiationNeeded();
1685 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001686
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687 return DataChannelProxy::Create(signaling_thread(), channel.get());
1688}
1689
1690void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1691 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001692 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001693
zhihuang1c378ed2017-08-17 14:10:50 -07001694 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1695 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1696 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1697 // compares the mandatory fields parsed with the mandatory fields added in the
1698 // |constraints| and some downstream applications might create offers with
1699 // mandatory fields which would not be parsed in the helper method. For
1700 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1701 // |constraints| as a mandatory field but it is not parsed.
1702 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001703
zhihuang1c378ed2017-08-17 14:10:50 -07001704 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001705}
1706
1707void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1708 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001709 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001710
nisse7ce109a2017-01-31 00:57:56 -08001711 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001712 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001713 return;
1714 }
deadbeefab9b2d12015-10-14 11:33:11 -07001715
Steve Anton8d3444d2017-10-20 15:30:51 -07001716 if (IsClosed()) {
1717 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001718 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001719 PostCreateSessionDescriptionFailure(
1720 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001721 return;
1722 }
1723
zhihuang1c378ed2017-08-17 14:10:50 -07001724 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001725 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001726 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001727 PostCreateSessionDescriptionFailure(
1728 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001729 return;
1730 }
1731
Steve Anton22da89f2018-01-25 13:58:07 -08001732 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1733 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1734 if (IsUnifiedPlan()) {
1735 RTCError error = HandleLegacyOfferOptions(options);
1736 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001737 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001738 return;
1739 }
1740 }
1741
zhihuang1c378ed2017-08-17 14:10:50 -07001742 cricket::MediaSessionOptions session_options;
1743 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001744 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001745}
1746
Steve Anton22da89f2018-01-25 13:58:07 -08001747RTCError PeerConnection::HandleLegacyOfferOptions(
1748 const RTCOfferAnswerOptions& options) {
1749 RTC_DCHECK(IsUnifiedPlan());
1750
1751 if (options.offer_to_receive_audio == 0) {
1752 RemoveRecvDirectionFromReceivingTransceiversOfType(
1753 cricket::MEDIA_TYPE_AUDIO);
1754 } else if (options.offer_to_receive_audio == 1) {
1755 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1756 } else if (options.offer_to_receive_audio > 1) {
1757 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1758 "offer_to_receive_audio > 1 is not supported.");
1759 }
1760
1761 if (options.offer_to_receive_video == 0) {
1762 RemoveRecvDirectionFromReceivingTransceiversOfType(
1763 cricket::MEDIA_TYPE_VIDEO);
1764 } else if (options.offer_to_receive_video == 1) {
1765 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1766 } else if (options.offer_to_receive_video > 1) {
1767 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1768 "offer_to_receive_video > 1 is not supported.");
1769 }
1770
1771 return RTCError::OK();
1772}
1773
1774void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1775 cricket::MediaType media_type) {
1776 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
1777 transceiver->internal()->set_direction(
1778 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false));
1779 }
1780}
1781
1782void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1783 cricket::MediaType media_type) {
1784 if (GetReceivingTransceiversOfType(media_type).empty()) {
1785 RtpTransceiverInit init;
1786 init.direction = RtpTransceiverDirection::kRecvOnly;
1787 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1788 }
1789}
1790
1791std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1792PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1793 std::vector<
1794 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1795 receiving_transceivers;
1796 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001797 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001798 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1799 receiving_transceivers.push_back(transceiver);
1800 }
1801 }
1802 return receiving_transceivers;
1803}
1804
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001805void PeerConnection::CreateAnswer(
1806 CreateSessionDescriptionObserver* observer,
1807 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001808 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001809
nisse7ce109a2017-01-31 00:57:56 -08001810 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001811 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001812 return;
1813 }
deadbeefab9b2d12015-10-14 11:33:11 -07001814
zhihuang1c378ed2017-08-17 14:10:50 -07001815 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1816 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1817 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001818 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001819 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001820 PostCreateSessionDescriptionFailure(
1821 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001822 return;
1823 }
1824
Steve Anton8d3444d2017-10-20 15:30:51 -07001825 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001826}
1827
1828void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1829 const RTCOfferAnswerOptions& options) {
1830 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001831 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001832 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001833 return;
1834 }
1835
Steve Antondffead82018-02-06 10:31:29 -08001836 if (!(signaling_state_ == kHaveRemoteOffer ||
1837 signaling_state_ == kHaveLocalPrAnswer)) {
1838 std::string error =
1839 "PeerConnection cannot create an answer in a state other than "
1840 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001841 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001842 PostCreateSessionDescriptionFailure(
1843 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001844 return;
1845 }
1846
Steve Antondffead82018-02-06 10:31:29 -08001847 // The remote description should be set if we're in the right state.
1848 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001849
Steve Anton22da89f2018-01-25 13:58:07 -08001850 if (IsUnifiedPlan()) {
1851 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1852 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1853 "supported with Unified Plan semantics. Use the "
1854 "RtpTransceiver API instead.";
1855 }
1856 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1857 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1858 "supported with Unified Plan semantics. Use the "
1859 "RtpTransceiver API instead.";
1860 }
1861 }
1862
htaa2a49d92016-03-04 02:51:39 -08001863 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001864 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001865
Steve Antond25da372017-11-06 14:50:29 -08001866 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001867}
1868
1869void PeerConnection::SetLocalDescription(
1870 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001871 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001872 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001873
Steve Anton80dd7b52018-02-16 17:08:42 -08001874 // The SetLocalDescription contract is that we take ownership of the session
1875 // description regardless of the outcome, so wrap it in a unique_ptr right
1876 // away. Ideally, SetLocalDescription's signature will be changed to take the
1877 // description as a unique_ptr argument to formalize this agreement.
1878 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1879
nisse7ce109a2017-01-31 00:57:56 -08001880 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001881 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001882 return;
1883 }
Steve Anton8a006912017-12-04 15:25:56 -08001884
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001885 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001886 PostSetSessionDescriptionFailure(
1887 observer,
1888 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001889 return;
1890 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001891
Steve Anton80dd7b52018-02-16 17:08:42 -08001892 // If a session error has occurred the PeerConnection is in a possibly
1893 // inconsistent state so fail right away.
1894 if (session_error() != SessionError::kNone) {
1895 std::string error_message = GetSessionErrorMsg();
1896 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001897 PostSetSessionDescriptionFailure(
1898 observer,
1899 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001900 return;
1901 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001902
Steve Anton80dd7b52018-02-16 17:08:42 -08001903 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1904 if (!error.ok()) {
1905 std::string error_message = GetSetDescriptionErrorMessage(
1906 cricket::CS_LOCAL, desc->GetType(), error);
1907 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001908 PostSetSessionDescriptionFailure(
1909 observer,
1910 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001911 return;
1912 }
1913
1914 // Grab the description type before moving ownership to ApplyLocalDescription,
1915 // which may destroy it before returning.
1916 const SdpType type = desc->GetType();
1917
1918 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001919 // |desc| may be destroyed at this point.
1920
1921 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001922 // If ApplyLocalDescription fails, the PeerConnection could be in an
1923 // inconsistent state, so act conservatively here and set the session error
1924 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1925 SetSessionError(SessionError::kContent, error.message());
1926 std::string error_message =
1927 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1928 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001929 PostSetSessionDescriptionFailure(
1930 observer,
1931 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001932 return;
1933 }
Steve Anton8a006912017-12-04 15:25:56 -08001934 RTC_DCHECK(local_description());
1935
1936 PostSetSessionDescriptionSuccess(observer);
1937
1938 // According to JSEP, after setLocalDescription, changing the candidate pool
1939 // size is not allowed, and changing the set of ICE servers will not result
1940 // in new candidates being gathered.
1941 port_allocator_->FreezeCandidatePool();
1942
1943 // MaybeStartGathering needs to be called after posting
1944 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1945 // before signaling that SetLocalDescription completed.
1946 transport_controller_->MaybeStartGathering();
1947
Steve Antona3a92c22017-12-07 10:27:41 -08001948 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001949 // TODO(deadbeef): We already had to hop to the network thread for
1950 // MaybeStartGathering...
1951 network_thread()->Invoke<void>(
1952 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1953 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001954 // Make UMA notes about what was agreed to.
1955 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001956 }
1957}
1958
1959RTCError PeerConnection::ApplyLocalDescription(
1960 std::unique_ptr<SessionDescriptionInterface> desc) {
1961 RTC_DCHECK_RUN_ON(signaling_thread());
1962 RTC_DCHECK(desc);
1963
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001964 // Update stats here so that we have the most recent stats for tracks and
1965 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001966 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001967
1968 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001969 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001970 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001971 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001972 if (*initial_offerer_) {
1973 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1974 } else {
1975 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1976 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 }
Steve Anton8a006912017-12-04 15:25:56 -08001978
Steve Antondcc3c022017-12-22 16:02:54 -08001979 // Take a reference to the old local description since it's used below to
1980 // compare against the new local description. When setting the new local
1981 // description, grab ownership of the replaced session description in case it
1982 // is the same as |old_local_description|, to keep it alive for the duration
1983 // of the method.
1984 const SessionDescriptionInterface* old_local_description =
1985 local_description();
1986 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001987 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001988 replaced_local_description = pending_local_description_
1989 ? std::move(pending_local_description_)
1990 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001991 current_local_description_ = std::move(desc);
1992 pending_local_description_ = nullptr;
1993 current_remote_description_ = std::move(pending_remote_description_);
1994 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001995 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001996 pending_local_description_ = std::move(desc);
1997 }
1998 // The session description to apply now must be accessed by
1999 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002000 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002001
Steve Antondcc3c022017-12-22 16:02:54 -08002002 if (IsUnifiedPlan()) {
2003 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002004 cricket::CS_LOCAL, *local_description(), old_local_description,
2005 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002006 if (!error.ok()) {
2007 return error;
2008 }
Steve Antondcc3c022017-12-22 16:02:54 -08002009 for (auto transceiver : transceivers_) {
2010 const ContentInfo* content =
2011 FindMediaSectionForTransceiver(transceiver, local_description());
2012 if (!content) {
2013 continue;
2014 }
2015 const MediaContentDescription* media_desc = content->media_description();
2016 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2017 transceiver->internal()->set_current_direction(media_desc->direction());
2018 }
2019 if (content->rejected && !transceiver->stopped()) {
2020 transceiver->Stop();
2021 }
2022 }
2023 } else {
2024 // Transport and Media channels will be created only when offer is set.
2025 if (type == SdpType::kOffer) {
2026 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2027 // description is applied. Restore back to old description.
2028 RTCError error = CreateChannels(*local_description()->description());
2029 if (!error.ok()) {
2030 return error;
2031 }
2032 }
Steve Anton8a006912017-12-04 15:25:56 -08002033
Steve Antondcc3c022017-12-22 16:02:54 -08002034 // Remove unused channels if MediaContentDescription is rejected.
2035 RemoveUnusedChannels(local_description()->description());
2036 }
Steve Anton8a006912017-12-04 15:25:56 -08002037
Steve Anton80dd7b52018-02-16 17:08:42 -08002038 RTCError error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08002039 if (!error.ok()) {
2040 return error;
2041 }
Steve Antondcc3c022017-12-22 16:02:54 -08002042
Steve Anton8a006912017-12-04 15:25:56 -08002043 if (remote_description()) {
2044 // Now that we have a local description, we can push down remote candidates.
2045 UseCandidatesInSessionDescription(remote_description());
2046 }
2047
2048 pending_ice_restarts_.clear();
2049 if (session_error() != SessionError::kNone) {
2050 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2051 }
2052
deadbeefab9b2d12015-10-14 11:33:11 -07002053 // If setting the description decided our SSL role, allocate any necessary
2054 // SCTP sids.
2055 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002056 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002057 AllocateSctpSids(role);
2058 }
2059
Steve Antond3679212018-01-17 17:41:02 -08002060 if (IsUnifiedPlan()) {
2061 for (auto transceiver : transceivers_) {
2062 const ContentInfo* content =
2063 FindMediaSectionForTransceiver(transceiver, local_description());
2064 if (!content) {
2065 continue;
2066 }
2067 if (content->rejected && !transceiver->stopped()) {
2068 transceiver->Stop();
2069 }
Steve Anton74255ff2018-01-24 18:32:57 -08002070 const auto& streams = content->media_description()->streams();
2071 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002072 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002073 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002074 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002075 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002076 }
2077 }
2078 } else {
2079 // Plan B semantics.
2080
Steve Antondcc3c022017-12-22 16:02:54 -08002081 // Update state and SSRC of local MediaStreams and DataChannels based on the
2082 // local session description.
2083 const cricket::ContentInfo* audio_content =
2084 GetFirstAudioContent(local_description()->description());
2085 if (audio_content) {
2086 if (audio_content->rejected) {
2087 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2088 } else {
2089 const cricket::AudioContentDescription* audio_desc =
2090 audio_content->media_description()->as_audio();
2091 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2092 }
deadbeeffaac4972015-11-12 15:33:07 -08002093 }
deadbeefab9b2d12015-10-14 11:33:11 -07002094
Steve Antondcc3c022017-12-22 16:02:54 -08002095 const cricket::ContentInfo* video_content =
2096 GetFirstVideoContent(local_description()->description());
2097 if (video_content) {
2098 if (video_content->rejected) {
2099 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2100 } else {
2101 const cricket::VideoContentDescription* video_desc =
2102 video_content->media_description()->as_video();
2103 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2104 }
deadbeeffaac4972015-11-12 15:33:07 -08002105 }
deadbeefab9b2d12015-10-14 11:33:11 -07002106 }
2107
2108 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002109 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002110 if (data_content) {
2111 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002112 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002113 if (rtc::starts_with(data_desc->protocol().data(),
2114 cricket::kMediaProtocolRtpPrefix)) {
2115 UpdateLocalRtpDataChannels(data_desc->streams());
2116 }
2117 }
2118
Steve Anton8a006912017-12-04 15:25:56 -08002119 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002120}
2121
2122void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002123 SetSessionDescriptionObserver* observer,
2124 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002125 SetRemoteDescription(
2126 std::unique_ptr<SessionDescriptionInterface>(desc),
2127 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2128 new SetRemoteDescriptionObserverAdapter(this, observer)));
2129}
2130
2131void PeerConnection::SetRemoteDescription(
2132 std::unique_ptr<SessionDescriptionInterface> desc,
2133 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002134 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002135
nisse7ce109a2017-01-31 00:57:56 -08002136 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002137 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002138 return;
2139 }
Steve Anton8a006912017-12-04 15:25:56 -08002140
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002142 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002143 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144 return;
2145 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002146
Steve Anton80dd7b52018-02-16 17:08:42 -08002147 // If a session error has occurred the PeerConnection is in a possibly
2148 // inconsistent state so fail right away.
2149 if (session_error() != SessionError::kNone) {
2150 std::string error_message = GetSessionErrorMsg();
2151 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2152 observer->OnSetRemoteDescriptionComplete(
2153 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2154 return;
2155 }
Steve Anton71439a62018-02-15 11:53:06 -08002156
Steve Anton80dd7b52018-02-16 17:08:42 -08002157 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002158 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002159 std::string error_message = GetSetDescriptionErrorMessage(
2160 cricket::CS_REMOTE, desc->GetType(), error);
2161 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002162 observer->OnSetRemoteDescriptionComplete(
2163 RTCError(error.type(), std::move(error_message)));
2164 return;
2165 }
Steve Anton71439a62018-02-15 11:53:06 -08002166
Steve Anton80dd7b52018-02-16 17:08:42 -08002167 // Grab the description type before moving ownership to
2168 // ApplyRemoteDescription, which may destroy it before returning.
2169 const SdpType type = desc->GetType();
2170
2171 error = ApplyRemoteDescription(std::move(desc));
2172 // |desc| may be destroyed at this point.
2173
2174 if (!error.ok()) {
2175 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2176 // inconsistent state, so act conservatively here and set the session error
2177 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2178 SetSessionError(SessionError::kContent, error.message());
2179 std::string error_message =
2180 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2181 RTC_LOG(LS_ERROR) << error_message;
2182 observer->OnSetRemoteDescriptionComplete(
2183 RTCError(error.type(), std::move(error_message)));
2184 return;
2185 }
2186 RTC_DCHECK(remote_description());
2187
Steve Anton8e20f172018-03-06 10:55:04 -08002188 if (type == SdpType::kOffer) {
2189 // Report to UMA the format of the received offer.
2190 ReportSdpFormatReceived(*remote_description());
2191 }
2192
Steve Anton80dd7b52018-02-16 17:08:42 -08002193 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002194 // TODO(deadbeef): We already had to hop to the network thread for
2195 // MaybeStartGathering...
2196 network_thread()->Invoke<void>(
2197 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2198 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002199 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002200 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002201 }
2202
2203 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2204}
2205
2206RTCError PeerConnection::ApplyRemoteDescription(
2207 std::unique_ptr<SessionDescriptionInterface> desc) {
2208 RTC_DCHECK_RUN_ON(signaling_thread());
2209 RTC_DCHECK(desc);
2210
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 // Update stats here so that we have the most recent stats for tracks and
2212 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002213 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002214
Steve Antondcc3c022017-12-22 16:02:54 -08002215 // Take a reference to the old remote description since it's used below to
2216 // compare against the new remote description. When setting the new remote
2217 // description, grab ownership of the replaced session description in case it
2218 // is the same as |old_remote_description|, to keep it alive for the duration
2219 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002220 const SessionDescriptionInterface* old_remote_description =
2221 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002222 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002223 SdpType type = desc->GetType();
2224 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002225 replaced_remote_description = pending_remote_description_
2226 ? std::move(pending_remote_description_)
2227 : std::move(current_remote_description_);
2228 current_remote_description_ = std::move(desc);
2229 pending_remote_description_ = nullptr;
2230 current_local_description_ = std::move(pending_local_description_);
2231 } else {
2232 replaced_remote_description = std::move(pending_remote_description_);
2233 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234 }
Steve Anton8a006912017-12-04 15:25:56 -08002235 // The session description to apply now must be accessed by
2236 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002237 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238
Steve Anton8a006912017-12-04 15:25:56 -08002239 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002240 if (IsUnifiedPlan()) {
2241 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002242 cricket::CS_REMOTE, *remote_description(), local_description(),
2243 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002244 if (!error.ok()) {
2245 return error;
2246 }
Steve Antondcc3c022017-12-22 16:02:54 -08002247 } else {
2248 if (type == SdpType::kOffer) {
2249 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2250 // description is applied. Restore back to old description.
2251 RTCError error = CreateChannels(*remote_description()->description());
2252 if (!error.ok()) {
2253 return error;
2254 }
2255 }
Steve Anton8a006912017-12-04 15:25:56 -08002256
Steve Antondcc3c022017-12-22 16:02:54 -08002257 // Remove unused channels if MediaContentDescription is rejected.
2258 RemoveUnusedChannels(remote_description()->description());
2259 }
Steve Anton8a006912017-12-04 15:25:56 -08002260
2261 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
2262 // is called.
Steve Anton80dd7b52018-02-16 17:08:42 -08002263 RTCError error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08002264 if (!error.ok()) {
2265 return error;
2266 }
2267
2268 if (local_description() &&
2269 !UseCandidatesInSessionDescription(remote_description())) {
2270 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2271 }
2272
2273 if (old_remote_description) {
2274 for (const cricket::ContentInfo& content :
2275 old_remote_description->description()->contents()) {
2276 // Check if this new SessionDescription contains new ICE ufrag and
2277 // password that indicates the remote peer requests an ICE restart.
2278 // TODO(deadbeef): When we start storing both the current and pending
2279 // remote description, this should reset pending_ice_restarts and compare
2280 // against the current description.
2281 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2282 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002283 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002284 pending_ice_restarts_.insert(content.name);
2285 }
2286 } else {
2287 // We retain all received candidates only if ICE is not restarted.
2288 // When ICE is restarted, all previous candidates belong to an old
2289 // generation and should not be kept.
2290 // TODO(deadbeef): This goes against the W3C spec which says the remote
2291 // description should only contain candidates from the last set remote
2292 // description plus any candidates added since then. We should remove
2293 // this once we're sure it won't break anything.
2294 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2295 old_remote_description, content.name, mutable_remote_description());
2296 }
2297 }
2298 }
2299
2300 if (session_error() != SessionError::kNone) {
2301 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2302 }
2303
2304 // Set the the ICE connection state to connecting since the connection may
2305 // become writable with peer reflexive candidates before any remote candidate
2306 // is signaled.
2307 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2308 // is to have a new signal the indicates a change in checking state from the
2309 // transport and expose a new checking() member from transport that can be
2310 // read to determine the current checking state. The existing SignalConnecting
2311 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002312 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002313 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2314 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2315 }
2316
deadbeefab9b2d12015-10-14 11:33:11 -07002317 // If setting the description decided our SSL role, allocate any necessary
2318 // SCTP sids.
2319 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002320 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002321 AllocateSctpSids(role);
2322 }
2323
Steve Antondcc3c022017-12-22 16:02:54 -08002324 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002325 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2326 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002327 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002328 for (auto transceiver : transceivers_) {
2329 const ContentInfo* content =
2330 FindMediaSectionForTransceiver(transceiver, remote_description());
2331 if (!content) {
2332 continue;
2333 }
2334 const MediaContentDescription* media_desc = content->media_description();
2335 RtpTransceiverDirection local_direction =
2336 RtpTransceiverDirectionReversed(media_desc->direction());
2337 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2338 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2339 // transceiver's current direction is neither sendrecv nor recvonly,
2340 // process the addition of a remote track for the media description.
Seth Hampsonf351c342018-03-29 15:45:58 -07002341 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002342 if (!media_desc->streams().empty()) {
Seth Hampsonf351c342018-03-29 15:45:58 -07002343 // TODO(bugs.webrtc.org/7932): Currently stream ids are all populated
2344 // within StreamParams. When they are updated to be stored within the
2345 // MediaContentDescription, change the logic here.
Steve Anton5a26a3a2018-02-28 11:38:47 -08002346 const cricket::StreamParams& stream_params = media_desc->streams()[0];
Seth Hampson845e8782018-03-02 11:34:10 -08002347 if (!stream_params.stream_ids().empty()) {
Seth Hampsonf351c342018-03-29 15:45:58 -07002348 stream_ids = stream_params.stream_ids();
Steve Anton5a26a3a2018-02-28 11:38:47 -08002349 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002350 }
Steve Antondcc3c022017-12-22 16:02:54 -08002351 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2352 (!transceiver->current_direction() ||
2353 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002354 *transceiver->current_direction()))) {
Seth Hampsonf351c342018-03-29 15:45:58 -07002355 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2356 for (const std::string& stream_id : stream_ids) {
2357 rtc::scoped_refptr<MediaStreamInterface> stream =
2358 remote_streams_->find(stream_id);
2359 if (!stream) {
2360 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2361 MediaStream::Create(stream_id));
2362 remote_streams_->AddStream(stream);
2363 added_streams.push_back(stream);
2364 }
2365 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002366 }
Seth Hampsonf351c342018-03-29 15:45:58 -07002367 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton8b815cd2018-02-16 16:14:42 -08002368 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002369 }
2370 // If direction is sendonly or inactive, and transceiver's current
2371 // direction is neither sendonly nor inactive, process the removal of a
2372 // remote track for the media description.
2373 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002374 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002375 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002376 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002377 }
2378 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2379 transceiver->internal()->set_current_direction(local_direction);
2380 }
2381 if (content->rejected && !transceiver->stopped()) {
2382 transceiver->Stop();
2383 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002384 if (!content->rejected &&
2385 RtpTransceiverDirectionHasRecv(local_direction)) {
2386 // Set ssrc to 0 in the case of an unsignalled ssrc.
2387 uint32_t ssrc = 0;
2388 if (!media_desc->streams().empty()) {
2389 ssrc = media_desc->streams()[0].first_ssrc();
2390 }
2391 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002392 }
Steve Antondcc3c022017-12-22 16:02:54 -08002393 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002394 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002395 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002396 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002397 observer_->OnTrack(transceiver);
2398 observer_->OnAddTrack(transceiver->receiver(),
2399 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002400 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002401 for (auto stream : added_streams) {
2402 observer_->OnAddStream(stream);
2403 }
Steve Antondcc3c022017-12-22 16:02:54 -08002404 }
2405
Henrik Boströmfdb92012017-11-09 19:55:44 +01002406 const cricket::ContentInfo* audio_content =
2407 GetFirstAudioContent(remote_description()->description());
2408 const cricket::ContentInfo* video_content =
2409 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002410 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002411 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002412 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002413 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002414 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002415 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002416
2417 // Check if the descriptions include streams, just in case the peer supports
2418 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002419 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002420 (audio_desc && !audio_desc->streams().empty()) ||
2421 (video_desc && !video_desc->streams().empty())) {
2422 remote_peer_supports_msid_ = true;
2423 }
deadbeefab9b2d12015-10-14 11:33:11 -07002424
2425 // We wait to signal new streams until we finish processing the description,
2426 // since only at that point will new streams have all their tracks.
2427 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2428
Steve Antondcc3c022017-12-22 16:02:54 -08002429 if (!IsUnifiedPlan()) {
2430 // TODO(steveanton): When removing RTP senders/receivers in response to a
2431 // rejected media section, there is some cleanup logic that expects the
2432 // voice/ video channel to still be set. But in this method the voice/video
2433 // channel would have been destroyed by the SetRemoteDescription caller
2434 // above so the cleanup that relies on them fails to run. The RemoveSenders
2435 // calls should be moved to right before the DestroyChannel calls to fix
2436 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002437
Steve Antondcc3c022017-12-22 16:02:54 -08002438 // Find all audio rtp streams and create corresponding remote AudioTracks
2439 // and MediaStreams.
2440 if (audio_content) {
2441 if (audio_content->rejected) {
2442 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2443 } else {
2444 bool default_audio_track_needed =
2445 !remote_peer_supports_msid_ &&
2446 RtpTransceiverDirectionHasSend(audio_desc->direction());
2447 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2448 default_audio_track_needed, audio_desc->type(),
2449 new_streams);
2450 }
deadbeeffaac4972015-11-12 15:33:07 -08002451 }
deadbeefab9b2d12015-10-14 11:33:11 -07002452
Steve Antondcc3c022017-12-22 16:02:54 -08002453 // Find all video rtp streams and create corresponding remote VideoTracks
2454 // and MediaStreams.
2455 if (video_content) {
2456 if (video_content->rejected) {
2457 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2458 } else {
2459 bool default_video_track_needed =
2460 !remote_peer_supports_msid_ &&
2461 RtpTransceiverDirectionHasSend(video_desc->direction());
2462 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2463 default_video_track_needed, video_desc->type(),
2464 new_streams);
2465 }
deadbeeffaac4972015-11-12 15:33:07 -08002466 }
deadbeefab9b2d12015-10-14 11:33:11 -07002467
Steve Antondcc3c022017-12-22 16:02:54 -08002468 // Update the DataChannels with the information from the remote peer.
2469 if (data_desc) {
2470 if (rtc::starts_with(data_desc->protocol().data(),
2471 cricket::kMediaProtocolRtpPrefix)) {
2472 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2473 }
deadbeefab9b2d12015-10-14 11:33:11 -07002474 }
deadbeefab9b2d12015-10-14 11:33:11 -07002475
Steve Antondcc3c022017-12-22 16:02:54 -08002476 // Iterate new_streams and notify the observer about new MediaStreams.
2477 for (size_t i = 0; i < new_streams->count(); ++i) {
2478 MediaStreamInterface* new_stream = new_streams->at(i);
2479 stats_->AddStream(new_stream);
2480 observer_->OnAddStream(
2481 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2482 }
deadbeefab9b2d12015-10-14 11:33:11 -07002483
Steve Antondcc3c022017-12-22 16:02:54 -08002484 UpdateEndedRemoteMediaStreams();
2485 }
deadbeefab9b2d12015-10-14 11:33:11 -07002486
Steve Anton8a006912017-12-04 15:25:56 -08002487 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002488}
2489
Steve Antondcc3c022017-12-22 16:02:54 -08002490RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2491 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002492 const SessionDescriptionInterface& new_session,
2493 const SessionDescriptionInterface* old_local_description,
2494 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002495 RTC_DCHECK(IsUnifiedPlan());
2496
Steve Anton7464fca2018-01-19 11:10:37 -08002497 const cricket::ContentGroup* bundle_group = nullptr;
2498 if (new_session.GetType() == SdpType::kOffer) {
2499 auto bundle_group_or_error =
2500 GetEarlyBundleGroup(*new_session.description());
2501 if (!bundle_group_or_error.ok()) {
2502 return bundle_group_or_error.MoveError();
2503 }
2504 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002505 }
Steve Antondcc3c022017-12-22 16:02:54 -08002506
Steve Antondcc3c022017-12-22 16:02:54 -08002507 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002508 for (size_t i = 0; i < new_contents.size(); ++i) {
2509 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002510 cricket::MediaType media_type = new_content.media_description()->type();
2511 seen_mids_.insert(new_content.name);
2512 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2513 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002514 const cricket::ContentInfo* old_local_content = nullptr;
2515 if (old_local_description &&
2516 i < old_local_description->description()->contents().size()) {
2517 old_local_content =
2518 &old_local_description->description()->contents()[i];
2519 }
2520 const cricket::ContentInfo* old_remote_content = nullptr;
2521 if (old_remote_description &&
2522 i < old_remote_description->description()->contents().size()) {
2523 old_remote_content =
2524 &old_remote_description->description()->contents()[i];
2525 }
Steve Antondcc3c022017-12-22 16:02:54 -08002526 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002527 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2528 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002529 if (!transceiver_or_error.ok()) {
2530 return transceiver_or_error.MoveError();
2531 }
2532 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002533 RTCError error =
2534 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2535 if (!error.ok()) {
2536 return error;
2537 }
2538 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002539 if (GetDataMid() && new_content.name != *GetDataMid()) {
2540 // Ignore all but the first data section.
2541 continue;
2542 }
2543 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2544 if (!error.ok()) {
2545 return error;
2546 }
Steve Antondcc3c022017-12-22 16:02:54 -08002547 } else {
2548 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2549 "Unknown section type.");
2550 }
2551 }
2552
2553 return RTCError::OK();
2554}
2555
2556RTCError PeerConnection::UpdateTransceiverChannel(
2557 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2558 transceiver,
2559 const cricket::ContentInfo& content,
2560 const cricket::ContentGroup* bundle_group) {
2561 RTC_DCHECK(IsUnifiedPlan());
2562 RTC_DCHECK(transceiver);
2563 cricket::BaseChannel* channel = transceiver->internal()->channel();
2564 if (content.rejected) {
2565 if (channel) {
2566 transceiver->internal()->SetChannel(nullptr);
2567 DestroyBaseChannel(channel);
2568 }
2569 } else {
2570 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002571 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Antondcc3c022017-12-22 16:02:54 -08002572 channel = CreateVoiceChannel(
2573 content.name,
2574 GetTransportNameForMediaSection(content.name, bundle_group));
2575 } else {
Steve Anton69470252018-02-09 11:43:08 -08002576 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Steve Antondcc3c022017-12-22 16:02:54 -08002577 channel = CreateVideoChannel(
2578 content.name,
2579 GetTransportNameForMediaSection(content.name, bundle_group));
2580 }
2581 if (!channel) {
2582 LOG_AND_RETURN_ERROR(
2583 RTCErrorType::INTERNAL_ERROR,
2584 "Failed to create channel for mid=" + content.name);
2585 }
2586 transceiver->internal()->SetChannel(channel);
2587 }
2588 }
2589 return RTCError::OK();
2590}
2591
Steve Antonfa2260d2017-12-28 16:38:23 -08002592RTCError PeerConnection::UpdateDataChannel(
2593 cricket::ContentSource source,
2594 const cricket::ContentInfo& content,
2595 const cricket::ContentGroup* bundle_group) {
2596 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002597 // If data channels are disabled, ignore this media section. CreateAnswer
2598 // will take care of rejecting it.
2599 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002600 }
2601 if (content.rejected) {
2602 DestroyDataChannel();
2603 } else {
2604 if (!rtp_data_channel_ && !sctp_transport_) {
2605 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2606 content.name, bundle_group))) {
2607 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2608 "Failed to create data channel.");
2609 }
2610 }
2611 if (source == cricket::CS_REMOTE) {
2612 const MediaContentDescription* data_desc = content.media_description();
2613 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2614 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2615 }
2616 }
2617 }
2618 return RTCError::OK();
2619}
2620
Steve Antondcc3c022017-12-22 16:02:54 -08002621RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2622PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002623 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002624 size_t mline_index,
2625 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002626 const ContentInfo* old_local_content,
2627 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002628 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002629 // If this is an offer then the m= section might be recycled. If the m=
2630 // section is being recycled (defined as: rejected in the current local or
2631 // remote description and not rejected in new description), dissociate the
2632 // currently associated RtpTransceiver by setting its mid property to null,
2633 // and discard the mapping between the transceiver and its m= section index.
2634 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2635 old_remote_content)) {
2636 // We want to dissociate the transceiver that has the rejected mid.
2637 const std::string& old_mid =
2638 (old_local_content && old_local_content->rejected)
2639 ? old_local_content->name
2640 : old_remote_content->name;
2641 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002642 if (old_transceiver) {
2643 old_transceiver->internal()->set_mid(rtc::nullopt);
2644 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2645 }
2646 }
2647 const MediaContentDescription* media_desc = content.media_description();
2648 auto transceiver = GetAssociatedTransceiver(content.name);
2649 if (source == cricket::CS_LOCAL) {
2650 // Find the RtpTransceiver that corresponds to this m= section, using the
2651 // mapping between transceivers and m= section indices established when
2652 // creating the offer.
2653 if (!transceiver) {
2654 transceiver = GetTransceiverByMLineIndex(mline_index);
2655 }
2656 if (!transceiver) {
2657 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2658 "Unknown transceiver");
2659 }
2660 } else {
2661 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2662 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2663 // of the same type...
2664 if (!transceiver &&
2665 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2666 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2667 }
2668 // If no RtpTransceiver was found in the previous step, create one with a
2669 // recvonly direction.
2670 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002671 auto sender =
2672 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002673 std::string receiver_id;
2674 if (!media_desc->streams().empty()) {
2675 receiver_id = media_desc->streams()[0].id;
2676 } else {
2677 receiver_id = rtc::CreateRandomUuid();
2678 }
2679 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002680 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002681 transceiver->internal()->set_direction(
2682 RtpTransceiverDirection::kRecvOnly);
2683 }
2684 }
2685 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002686 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002687 LOG_AND_RETURN_ERROR(
2688 RTCErrorType::INVALID_PARAMETER,
2689 "Transceiver type does not match media description type.");
2690 }
2691 // Associate the found or created RtpTransceiver with the m= section by
2692 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2693 // section, and establish a mapping between the transceiver and the index of
2694 // the m= section.
2695 transceiver->internal()->set_mid(content.name);
2696 transceiver->internal()->set_mline_index(mline_index);
2697 return std::move(transceiver);
2698}
2699
2700rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2701PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2702 RTC_DCHECK(IsUnifiedPlan());
2703 for (auto transceiver : transceivers_) {
2704 if (transceiver->mid() == mid) {
2705 return transceiver;
2706 }
2707 }
2708 return nullptr;
2709}
2710
2711rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2712PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2713 RTC_DCHECK(IsUnifiedPlan());
2714 for (auto transceiver : transceivers_) {
2715 if (transceiver->internal()->mline_index() == mline_index) {
2716 return transceiver;
2717 }
2718 }
2719 return nullptr;
2720}
2721
2722rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2723PeerConnection::FindAvailableTransceiverToReceive(
2724 cricket::MediaType media_type) const {
2725 RTC_DCHECK(IsUnifiedPlan());
2726 // From JSEP section 5.10 (Applying a Remote Description):
2727 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2728 // the same type that were added to the PeerConnection by addTrack and are not
2729 // associated with any m= section and are not stopped, find the first such
2730 // RtpTransceiver.
2731 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002732 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002733 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2734 !transceiver->stopped()) {
2735 return transceiver;
2736 }
2737 }
2738 return nullptr;
2739}
2740
Steve Antoned10bd92017-12-05 10:52:59 -08002741const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2742 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2743 transceiver,
2744 const SessionDescriptionInterface* sdesc) const {
2745 RTC_DCHECK(transceiver);
2746 RTC_DCHECK(sdesc);
2747 if (IsUnifiedPlan()) {
2748 if (!transceiver->internal()->mid()) {
2749 // This transceiver is not associated with a media section yet.
2750 return nullptr;
2751 }
2752 return sdesc->description()->GetContentByName(
2753 *transceiver->internal()->mid());
2754 } else {
2755 // Plan B only allows at most one audio and one video section, so use the
2756 // first media section of that type.
2757 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002758 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002759 }
2760}
2761
deadbeef46c73892016-11-16 19:42:04 -08002762PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2763 return configuration_;
2764}
2765
deadbeef293e9262017-01-11 12:28:30 -08002766bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2767 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002768 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002769
Steve Anton75737c02017-11-06 10:37:17 -08002770 if (local_description() && configuration.ice_candidate_pool_size !=
2771 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002772 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2773 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002774 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002775 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002776
deadbeef293e9262017-01-11 12:28:30 -08002777 // The simplest (and most future-compatible) way to tell if the config was
2778 // modified in an invalid way is to copy each property we do support
2779 // modifying, then use operator==. There are far more properties we don't
2780 // support modifying than those we do, and more could be added.
2781 RTCConfiguration modified_config = configuration_;
2782 modified_config.servers = configuration.servers;
2783 modified_config.type = configuration.type;
2784 modified_config.ice_candidate_pool_size =
2785 configuration.ice_candidate_pool_size;
2786 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002787 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002788 modified_config.ice_check_interval_strong_connectivity =
2789 configuration.ice_check_interval_strong_connectivity;
2790 modified_config.ice_check_interval_weak_connectivity =
2791 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002792 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2793 modified_config.ice_unwritable_min_checks =
2794 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002795 modified_config.stun_candidate_keepalive_interval =
2796 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002797 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002798 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002799 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002800 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002801 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2802 }
2803
Steve Anton038834f2017-07-14 15:59:59 -07002804 // Validate the modified configuration.
2805 RTCError validate_error = ValidateConfiguration(modified_config);
2806 if (!validate_error.ok()) {
2807 return SafeSetError(std::move(validate_error), error);
2808 }
2809
deadbeef293e9262017-01-11 12:28:30 -08002810 // Note that this isn't possible through chromium, since it's an unsigned
2811 // short in WebIDL.
2812 if (configuration.ice_candidate_pool_size < 0 ||
2813 configuration.ice_candidate_pool_size > UINT16_MAX) {
2814 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2815 }
2816
2817 // Parse ICE servers before hopping to network thread.
2818 cricket::ServerAddresses stun_servers;
2819 std::vector<cricket::RelayServerConfig> turn_servers;
2820 RTCErrorType parse_error =
2821 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2822 if (parse_error != RTCErrorType::NONE) {
2823 return SafeSetError(parse_error, error);
2824 }
2825
2826 // In theory this shouldn't fail.
2827 if (!network_thread()->Invoke<bool>(
2828 RTC_FROM_HERE,
2829 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2830 stun_servers, turn_servers, modified_config.type,
2831 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002832 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002833 modified_config.turn_customizer,
2834 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002835 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002836 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2837 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002838
deadbeefd1a38b52016-12-10 13:15:33 -08002839 // As described in JSEP, calling setConfiguration with new ICE servers or
2840 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2841 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002842 if (modified_config.servers != configuration_.servers ||
2843 modified_config.type != configuration_.type ||
2844 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002845 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002846 }
skvladd1f5fda2017-02-03 16:54:05 -08002847
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002848 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002849
deadbeef293e9262017-01-11 12:28:30 -08002850 configuration_ = modified_config;
2851 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002852}
2853
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002854bool PeerConnection::AddIceCandidate(
2855 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002856 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002857 if (IsClosed()) {
2858 return false;
2859 }
Steve Antond25da372017-11-06 14:50:29 -08002860
2861 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002862 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002863 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002864 return false;
2865 }
2866
2867 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002868 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002869 return false;
2870 }
2871
2872 bool valid = false;
2873 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2874 if (!valid) {
2875 return false;
2876 }
2877
2878 // Add this candidate to the remote session description.
2879 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002880 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002881 return false;
2882 }
2883
2884 if (ready) {
2885 return UseCandidate(ice_candidate);
2886 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002887 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002888 return true;
2889 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002890}
2891
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002892bool PeerConnection::RemoveIceCandidates(
2893 const std::vector<cricket::Candidate>& candidates) {
2894 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002895 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002896 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002897 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002898 return false;
2899 }
2900
2901 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002902 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002903 return false;
2904 }
2905
2906 size_t number_removed =
2907 mutable_remote_description()->RemoveCandidates(candidates);
2908 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002909 RTC_LOG(LS_ERROR)
2910 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002911 "Requested "
2912 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002913 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002914 }
2915
2916 // Remove the candidates from the transport controller.
2917 std::string error;
2918 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2919 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002920 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002921 }
2922 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002923}
2924
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002925void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002926 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002927 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002928
Steve Anton75737c02017-11-06 10:37:17 -08002929 if (transport_controller()) {
2930 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002931 }
2932
Steve Antondb67ba12018-03-19 17:41:42 -07002933 for (auto transceiver : transceivers_) {
2934 auto* channel = transceiver->internal()->channel();
2935 if (channel) {
2936 channel->SetMetricsObserver(uma_observer_);
2937 }
2938 }
2939
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002940 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002941 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002942 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002943 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002944 uma_observer_->IncrementEnumCounter(
2945 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2946 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002947 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002948 uma_observer_->IncrementEnumCounter(
2949 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2950 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002951 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002952 // Send information about the requested SDP semantics.
2953 switch (configuration_.sdp_semantics) {
2954 case SdpSemantics::kDefault:
2955 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2956 kSdpSemanticRequestDefault,
2957 kSdpSemanticRequestMax);
2958
2959 break;
2960 case SdpSemantics::kPlanB:
2961 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2962 kSdpSemanticRequestPlanB,
2963 kSdpSemanticRequestMax);
2964 break;
2965 case SdpSemantics::kUnifiedPlan:
2966 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2967 kSdpSemanticRequestUnifiedPlan,
2968 kSdpSemanticRequestMax);
2969 break;
2970 default:
2971 RTC_NOTREACHED();
2972 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002973 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002974}
2975
zstein4b979802017-06-02 14:37:37 -07002976RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002977 if (!worker_thread()->IsCurrent()) {
2978 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002979 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2980 }
2981
2982 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2983 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2984 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2985 if (has_min && *bitrate.min_bitrate_bps < 0) {
2986 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2987 "min_bitrate_bps <= 0");
2988 }
2989 if (has_current) {
2990 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2991 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2992 "current_bitrate_bps < min_bitrate_bps");
2993 } else if (*bitrate.current_bitrate_bps < 0) {
2994 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2995 "curent_bitrate_bps < 0");
2996 }
2997 }
2998 if (has_max) {
2999 if (has_current &&
3000 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
3001 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3002 "max_bitrate_bps < current_bitrate_bps");
3003 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3004 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3005 "max_bitrate_bps < min_bitrate_bps");
3006 } else if (*bitrate.max_bitrate_bps < 0) {
3007 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3008 "max_bitrate_bps < 0");
3009 }
3010 }
3011
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01003012 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07003013 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3014 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3015 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3016
3017 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01003018 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07003019
3020 return RTCError::OK();
3021}
3022
Alex Narest78609d52017-10-20 10:37:47 +02003023void PeerConnection::SetBitrateAllocationStrategy(
3024 std::unique_ptr<rtc::BitrateAllocationStrategy>
3025 bitrate_allocation_strategy) {
3026 rtc::Thread* worker_thread = factory_->worker_thread();
3027 if (!worker_thread->IsCurrent()) {
3028 rtc::BitrateAllocationStrategy* strategy_raw =
3029 bitrate_allocation_strategy.release();
3030 auto functor = [this, strategy_raw]() {
3031 call_->SetBitrateAllocationStrategy(
3032 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3033 };
3034 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3035 return;
3036 }
3037 RTC_DCHECK(call_.get());
3038 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3039}
3040
henrika5f6bf242017-11-01 11:06:56 +01003041void PeerConnection::SetAudioPlayout(bool playout) {
3042 if (!worker_thread()->IsCurrent()) {
3043 worker_thread()->Invoke<void>(
3044 RTC_FROM_HERE,
3045 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3046 return;
3047 }
3048 auto audio_state =
3049 factory_->channel_manager()->media_engine()->GetAudioState();
3050 audio_state->SetPlayout(playout);
3051}
3052
3053void PeerConnection::SetAudioRecording(bool recording) {
3054 if (!worker_thread()->IsCurrent()) {
3055 worker_thread()->Invoke<void>(
3056 RTC_FROM_HERE,
3057 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3058 return;
3059 }
3060 auto audio_state =
3061 factory_->channel_manager()->media_engine()->GetAudioState();
3062 audio_state->SetRecording(recording);
3063}
3064
Steve Anton8c0f7a72017-10-03 10:03:10 -07003065std::unique_ptr<rtc::SSLCertificate>
3066PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003067 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3068 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003069 return nullptr;
3070 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003071 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003072}
3073
Zhi Huang70b820f2018-01-27 14:16:15 -08003074std::unique_ptr<rtc::SSLCertChain>
3075PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003076 auto audio_transceiver = GetFirstAudioTransceiver();
3077 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003078 return nullptr;
3079 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003080 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003081 audio_transceiver->internal()->channel()->transport_name());
3082}
3083
3084rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3085PeerConnection::GetFirstAudioTransceiver() const {
3086 for (auto transceiver : transceivers_) {
3087 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3088 return transceiver;
3089 }
3090 }
3091 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003092}
3093
ivoc14d5dbe2016-07-04 07:06:55 -07003094bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3095 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003096 // TODO(eladalon): It would be better to not allow negative values into PC.
3097 const size_t max_size = (max_size_bytes < 0)
3098 ? RtcEventLog::kUnlimitedOutput
3099 : rtc::saturated_cast<size_t>(max_size_bytes);
3100 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003101 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3102 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003103}
3104
Bjorn Tereliusde939432017-11-20 17:38:14 +01003105bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3106 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003107 // TODO(eladalon): In C++14, this can be done with a lambda.
3108 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003109 bool operator()() {
3110 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3111 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003112 PeerConnection* const pc;
3113 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003114 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003115 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003116 return worker_thread()->Invoke<bool>(
3117 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003118}
3119
3120void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003121 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003122 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3123}
3124
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003125const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003126 return pending_local_description_ ? pending_local_description_.get()
3127 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003128}
3129
3130const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003131 return pending_remote_description_ ? pending_remote_description_.get()
3132 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003133}
3134
deadbeeffe4a8a42016-12-20 17:56:17 -08003135const SessionDescriptionInterface* PeerConnection::current_local_description()
3136 const {
Steve Anton75737c02017-11-06 10:37:17 -08003137 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003138}
3139
3140const SessionDescriptionInterface* PeerConnection::current_remote_description()
3141 const {
Steve Anton75737c02017-11-06 10:37:17 -08003142 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003143}
3144
3145const SessionDescriptionInterface* PeerConnection::pending_local_description()
3146 const {
Steve Anton75737c02017-11-06 10:37:17 -08003147 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003148}
3149
3150const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3151 const {
Steve Anton75737c02017-11-06 10:37:17 -08003152 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003153}
3154
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003155void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003156 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003157 // Update stats here so that we have the most recent stats for tracks and
3158 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003159 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003160
Steve Anton75737c02017-11-06 10:37:17 -08003161 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003162
Steve Anton8af21862017-12-15 11:20:13 -08003163 for (auto transceiver : transceivers_) {
3164 transceiver->Stop();
3165 }
3166 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003167
Qingsi Wang93a84392018-01-30 17:13:09 -08003168 // The event log is used in the transport controller, which must be outlived
3169 // by the former. CreateOffer by the peer connection is implemented
3170 // asynchronously and if the peer connection is closed without resetting the
3171 // WebRTC session description factory, the session description factory would
3172 // call the transport controller.
3173 webrtc_session_desc_factory_.reset();
3174 transport_controller_.reset();
3175
deadbeef42a42632017-03-10 15:18:00 -08003176 network_thread()->Invoke<void>(
3177 RTC_FROM_HERE,
3178 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3179 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003180
Steve Anton978b8762017-09-29 12:15:02 -07003181 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003182 call_.reset();
3183 // The event log must outlive call (and any other object that uses it).
3184 event_log_.reset();
3185 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003186}
3187
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003188void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003189 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3191 SetSessionDescriptionMsg* param =
3192 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3193 param->observer->OnSuccess();
3194 delete param;
3195 break;
3196 }
3197 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3198 SetSessionDescriptionMsg* param =
3199 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003200 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003201 delete param;
3202 break;
3203 }
deadbeefab9b2d12015-10-14 11:33:11 -07003204 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3205 CreateSessionDescriptionMsg* param =
3206 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003207 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003208 delete param;
3209 break;
3210 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211 case MSG_GETSTATS: {
3212 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003213 StatsReports reports;
3214 stats_->GetStats(param->track, &reports);
3215 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003216 delete param;
3217 break;
3218 }
deadbeefbd292462015-12-14 18:15:29 -08003219 case MSG_FREE_DATACHANNELS: {
3220 sctp_data_channels_to_free_.clear();
3221 break;
3222 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003223 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003224 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225 break;
3226 }
3227}
3228
Steve Antonafb0bb72018-02-20 11:35:37 -08003229cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3230 RTC_DCHECK(!IsUnifiedPlan());
3231 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3232 GetAudioTransceiver()->internal()->channel());
3233 if (voice_channel) {
3234 return voice_channel->media_channel();
3235 } else {
3236 return nullptr;
3237 }
3238}
3239
3240cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3241 RTC_DCHECK(!IsUnifiedPlan());
3242 auto* video_channel = static_cast<cricket::VideoChannel*>(
3243 GetVideoTransceiver()->internal()->channel());
3244 if (video_channel) {
3245 return video_channel->media_channel();
3246 } else {
3247 return nullptr;
3248 }
3249}
3250
Steve Anton4171afb2017-11-20 10:20:22 -08003251void PeerConnection::CreateAudioReceiver(
3252 MediaStreamInterface* stream,
3253 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003254 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3255 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003256 auto* audio_receiver = new AudioRtpReceiver(
3257 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003258 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003259 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3260 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3261 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003262 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003263 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003264}
3265
Steve Anton4171afb2017-11-20 10:20:22 -08003266void PeerConnection::CreateVideoReceiver(
3267 MediaStreamInterface* stream,
3268 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003269 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3270 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003271 auto* video_receiver = new VideoRtpReceiver(
3272 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003273 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003274 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3275 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3276 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003277 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003278 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003279}
3280
deadbeef70ab1a12015-09-28 16:53:55 -07003281// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3282// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003283rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003284 const RtpSenderInfo& remote_sender_info) {
3285 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3286 if (!receiver) {
3287 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3288 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003289 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003290 }
Steve Anton4171afb2017-11-20 10:20:22 -08003291 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3292 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3293 } else {
3294 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3295 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003296 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297}
3298
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003299void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3300 MediaStreamInterface* stream) {
3301 RTC_DCHECK(!IsClosed());
3302 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003303 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003304 // We already have a sender for this track, so just change the stream_id
3305 // so that it's correct in the next call to CreateOffer.
Seth Hampsonf351c342018-03-29 15:45:58 -07003306 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003307 return;
3308 }
3309
3310 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003311 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003312 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003313 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003314 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003315 // If the sender has already been configured in SDP, we call SetSsrc,
3316 // which will connect the sender to the underlying transport. This can
3317 // occur if a local session description that contains the ID of the sender
3318 // is set before AddStream is called. It can also occur if the local
3319 // session description is not changed and RemoveStream is called, and
3320 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003321 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003322 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003323 if (sender_info) {
3324 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003325 }
3326}
3327
3328// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3329// indefinitely, when we have unified plan SDP.
3330void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3331 MediaStreamInterface* stream) {
3332 RTC_DCHECK(!IsClosed());
3333 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003334 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003335 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3336 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003337 return;
3338 }
Steve Anton4171afb2017-11-20 10:20:22 -08003339 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003340}
3341
3342void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3343 MediaStreamInterface* stream) {
3344 RTC_DCHECK(!IsClosed());
3345 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003346 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003347 // We already have a sender for this track, so just change the stream_id
3348 // so that it's correct in the next call to CreateOffer.
Seth Hampsonf351c342018-03-29 15:45:58 -07003349 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003350 return;
3351 }
3352
3353 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003354 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003355 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003356 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003357 GetVideoTransceiver()->internal()->AddSender(new_sender);
3358 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003359 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003360 if (sender_info) {
3361 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003362 }
3363}
3364
3365void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3366 MediaStreamInterface* stream) {
3367 RTC_DCHECK(!IsClosed());
3368 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003369 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003370 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3371 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003372 return;
3373 }
Steve Anton4171afb2017-11-20 10:20:22 -08003374 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003375}
3376
Steve Antonba818672017-11-06 10:21:57 -08003377void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003378 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003379 if (ice_connection_state_ == new_state) {
3380 return;
3381 }
3382
deadbeefcbecd352015-09-23 11:50:27 -07003383 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003384 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003385 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003386 return;
3387 }
Steve Antonba818672017-11-06 10:21:57 -08003388
Mirko Bonadei675513b2017-11-09 11:09:25 +01003389 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3390 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003391 RTC_DCHECK(ice_connection_state_ !=
3392 PeerConnectionInterface::kIceConnectionClosed);
3393
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003394 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003395 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003396}
3397
3398void PeerConnection::OnIceGatheringChange(
3399 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003400 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003401 if (IsClosed()) {
3402 return;
3403 }
3404 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003405 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406}
3407
jbauch81bf7b02017-03-25 08:31:12 -07003408void PeerConnection::OnIceCandidate(
3409 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003410 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003411 if (IsClosed()) {
3412 return;
3413 }
jbauch81bf7b02017-03-25 08:31:12 -07003414 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003415}
3416
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003417void PeerConnection::OnIceCandidatesRemoved(
3418 const std::vector<cricket::Candidate>& candidates) {
3419 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003420 if (IsClosed()) {
3421 return;
3422 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003423 observer_->OnIceCandidatesRemoved(candidates);
3424}
3425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003426void PeerConnection::ChangeSignalingState(
3427 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003428 RTC_DCHECK(signaling_thread()->IsCurrent());
3429 if (signaling_state_ == signaling_state) {
3430 return;
3431 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003432 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3433 << GetSignalingStateString(signaling_state_)
3434 << " New state: "
3435 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003436 signaling_state_ = signaling_state;
3437 if (signaling_state == kClosed) {
3438 ice_connection_state_ = kIceConnectionClosed;
3439 observer_->OnIceConnectionChange(ice_connection_state_);
3440 if (ice_gathering_state_ != kIceGatheringComplete) {
3441 ice_gathering_state_ = kIceGatheringComplete;
3442 observer_->OnIceGatheringChange(ice_gathering_state_);
3443 }
3444 }
3445 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003446}
3447
deadbeefeb459812015-12-15 19:24:43 -08003448void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3449 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003450 if (IsClosed()) {
3451 return;
3452 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003453 AddAudioTrack(track, stream);
3454 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003455}
3456
deadbeefeb459812015-12-15 19:24:43 -08003457void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3458 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003459 if (IsClosed()) {
3460 return;
3461 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003462 RemoveAudioTrack(track, stream);
3463 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003464}
3465
3466void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3467 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003468 if (IsClosed()) {
3469 return;
3470 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003471 AddVideoTrack(track, stream);
3472 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003473}
3474
3475void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3476 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003477 if (IsClosed()) {
3478 return;
3479 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003480 RemoveVideoTrack(track, stream);
3481 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003482}
3483
Henrik Boström31638672017-11-23 17:48:32 +01003484void PeerConnection::PostSetSessionDescriptionSuccess(
3485 SetSessionDescriptionObserver* observer) {
3486 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3487 signaling_thread()->Post(RTC_FROM_HERE, this,
3488 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3489}
3490
deadbeefab9b2d12015-10-14 11:33:11 -07003491void PeerConnection::PostSetSessionDescriptionFailure(
3492 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003493 RTCError&& error) {
3494 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003495 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003496 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003497 signaling_thread()->Post(RTC_FROM_HERE, this,
3498 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003499}
3500
3501void PeerConnection::PostCreateSessionDescriptionFailure(
3502 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003503 RTCError error) {
3504 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003505 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003506 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003507 signaling_thread()->Post(RTC_FROM_HERE, this,
3508 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003509}
3510
zhihuang1c378ed2017-08-17 14:10:50 -07003511void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003512 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003513 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003514 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003515
Steve Antondcc3c022017-12-22 16:02:54 -08003516 if (IsUnifiedPlan()) {
3517 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3518 } else {
3519 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3520 }
3521
Steve Antonfa2260d2017-12-28 16:38:23 -08003522 // Intentionally unset the data channel type for RTP data channel with the
3523 // second condition. Otherwise the RTP data channels would be successfully
3524 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3525 // when building with chromium. We want to leave RTP data channels broken, so
3526 // people won't try to use them.
3527 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3528 session_options->data_channel_type = data_channel_type();
3529 }
3530
Steve Antondcc3c022017-12-22 16:02:54 -08003531 // Apply ICE restart flag and renomination flag.
3532 for (auto& options : session_options->media_description_options) {
3533 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3534 options.transport_options.enable_ice_renomination =
3535 configuration_.enable_ice_renomination;
3536 }
3537
3538 session_options->rtcp_cname = rtcp_cname_;
3539 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003540 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003541}
3542
3543void PeerConnection::GetOptionsForPlanBOffer(
3544 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3545 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003546 // Figure out transceiver directional preferences.
3547 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3548 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3549
3550 // By default, generate sendrecv/recvonly m= sections.
3551 bool recv_audio = true;
3552 bool recv_video = true;
3553
3554 // By default, only offer a new m= section if we have media to send with it.
3555 bool offer_new_audio_description = send_audio;
3556 bool offer_new_video_description = send_video;
3557 bool offer_new_data_description = HasDataChannels();
3558
3559 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003560 if (offer_answer_options.offer_to_receive_audio !=
3561 RTCOfferAnswerOptions::kUndefined) {
3562 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003563 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003564 offer_new_audio_description ||
3565 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003566 }
Steve Antondcc3c022017-12-22 16:02:54 -08003567 if (offer_answer_options.offer_to_receive_video !=
3568 RTCOfferAnswerOptions::kUndefined) {
3569 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003570 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003571 offer_new_video_description ||
3572 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003573 }
3574
3575 rtc::Optional<size_t> audio_index;
3576 rtc::Optional<size_t> video_index;
3577 rtc::Optional<size_t> data_index;
3578 // If a current description exists, generate m= sections in the same order,
3579 // using the first audio/video/data section that appears and rejecting
3580 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003581 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003582 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003583 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003584 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3585 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3586 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003587 }
3588
zhihuang1c378ed2017-08-17 14:10:50 -07003589 // Add audio/video/data m= sections to the end if needed.
3590 if (!audio_index && offer_new_audio_description) {
3591 session_options->media_description_options.push_back(
3592 cricket::MediaDescriptionOptions(
3593 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003594 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3595 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003596 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003597 }
zhihuang1c378ed2017-08-17 14:10:50 -07003598 if (!video_index && offer_new_video_description) {
3599 session_options->media_description_options.push_back(
3600 cricket::MediaDescriptionOptions(
3601 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003602 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3603 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003604 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003605 }
zhihuang1c378ed2017-08-17 14:10:50 -07003606 if (!data_index && offer_new_data_description) {
3607 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003608 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003609 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003610 }
3611
3612 cricket::MediaDescriptionOptions* audio_media_description_options =
3613 !audio_index ? nullptr
3614 : &session_options->media_description_options[*audio_index];
3615 cricket::MediaDescriptionOptions* video_media_description_options =
3616 !video_index ? nullptr
3617 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003618
Steve Anton4171afb2017-11-20 10:20:22 -08003619 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003620 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003621}
3622
3623// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3624// and return a reference to it.
3625// Generated MIDs should be no more than 3 bytes long to take up less space in
3626// the RTP packet.
3627static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3628 RTC_DCHECK(used_mids);
3629 // We're boring: just generate MIDs 0, 1, 2, ...
3630 size_t i = 0;
3631 std::set<std::string>::iterator it;
3632 bool inserted;
3633 do {
3634 std::string mid = rtc::ToString(i++);
3635 auto insert_result = used_mids->insert(mid);
3636 it = insert_result.first;
3637 inserted = insert_result.second;
3638 } while (!inserted);
3639 return *it;
3640}
3641
3642static cricket::MediaDescriptionOptions
3643GetMediaDescriptionOptionsForTransceiver(
3644 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3645 transceiver,
3646 const std::string& mid) {
3647 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003648 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003649 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003650 // This behavior is specified in JSEP. The gist is that:
3651 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3652 // sendrecv.
3653 // 2. If the MSID is included, then it must be included in any subsequent
3654 // offer/answer exactly the same until the RtpTransceiver is stopped.
3655 if (!transceiver->stopped() &&
3656 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3657 transceiver->internal()->has_ever_been_used_to_send())) {
3658 cricket::SenderOptions sender_options;
3659 sender_options.track_id = transceiver->sender()->id();
3660 sender_options.stream_ids = transceiver->sender()->stream_ids();
3661 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3662 // set in the RTP parameters when the transceiver was added.
3663 sender_options.num_sim_layers = 1;
3664 media_description_options.sender_options.push_back(sender_options);
3665 }
Steve Antondcc3c022017-12-22 16:02:54 -08003666 return media_description_options;
3667}
3668
3669void PeerConnection::GetOptionsForUnifiedPlanOffer(
3670 const RTCOfferAnswerOptions& offer_answer_options,
3671 cricket::MediaSessionOptions* session_options) {
3672 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3673 // Offers) and 5.2.2 (Subsequent Offers).
3674 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3675 const ContentInfos& local_contents =
3676 (local_description() ? local_description()->description()->contents()
3677 : ContentInfos());
3678 const ContentInfos& remote_contents =
3679 (remote_description() ? remote_description()->description()->contents()
3680 : ContentInfos());
3681 // The mline indices that can be recycled. New transceivers should reuse these
3682 // slots first.
3683 std::queue<size_t> recycleable_mline_indices;
3684 // Track the MIDs used in previous offer/answer exchanges and the current
3685 // offer so that new, unique MIDs are generated.
3686 std::set<std::string> used_mids = seen_mids_;
3687 // First, go through each media section that exists in either the local or
3688 // remote description and generate a media section in this offer for the
3689 // associated transceiver. If a media section can be recycled, generate a
3690 // default, rejected media section here that can be later overwritten.
3691 for (size_t i = 0;
3692 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3693 // Either |local_content| or |remote_content| is non-null.
3694 const ContentInfo* local_content =
3695 (i < local_contents.size() ? &local_contents[i] : nullptr);
3696 const ContentInfo* remote_content =
3697 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3698 bool had_been_rejected = (local_content && local_content->rejected) ||
3699 (remote_content && remote_content->rejected);
3700 const std::string& mid =
3701 (local_content ? local_content->name : remote_content->name);
3702 cricket::MediaType media_type =
3703 (local_content ? local_content->media_description()->type()
3704 : remote_content->media_description()->type());
3705 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3706 media_type == cricket::MEDIA_TYPE_VIDEO) {
3707 auto transceiver = GetAssociatedTransceiver(mid);
3708 RTC_CHECK(transceiver);
3709 // A media section is considered eligible for recycling if it is marked as
3710 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003711 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003712 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003713 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3714 RtpTransceiverDirection::kInactive,
3715 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003716 recycleable_mline_indices.push(i);
3717 } else {
3718 session_options->media_description_options.push_back(
3719 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3720 // CreateOffer shouldn't really cause any state changes in
3721 // PeerConnection, but we need a way to match new transceivers to new
3722 // media sections in SetLocalDescription and JSEP specifies this is done
3723 // by recording the index of the media section generated for the
3724 // transceiver in the offer.
3725 transceiver->internal()->set_mline_index(i);
3726 }
3727 } else {
3728 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003729 RTC_CHECK(GetDataMid());
3730 if (had_been_rejected || mid != *GetDataMid()) {
3731 session_options->media_description_options.push_back(
3732 GetMediaDescriptionOptionsForRejectedData(mid));
3733 } else {
3734 session_options->media_description_options.push_back(
3735 GetMediaDescriptionOptionsForActiveData(mid));
3736 }
Steve Antondcc3c022017-12-22 16:02:54 -08003737 }
3738 }
3739 // Next, look for transceivers that are newly added (that is, are not stopped
3740 // and not associated). Reuse media sections marked as recyclable first,
3741 // otherwise append to the end of the offer. New media sections should be
3742 // added in the order they were added to the PeerConnection.
3743 for (auto transceiver : transceivers_) {
3744 if (transceiver->mid() || transceiver->stopped()) {
3745 continue;
3746 }
3747 size_t mline_index;
3748 if (!recycleable_mline_indices.empty()) {
3749 mline_index = recycleable_mline_indices.front();
3750 recycleable_mline_indices.pop();
3751 session_options->media_description_options[mline_index] =
3752 GetMediaDescriptionOptionsForTransceiver(transceiver,
3753 AllocateMid(&used_mids));
3754 } else {
3755 mline_index = session_options->media_description_options.size();
3756 session_options->media_description_options.push_back(
3757 GetMediaDescriptionOptionsForTransceiver(transceiver,
3758 AllocateMid(&used_mids)));
3759 }
3760 // See comment above for why CreateOffer changes the transceiver's state.
3761 transceiver->internal()->set_mline_index(mline_index);
3762 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003763 // Lastly, add a m-section if we have local data channels and an m section
3764 // does not already exist.
3765 if (!GetDataMid() && HasDataChannels()) {
3766 session_options->media_description_options.push_back(
3767 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3768 }
Steve Antondcc3c022017-12-22 16:02:54 -08003769}
3770
3771void PeerConnection::GetOptionsForAnswer(
3772 const RTCOfferAnswerOptions& offer_answer_options,
3773 cricket::MediaSessionOptions* session_options) {
3774 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3775
3776 if (IsUnifiedPlan()) {
3777 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3778 } else {
3779 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3780 }
3781
Steve Antonfa2260d2017-12-28 16:38:23 -08003782 // Intentionally unset the data channel type for RTP data channel. Otherwise
3783 // the RTP data channels would be successfully negotiated by default and the
3784 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3785 // We want to leave RTP data channels broken, so people won't try to use them.
3786 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3787 session_options->data_channel_type = data_channel_type();
3788 }
3789
Steve Antondcc3c022017-12-22 16:02:54 -08003790 // Apply ICE renomination flag.
3791 for (auto& options : session_options->media_description_options) {
3792 options.transport_options.enable_ice_renomination =
3793 configuration_.enable_ice_renomination;
3794 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003795
3796 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003797 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003798 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003799}
3800
Steve Antondcc3c022017-12-22 16:02:54 -08003801void PeerConnection::GetOptionsForPlanBAnswer(
3802 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003803 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003804 // Figure out transceiver directional preferences.
3805 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3806 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3807
3808 // By default, generate sendrecv/recvonly m= sections. The direction is also
3809 // restricted by the direction in the offer.
3810 bool recv_audio = true;
3811 bool recv_video = true;
3812
3813 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003814 if (offer_answer_options.offer_to_receive_audio !=
3815 RTCOfferAnswerOptions::kUndefined) {
3816 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003817 }
Steve Antondcc3c022017-12-22 16:02:54 -08003818 if (offer_answer_options.offer_to_receive_video !=
3819 RTCOfferAnswerOptions::kUndefined) {
3820 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003821 }
3822
3823 rtc::Optional<size_t> audio_index;
3824 rtc::Optional<size_t> video_index;
3825 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003826
3827 // Generate m= sections that match those in the offer.
3828 // Note that mediasession.cc will handle intersection our preferred
3829 // direction with the offered direction.
3830 GenerateMediaDescriptionOptions(
3831 remote_description(),
3832 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3833 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3834 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003835
3836 cricket::MediaDescriptionOptions* audio_media_description_options =
3837 !audio_index ? nullptr
3838 : &session_options->media_description_options[*audio_index];
3839 cricket::MediaDescriptionOptions* video_media_description_options =
3840 !video_index ? nullptr
3841 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003842
Steve Anton4171afb2017-11-20 10:20:22 -08003843 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003844 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003845}
zhihuangaf388472016-11-02 16:49:48 -07003846
Steve Antondcc3c022017-12-22 16:02:54 -08003847void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3848 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3849 cricket::MediaSessionOptions* session_options) {
3850 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3851 // Answers) and 5.3.2 (Subsequent Answers).
3852 RTC_DCHECK(remote_description());
3853 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3854 for (const ContentInfo& content :
3855 remote_description()->description()->contents()) {
3856 cricket::MediaType media_type = content.media_description()->type();
3857 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3858 media_type == cricket::MEDIA_TYPE_VIDEO) {
3859 auto transceiver = GetAssociatedTransceiver(content.name);
3860 RTC_CHECK(transceiver);
3861 session_options->media_description_options.push_back(
3862 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3863 } else {
3864 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003865 // Reject all data sections if data channels are disabled.
3866 // Reject a data section if it has already been rejected.
3867 // Reject all data sections except for the first one.
3868 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3869 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003870 session_options->media_description_options.push_back(
3871 GetMediaDescriptionOptionsForRejectedData(content.name));
3872 } else {
3873 session_options->media_description_options.push_back(
3874 GetMediaDescriptionOptionsForActiveData(content.name));
3875 }
Steve Antondcc3c022017-12-22 16:02:54 -08003876 }
3877 }
htaa2a49d92016-03-04 02:51:39 -08003878}
3879
zhihuang1c378ed2017-08-17 14:10:50 -07003880void PeerConnection::GenerateMediaDescriptionOptions(
3881 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003882 RtpTransceiverDirection audio_direction,
3883 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003884 rtc::Optional<size_t>* audio_index,
3885 rtc::Optional<size_t>* video_index,
3886 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003887 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003888 for (const cricket::ContentInfo& content :
3889 session_desc->description()->contents()) {
3890 if (IsAudioContent(&content)) {
3891 // If we already have an audio m= section, reject this extra one.
3892 if (*audio_index) {
3893 session_options->media_description_options.push_back(
3894 cricket::MediaDescriptionOptions(
3895 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003896 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003897 } else {
3898 session_options->media_description_options.push_back(
3899 cricket::MediaDescriptionOptions(
3900 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003901 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003902 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003903 }
3904 } else if (IsVideoContent(&content)) {
3905 // If we already have an video m= section, reject this extra one.
3906 if (*video_index) {
3907 session_options->media_description_options.push_back(
3908 cricket::MediaDescriptionOptions(
3909 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003910 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003911 } else {
3912 session_options->media_description_options.push_back(
3913 cricket::MediaDescriptionOptions(
3914 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003915 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003916 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003917 }
3918 } else {
3919 RTC_DCHECK(IsDataContent(&content));
3920 // If we already have an data m= section, reject this extra one.
3921 if (*data_index) {
3922 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003923 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003924 } else {
3925 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003926 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003927 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003928 }
3929 }
htaa2a49d92016-03-04 02:51:39 -08003930 }
deadbeefab9b2d12015-10-14 11:33:11 -07003931}
3932
Steve Antonfa2260d2017-12-28 16:38:23 -08003933cricket::MediaDescriptionOptions
3934PeerConnection::GetMediaDescriptionOptionsForActiveData(
3935 const std::string& mid) const {
3936 // Direction for data sections is meaningless, but legacy endpoints might
3937 // expect sendrecv.
3938 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3939 RtpTransceiverDirection::kSendRecv,
3940 /*stopped=*/false);
3941 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3942 return options;
3943}
3944
3945cricket::MediaDescriptionOptions
3946PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3947 const std::string& mid) const {
3948 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3949 RtpTransceiverDirection::kInactive,
3950 /*stopped=*/true);
3951 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3952 return options;
3953}
3954
3955rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3956 switch (data_channel_type_) {
3957 case cricket::DCT_RTP:
3958 if (!rtp_data_channel_) {
3959 return rtc::nullopt;
3960 }
3961 return rtp_data_channel_->content_name();
3962 case cricket::DCT_SCTP:
3963 return sctp_content_name_;
3964 default:
3965 return rtc::nullopt;
3966 }
3967}
3968
Steve Anton4171afb2017-11-20 10:20:22 -08003969void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3970 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3971 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003972 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003973}
3974
Steve Anton4171afb2017-11-20 10:20:22 -08003975void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003976 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003977 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003978 cricket::MediaType media_type,
3979 StreamCollection* new_streams) {
Seth Hampsonf351c342018-03-29 15:45:58 -07003980 RTC_DCHECK(!IsUnifiedPlan());
3981
Steve Anton4171afb2017-11-20 10:20:22 -08003982 std::vector<RtpSenderInfo>* current_senders =
3983 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003984
Steve Anton4171afb2017-11-20 10:20:22 -08003985 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003986 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003987 for (auto sender_it = current_senders->begin();
3988 sender_it != current_senders->end();
3989 /* incremented manually */) {
3990 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003991 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003992 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampsonf351c342018-03-29 15:45:58 -07003993 bool sender_exists = params && params->id == info.sender_id &&
3994 params->first_stream_id() == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003995 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08003996 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08003997 sender_exists) {
3998 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003999 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004000 OnRemoteSenderRemoved(info, media_type);
4001 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004002 }
4003 }
4004
Steve Anton4171afb2017-11-20 10:20:22 -08004005 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004006 for (const cricket::StreamParams& params : streams) {
Seth Hampson845e8782018-03-02 11:34:10 -08004007 // |params.id| is the sender id and the stream id uses the first of
Seth Hampsonf351c342018-03-29 15:45:58 -07004008 // |params.stream_ids|. The remote description could come from a Unified
4009 // Plan endpoint, with multiple or no stream_ids() signalled. Since this is
4010 // not supported in Plan B, we just take the first here and create an empty
4011 // stream id if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004012 const std::string& stream_id =
Seth Hampsonf351c342018-03-29 15:45:58 -07004013 (!params.stream_ids().empty() ? params.stream_ids()[0]
4014 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004015 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004016 uint32_t ssrc = params.first_ssrc();
4017
4018 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004019 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004020 if (!stream) {
4021 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004022 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004023 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004024 remote_streams_->AddStream(stream);
4025 new_streams->AddStream(stream);
4026 }
4027
Steve Anton4171afb2017-11-20 10:20:22 -08004028 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004029 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004030 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004031 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004032 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004033 }
4034 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004035
Steve Anton4171afb2017-11-20 10:20:22 -08004036 // Add default sender if necessary.
4037 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004038 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004039 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004040 if (!default_stream) {
4041 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004042 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004043 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004044 remote_streams_->AddStream(default_stream);
4045 new_streams->AddStream(default_stream);
4046 }
Steve Anton4171afb2017-11-20 10:20:22 -08004047 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4048 ? kDefaultAudioSenderId
4049 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004050 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004051 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004052 if (!default_sender_info) {
4053 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004054 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004055 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004056 }
4057 }
deadbeefab9b2d12015-10-14 11:33:11 -07004058}
4059
Steve Anton4171afb2017-11-20 10:20:22 -08004060void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4061 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004062 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004063
4064 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004065 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004066 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004067 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004068 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004069 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004070 }
4071}
4072
Steve Anton4171afb2017-11-20 10:20:22 -08004073void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4074 cricket::MediaType media_type) {
Seth Hampson845e8782018-03-02 11:34:10 -08004075 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004076
Henrik Boström933d8b02017-10-10 10:05:16 -07004077 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004078 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004079 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4080 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004081 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004082 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004083 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004084 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004085 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004086 }
4087 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004088 // Stopping or destroying a VideoRtpReceiver will end the
4089 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004090 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004091 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004092 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004093 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004094 // There's no guarantee the track is still available, e.g. the track may
4095 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004096 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004097 }
4098 } else {
nisseede5da42017-01-12 05:15:36 -08004099 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004100 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004101 if (receiver) {
4102 observer_->OnRemoveTrack(receiver);
4103 }
deadbeefab9b2d12015-10-14 11:33:11 -07004104}
4105
4106void PeerConnection::UpdateEndedRemoteMediaStreams() {
4107 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4108 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4109 MediaStreamInterface* stream = remote_streams_->at(i);
4110 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4111 streams_to_remove.push_back(stream);
4112 }
4113 }
4114
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004115 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004116 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004117 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004118 }
4119}
4120
Steve Anton4171afb2017-11-20 10:20:22 -08004121void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004122 const std::vector<cricket::StreamParams>& streams,
4123 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004124 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004125
Seth Hampson845e8782018-03-02 11:34:10 -08004126 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004127 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004128 for (auto sender_it = current_senders->begin();
4129 sender_it != current_senders->end();
4130 /* incremented manually */) {
4131 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004132 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004133 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4134 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004135 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004136 OnLocalSenderRemoved(info, media_type);
4137 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004138 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004139 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004140 }
4141 }
4142
Steve Anton4171afb2017-11-20 10:20:22 -08004143 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004144 for (const cricket::StreamParams& params : streams) {
4145 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004146 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004147 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004148 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004149 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004150 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004151 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004152 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004153 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004154 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004155 }
4156 }
4157}
4158
Steve Anton4171afb2017-11-20 10:20:22 -08004159void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4160 cricket::MediaType media_type) {
Seth Hampsonf351c342018-03-29 15:45:58 -07004161 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004162 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004163 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004164 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4165 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004166 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004167 return;
4168 }
4169
deadbeeffac06552015-11-25 11:26:01 -08004170 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004171 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004172 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004173 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004174 }
deadbeeffac06552015-11-25 11:26:01 -08004175
Seth Hampsonf351c342018-03-29 15:45:58 -07004176 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004177 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004178}
4179
Steve Anton4171afb2017-11-20 10:20:22 -08004180void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4181 cricket::MediaType media_type) {
4182 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004183 if (!sender) {
4184 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004185 // SessionDescriptions has been renegotiated.
4186 return;
4187 }
deadbeeffac06552015-11-25 11:26:01 -08004188
4189 // A sender has been removed from the SessionDescription but it's still
4190 // associated with the PeerConnection. This only occurs if the SDP doesn't
4191 // match with the calls to CreateSender, AddStream and RemoveStream.
4192 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004193 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004194 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004195 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004196 }
deadbeeffac06552015-11-25 11:26:01 -08004197
Steve Anton4171afb2017-11-20 10:20:22 -08004198 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004199}
4200
4201void PeerConnection::UpdateLocalRtpDataChannels(
4202 const cricket::StreamParamsVec& streams) {
4203 std::vector<std::string> existing_channels;
4204
4205 // Find new and active data channels.
4206 for (const cricket::StreamParams& params : streams) {
4207 // |it->sync_label| is actually the data channel label. The reason is that
4208 // we use the same naming of data channels as we do for
4209 // MediaStreams and Tracks.
4210 // For MediaStreams, the sync_label is the MediaStream label and the
4211 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004212 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004213 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004214 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004215 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004216 continue;
4217 }
4218 // Set the SSRC the data channel should use for sending.
4219 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4220 existing_channels.push_back(data_channel_it->first);
4221 }
4222
4223 UpdateClosingRtpDataChannels(existing_channels, true);
4224}
4225
4226void PeerConnection::UpdateRemoteRtpDataChannels(
4227 const cricket::StreamParamsVec& streams) {
4228 std::vector<std::string> existing_channels;
4229
4230 // Find new and active data channels.
4231 for (const cricket::StreamParams& params : streams) {
4232 // The data channel label is either the mslabel or the SSRC if the mslabel
4233 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004234 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004235 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004236 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004237 auto data_channel_it = rtp_data_channels_.find(label);
4238 if (data_channel_it == rtp_data_channels_.end()) {
4239 // This is a new data channel.
4240 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4241 } else {
4242 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4243 }
4244 existing_channels.push_back(label);
4245 }
4246
4247 UpdateClosingRtpDataChannels(existing_channels, false);
4248}
4249
4250void PeerConnection::UpdateClosingRtpDataChannels(
4251 const std::vector<std::string>& active_channels,
4252 bool is_local_update) {
4253 auto it = rtp_data_channels_.begin();
4254 while (it != rtp_data_channels_.end()) {
4255 DataChannel* data_channel = it->second;
4256 if (std::find(active_channels.begin(), active_channels.end(),
4257 data_channel->label()) != active_channels.end()) {
4258 ++it;
4259 continue;
4260 }
4261
4262 if (is_local_update) {
4263 data_channel->SetSendSsrc(0);
4264 } else {
4265 data_channel->RemotePeerRequestClose();
4266 }
4267
4268 if (data_channel->state() == DataChannel::kClosed) {
4269 rtp_data_channels_.erase(it);
4270 it = rtp_data_channels_.begin();
4271 } else {
4272 ++it;
4273 }
4274 }
4275}
4276
4277void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4278 uint32_t remote_ssrc) {
4279 rtc::scoped_refptr<DataChannel> channel(
4280 InternalCreateDataChannel(label, nullptr));
4281 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004282 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004283 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004284 return;
4285 }
4286 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004287 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4288 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004289 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004290}
4291
4292rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4293 const std::string& label,
4294 const InternalDataChannelInit* config) {
4295 if (IsClosed()) {
4296 return nullptr;
4297 }
Steve Anton75737c02017-11-06 10:37:17 -08004298 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004299 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004300 << "InternalCreateDataChannel: Data is not supported in this call.";
4301 return nullptr;
4302 }
4303 InternalDataChannelInit new_config =
4304 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004305 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004306 if (new_config.id < 0) {
4307 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004308 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004309 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004310 RTC_LOG(LS_ERROR)
4311 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004312 return nullptr;
4313 }
4314 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004315 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004316 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004317 return nullptr;
4318 }
4319 }
4320
Steve Anton75737c02017-11-06 10:37:17 -08004321 rtc::scoped_refptr<DataChannel> channel(
4322 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004323 if (!channel) {
4324 sid_allocator_.ReleaseSid(new_config.id);
4325 return nullptr;
4326 }
4327
4328 if (channel->data_channel_type() == cricket::DCT_RTP) {
4329 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004330 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4331 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004332 return nullptr;
4333 }
4334 rtp_data_channels_[channel->label()] = channel;
4335 } else {
4336 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4337 sctp_data_channels_.push_back(channel);
4338 channel->SignalClosed.connect(this,
4339 &PeerConnection::OnSctpDataChannelClosed);
4340 }
4341
Steve Anton2d8609c2018-01-23 16:38:46 -08004342 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004343 return channel;
4344}
4345
4346bool PeerConnection::HasDataChannels() const {
4347 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4348}
4349
4350void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4351 for (const auto& channel : sctp_data_channels_) {
4352 if (channel->id() < 0) {
4353 int sid;
4354 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004355 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004356 continue;
4357 }
4358 channel->SetSctpSid(sid);
4359 }
4360 }
4361}
4362
4363void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004364 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004365 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4366 ++it) {
4367 if (it->get() == channel) {
4368 if (channel->id() >= 0) {
4369 sid_allocator_.ReleaseSid(channel->id());
4370 }
deadbeefbd292462015-12-14 18:15:29 -08004371 // Since this method is triggered by a signal from the DataChannel,
4372 // we can't free it directly here; we need to free it asynchronously.
4373 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004374 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004375 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4376 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004377 return;
4378 }
4379 }
4380}
4381
deadbeefab9b2d12015-10-14 11:33:11 -07004382void PeerConnection::OnDataChannelDestroyed() {
4383 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4384 // DataChannel may callback to us and try to modify the list.
4385 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4386 temp_rtp_dcs.swap(rtp_data_channels_);
4387 for (const auto& kv : temp_rtp_dcs) {
4388 kv.second->OnTransportChannelDestroyed();
4389 }
4390
4391 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4392 temp_sctp_dcs.swap(sctp_data_channels_);
4393 for (const auto& channel : temp_sctp_dcs) {
4394 channel->OnTransportChannelDestroyed();
4395 }
4396}
4397
4398void PeerConnection::OnDataChannelOpenMessage(
4399 const std::string& label,
4400 const InternalDataChannelInit& config) {
4401 rtc::scoped_refptr<DataChannel> channel(
4402 InternalCreateDataChannel(label, &config));
4403 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004404 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004405 return;
4406 }
4407
deadbeefa601f5c2016-06-06 14:27:39 -07004408 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4409 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004410 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004411}
4412
Steve Anton4171afb2017-11-20 10:20:22 -08004413rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4414PeerConnection::GetAudioTransceiver() const {
4415 // This method only works with Plan B SDP, where there is a single
4416 // audio/video transceiver.
4417 RTC_DCHECK(!IsUnifiedPlan());
4418 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004419 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004420 return transceiver;
4421 }
4422 }
4423 RTC_NOTREACHED();
4424 return nullptr;
4425}
4426
4427rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4428PeerConnection::GetVideoTransceiver() const {
4429 // This method only works with Plan B SDP, where there is a single
4430 // audio/video transceiver.
4431 RTC_DCHECK(!IsUnifiedPlan());
4432 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004433 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004434 return transceiver;
4435 }
4436 }
4437 RTC_NOTREACHED();
4438 return nullptr;
4439}
4440
4441// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4442// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004443bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004444 switch (type) {
4445 case cricket::MEDIA_TYPE_AUDIO:
4446 return !GetAudioTransceiver()->internal()->senders().empty();
4447 case cricket::MEDIA_TYPE_VIDEO:
4448 return !GetVideoTransceiver()->internal()->senders().empty();
4449 case cricket::MEDIA_TYPE_DATA:
4450 return false;
4451 }
4452 RTC_NOTREACHED();
4453 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004454}
4455
Steve Anton4171afb2017-11-20 10:20:22 -08004456rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4457PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4458 for (auto transceiver : transceivers_) {
4459 for (auto sender : transceiver->internal()->senders()) {
4460 if (sender->track() == track) {
4461 return sender;
4462 }
4463 }
4464 }
4465 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004466}
4467
Steve Anton4171afb2017-11-20 10:20:22 -08004468rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4469PeerConnection::FindSenderById(const std::string& sender_id) const {
4470 for (auto transceiver : transceivers_) {
4471 for (auto sender : transceiver->internal()->senders()) {
4472 if (sender->id() == sender_id) {
4473 return sender;
4474 }
4475 }
4476 }
4477 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004478}
4479
Steve Anton4171afb2017-11-20 10:20:22 -08004480rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4481PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4482 for (auto transceiver : transceivers_) {
4483 for (auto receiver : transceiver->internal()->receivers()) {
4484 if (receiver->id() == receiver_id) {
4485 return receiver;
4486 }
4487 }
4488 }
4489 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004490}
4491
Steve Anton4171afb2017-11-20 10:20:22 -08004492std::vector<PeerConnection::RtpSenderInfo>*
4493PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4494 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4495 media_type == cricket::MEDIA_TYPE_VIDEO);
4496 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4497 ? &remote_audio_sender_infos_
4498 : &remote_video_sender_infos_;
4499}
4500
4501std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004502 cricket::MediaType media_type) {
4503 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4504 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004505 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4506 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004507}
4508
Steve Anton4171afb2017-11-20 10:20:22 -08004509const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4510 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004511 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004512 const std::string sender_id) const {
4513 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004514 if (sender_info.stream_id == stream_id &&
4515 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004516 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004517 }
4518 }
4519 return nullptr;
4520}
4521
4522DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4523 for (const auto& channel : sctp_data_channels_) {
4524 if (channel->id() == sid) {
4525 return channel;
4526 }
4527 }
4528 return nullptr;
4529}
4530
deadbeef91dd5672016-05-18 16:55:30 -07004531bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004532 const RTCConfiguration& configuration) {
4533 cricket::ServerAddresses stun_servers;
4534 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004535 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4536 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004537 return false;
4538 }
4539
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004540 port_allocator_->Initialize();
4541
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004542 // To handle both internal and externally created port allocator, we will
4543 // enable BUNDLE here.
4544 int portallocator_flags = port_allocator_->flags();
4545 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004546 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4547 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004548 // If the disable-IPv6 flag was specified, we'll not override it
4549 // by experiment.
4550 if (configuration.disable_ipv6) {
4551 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004552 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4553 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004554 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4555 }
4556
zhihuangb09b3f92017-03-07 14:40:51 -08004557 if (configuration.disable_ipv6_on_wifi) {
4558 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004559 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004560 }
4561
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004562 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4563 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004564 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004565 }
4566
honghaiz60347052016-05-31 18:29:12 -07004567 if (configuration.candidate_network_policy ==
4568 kCandidateNetworkPolicyLowCost) {
4569 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004570 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004571 }
4572
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004573 if (configuration.disable_link_local_networks) {
4574 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
4575 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4576 }
4577
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004578 port_allocator_->set_flags(portallocator_flags);
4579 // No step delay is used while allocating ports.
4580 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4581 port_allocator_->set_candidate_filter(
4582 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004583 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004584
4585 // Call this last since it may create pooled allocator sessions using the
4586 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004587 port_allocator_->SetConfiguration(
4588 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4589 configuration.prune_turn_ports, configuration.turn_customizer,
4590 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004591 return true;
4592}
4593
deadbeef91dd5672016-05-18 16:55:30 -07004594bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004595 const cricket::ServerAddresses& stun_servers,
4596 const std::vector<cricket::RelayServerConfig>& turn_servers,
4597 IceTransportsType type,
4598 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004599 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004600 webrtc::TurnCustomizer* turn_customizer,
4601 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004602 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004603 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004604 // Call this last since it may create pooled allocator sessions using the
4605 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004606 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004607 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004608 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004609}
4610
Steve Antonba818672017-11-06 10:21:57 -08004611cricket::ChannelManager* PeerConnection::channel_manager() const {
4612 return factory_->channel_manager();
4613}
4614
4615MetricsObserverInterface* PeerConnection::metrics_observer() const {
4616 return uma_observer_;
4617}
4618
Elad Alon99c3fe52017-10-13 16:29:40 +02004619bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004620 std::unique_ptr<RtcEventLogOutput> output,
4621 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004622 if (!event_log_) {
4623 return false;
4624 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004625 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004626}
4627
4628void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004629 if (event_log_) {
4630 event_log_->StopLogging();
4631 }
ivoc14d5dbe2016-07-04 07:06:55 -07004632}
nisseeaabdf62017-05-05 02:23:02 -07004633
Steve Anton75737c02017-11-06 10:37:17 -08004634cricket::BaseChannel* PeerConnection::GetChannel(
4635 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004636 for (auto transceiver : transceivers_) {
4637 cricket::BaseChannel* channel = transceiver->internal()->channel();
4638 if (channel && channel->content_name() == content_name) {
4639 return channel;
4640 }
Steve Anton75737c02017-11-06 10:37:17 -08004641 }
4642 if (rtp_data_channel() &&
4643 rtp_data_channel()->content_name() == content_name) {
4644 return rtp_data_channel();
4645 }
4646 return nullptr;
4647}
4648
4649bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4650 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004651 RTC_LOG(LS_INFO)
4652 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004653 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004654 return false;
4655 }
4656 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004657 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004658 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004659 return false;
4660 }
4661
4662 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4663}
4664
4665bool PeerConnection::GetSslRole(const std::string& content_name,
4666 rtc::SSLRole* role) {
4667 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004668 RTC_LOG(LS_INFO)
4669 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004670 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004671 return false;
4672 }
4673
4674 return transport_controller_->GetSslRole(GetTransportName(content_name),
4675 role);
4676}
4677
Steve Antonf8470812017-12-04 10:46:21 -08004678void PeerConnection::SetSessionError(SessionError error,
4679 const std::string& error_desc) {
4680 RTC_DCHECK_RUN_ON(signaling_thread());
4681 if (error != session_error_) {
4682 session_error_ = error;
4683 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004684 }
4685}
4686
Steve Anton3828c062017-12-06 10:34:51 -08004687RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004688 cricket::ContentSource source) {
4689 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004690
4691 // If there's already a pending error then no state transition should happen.
4692 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004693 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004694
4695 // If this is an answer then we know whether to BUNDLE or not. If both the
4696 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004697 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004698 const cricket::ContentGroup* local_bundle =
4699 local_description()->description()->GetGroupByName(
4700 cricket::GROUP_TYPE_BUNDLE);
4701 const cricket::ContentGroup* remote_bundle =
4702 remote_description()->description()->GetGroupByName(
4703 cricket::GROUP_TYPE_BUNDLE);
4704 if (local_bundle && remote_bundle) {
4705 // The answerer decides the transport to bundle on.
4706 const cricket::ContentGroup* answer_bundle =
4707 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4708 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004709 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4710 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004711 }
4712 }
Steve Anton75737c02017-11-06 10:37:17 -08004713 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004714
4715 // Only push down the transport description after potentially enabling BUNDLE;
4716 // we don't want to push down a description on a transport about to be
4717 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004718 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004719 if (!error.ok()) {
4720 return error;
4721 }
4722
4723 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004724 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004725 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004726 }
4727
4728 // Update the signaling state according to the specified state machine (see
4729 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004730 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004731 ChangeSignalingState(source == cricket::CS_LOCAL
4732 ? PeerConnectionInterface::kHaveLocalOffer
4733 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004734 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004735 ChangeSignalingState(source == cricket::CS_LOCAL
4736 ? PeerConnectionInterface::kHaveLocalPrAnswer
4737 : PeerConnectionInterface::kHaveRemotePrAnswer);
4738 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004739 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004740 ChangeSignalingState(PeerConnectionInterface::kStable);
4741 }
4742
4743 // Update internal objects according to the session description's media
4744 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004745 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004746 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004747 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004748 }
4749
Steve Anton8a006912017-12-04 15:25:56 -08004750 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004751}
4752
Steve Anton8a006912017-12-04 15:25:56 -08004753RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004754 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004755 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004756 const SessionDescriptionInterface* sdesc =
4757 (source == cricket::CS_LOCAL ? local_description()
4758 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004759 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004760
4761 // Push down the new SDP media section for each audio/video transceiver.
4762 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004763 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004764 FindMediaSectionForTransceiver(transceiver, sdesc);
4765 cricket::BaseChannel* channel = transceiver->internal()->channel();
4766 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004767 continue;
4768 }
4769 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004770 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004771 if (!content_desc) {
4772 continue;
4773 }
4774 std::string error;
4775 bool success =
4776 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004777 ? channel->SetLocalContent(content_desc, type, &error)
4778 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004779 if (!success) {
4780 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4781 }
4782 }
4783
4784 // If using the RtpDataChannel, push down the new SDP section for it too.
4785 if (rtp_data_channel_) {
4786 const ContentInfo* data_content =
4787 cricket::GetFirstDataContent(sdesc->description());
4788 if (data_content && !data_content->rejected) {
4789 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004790 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004791 if (data_desc) {
4792 std::string error;
4793 bool success =
4794 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004795 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4796 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004797 &error);
4798 if (!success) {
4799 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4800 std::move(error));
4801 }
Steve Anton75737c02017-11-06 10:37:17 -08004802 }
4803 }
4804 }
Steve Antoned10bd92017-12-05 10:52:59 -08004805
Steve Anton75737c02017-11-06 10:37:17 -08004806 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4807 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4808 if (sctp_transport_ && local_description() && remote_description() &&
4809 cricket::GetFirstDataContent(local_description()->description()) &&
4810 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004811 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004812 RTC_FROM_HERE,
4813 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004814 if (!success) {
4815 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4816 "Failed to push down SCTP parameters.");
4817 }
Steve Anton75737c02017-11-06 10:37:17 -08004818 }
Steve Antoned10bd92017-12-05 10:52:59 -08004819
Steve Anton8a006912017-12-04 15:25:56 -08004820 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004821}
4822
4823bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4824 RTC_DCHECK(network_thread()->IsCurrent());
4825 RTC_DCHECK(local_description());
4826 RTC_DCHECK(remote_description());
4827 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4828 // When we support "max-message-size", that would also be pushed down here.
4829 return sctp_transport_->Start(
4830 GetSctpPort(local_description()->description()),
4831 GetSctpPort(remote_description()->description()));
4832}
4833
Steve Anton8a006912017-12-04 15:25:56 -08004834RTCError PeerConnection::PushdownTransportDescription(
4835 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004836 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004837 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004838
Steve Anton8a006912017-12-04 15:25:56 -08004839 const SessionDescriptionInterface* sdesc =
4840 (source == cricket::CS_LOCAL ? local_description()
4841 : remote_description());
4842 RTC_DCHECK(sdesc);
4843 for (const cricket::TransportInfo& tinfo :
4844 sdesc->description()->transport_infos()) {
4845 std::string error;
4846 bool success;
4847 if (source == cricket::CS_LOCAL) {
4848 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004849 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004850 } else {
4851 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004852 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004853 }
4854 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004855 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4856 "Failed to push down transport description for " +
4857 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004858 }
4859 }
4860
Steve Anton8a006912017-12-04 15:25:56 -08004861 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004862}
4863
4864bool PeerConnection::GetTransportDescription(
4865 const SessionDescription* description,
4866 const std::string& content_name,
4867 cricket::TransportDescription* tdesc) {
4868 if (!description || !tdesc) {
4869 return false;
4870 }
4871 const TransportInfo* transport_info =
4872 description->GetTransportInfoByName(content_name);
4873 if (!transport_info) {
4874 return false;
4875 }
4876 *tdesc = transport_info->description;
4877 return true;
4878}
4879
4880bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4881 const std::string* first_content_name = bundle.FirstContentName();
4882 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004883 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004884 return false;
4885 }
4886 const std::string& transport_name = *first_content_name;
4887
4888 auto maybe_set_transport = [this, bundle,
4889 transport_name](cricket::BaseChannel* ch) {
4890 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004891 return;
Steve Anton75737c02017-11-06 10:37:17 -08004892 }
4893
4894 std::string old_transport_name = ch->transport_name();
4895 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004896 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4897 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004898 return;
Steve Anton75737c02017-11-06 10:37:17 -08004899 }
4900
4901 cricket::DtlsTransportInternal* rtp_dtls_transport =
4902 transport_controller_->CreateDtlsTransport(
4903 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4904 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4905 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4906 if (need_rtcp) {
4907 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4908 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4909 }
4910
4911 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004912 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4913 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004914 transport_controller_->DestroyDtlsTransport(
4915 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4916 // If the channel needs rtcp, it means that the channel used to have a
4917 // rtcp transport which needs to be deleted now.
4918 if (need_rtcp) {
4919 transport_controller_->DestroyDtlsTransport(
4920 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4921 }
Steve Anton75737c02017-11-06 10:37:17 -08004922 };
4923
Steve Antoned10bd92017-12-05 10:52:59 -08004924 for (auto transceiver : transceivers_) {
4925 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004926 }
Steve Antoned10bd92017-12-05 10:52:59 -08004927 maybe_set_transport(rtp_data_channel_);
4928
Steve Anton75737c02017-11-06 10:37:17 -08004929 // For SCTP, transport creation/deletion happens here instead of in the
4930 // object itself.
4931 if (sctp_transport_) {
4932 RTC_DCHECK(sctp_transport_name_);
4933 RTC_DCHECK(sctp_content_name_);
4934 if (transport_name != *sctp_transport_name_ &&
4935 bundle.HasContentName(*sctp_content_name_)) {
4936 network_thread()->Invoke<void>(
4937 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4938 transport_name));
4939 }
4940 }
4941
4942 return true;
4943}
4944
Steve Anton75737c02017-11-06 10:37:17 -08004945cricket::IceConfig PeerConnection::ParseIceConfig(
4946 const PeerConnectionInterface::RTCConfiguration& config) const {
4947 cricket::ContinualGatheringPolicy gathering_policy;
4948 // TODO(honghaiz): Add the third continual gathering policy in
4949 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4950 switch (config.continual_gathering_policy) {
4951 case PeerConnectionInterface::GATHER_ONCE:
4952 gathering_policy = cricket::GATHER_ONCE;
4953 break;
4954 case PeerConnectionInterface::GATHER_CONTINUALLY:
4955 gathering_policy = cricket::GATHER_CONTINUALLY;
4956 break;
4957 default:
4958 RTC_NOTREACHED();
4959 gathering_policy = cricket::GATHER_ONCE;
4960 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004961
Steve Anton75737c02017-11-06 10:37:17 -08004962 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004963 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4964 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004965 ice_config.prioritize_most_likely_candidate_pairs =
4966 config.prioritize_most_likely_ice_candidate_pairs;
4967 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004968 RTCConfigurationToIceConfigOptionalInt(
4969 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004970 ice_config.continual_gathering_policy = gathering_policy;
4971 ice_config.presume_writable_when_fully_relayed =
4972 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004973 ice_config.ice_check_interval_strong_connectivity =
4974 config.ice_check_interval_strong_connectivity;
4975 ice_config.ice_check_interval_weak_connectivity =
4976 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004977 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004978 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004979 ice_config.regather_all_networks_interval_range =
4980 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004981 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004982 return ice_config;
4983}
4984
Steve Anton75737c02017-11-06 10:37:17 -08004985bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4986 std::string* track_id) {
4987 if (!local_description()) {
4988 return false;
4989 }
4990 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4991 track_id);
4992}
4993
4994bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4995 std::string* track_id) {
4996 if (!remote_description()) {
4997 return false;
4998 }
4999 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5000 track_id);
5001}
5002
5003bool PeerConnection::SendData(const cricket::SendDataParams& params,
5004 const rtc::CopyOnWriteBuffer& payload,
5005 cricket::SendDataResult* result) {
5006 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005007 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005008 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005009 return false;
5010 }
5011 return rtp_data_channel_
5012 ? rtp_data_channel_->SendData(params, payload, result)
5013 : network_thread()->Invoke<bool>(
5014 RTC_FROM_HERE,
5015 Bind(&cricket::SctpTransportInternal::SendData,
5016 sctp_transport_.get(), params, payload, result));
5017}
5018
5019bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5020 if (!rtp_data_channel_ && !sctp_transport_) {
5021 // Don't log an error here, because DataChannels are expected to call
5022 // ConnectDataChannel in this state. It's the only way to initially tell
5023 // whether or not the underlying transport is ready.
5024 return false;
5025 }
5026 if (rtp_data_channel_) {
5027 rtp_data_channel_->SignalReadyToSendData.connect(
5028 webrtc_data_channel, &DataChannel::OnChannelReady);
5029 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5030 &DataChannel::OnDataReceived);
5031 } else {
5032 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5033 &DataChannel::OnChannelReady);
5034 SignalSctpDataReceived.connect(webrtc_data_channel,
5035 &DataChannel::OnDataReceived);
5036 SignalSctpStreamClosedRemotely.connect(
5037 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5038 }
5039 return true;
5040}
5041
5042void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5043 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005044 RTC_LOG(LS_ERROR)
5045 << "DisconnectDataChannel called when rtp_data_channel_ and "
5046 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005047 return;
5048 }
5049 if (rtp_data_channel_) {
5050 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5051 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5052 } else {
5053 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5054 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5055 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5056 }
5057}
5058
5059void PeerConnection::AddSctpDataStream(int sid) {
5060 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005061 RTC_LOG(LS_ERROR)
5062 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005063 return;
5064 }
5065 network_thread()->Invoke<void>(
5066 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5067 sctp_transport_.get(), sid));
5068}
5069
5070void PeerConnection::RemoveSctpDataStream(int sid) {
5071 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005072 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005073 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005074 return;
5075 }
5076 network_thread()->Invoke<void>(
5077 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5078 sctp_transport_.get(), sid));
5079}
5080
5081bool PeerConnection::ReadyToSendData() const {
5082 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5083 sctp_ready_to_send_data_;
5084}
5085
Qingsi Wang72a43a12018-02-20 16:03:18 -08005086cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5087 cricket::CandidateStatsList candidate_states_list;
5088 port_allocator_->GetCandidateStatsFromPooledSessions(&candidate_states_list);
5089 return candidate_states_list;
5090}
5091
Steve Anton5dfde182018-02-06 10:34:40 -08005092std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5093 const {
5094 std::map<std::string, std::string> transport_names_by_mid;
5095 for (auto transceiver : transceivers_) {
5096 cricket::BaseChannel* channel = transceiver->internal()->channel();
5097 if (channel) {
5098 transport_names_by_mid[channel->content_name()] =
5099 channel->transport_name();
5100 }
Steve Anton75737c02017-11-06 10:37:17 -08005101 }
Steve Anton5dfde182018-02-06 10:34:40 -08005102 if (rtp_data_channel_) {
5103 transport_names_by_mid[rtp_data_channel_->content_name()] =
5104 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005105 }
5106 if (sctp_transport_) {
Steve Anton5dfde182018-02-06 10:34:40 -08005107 transport_names_by_mid[*sctp_content_name_] = *sctp_transport_name_;
Steve Anton75737c02017-11-06 10:37:17 -08005108 }
Steve Anton5dfde182018-02-06 10:34:40 -08005109 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005110}
5111
Steve Anton5dfde182018-02-06 10:34:40 -08005112std::map<std::string, cricket::TransportStats>
5113PeerConnection::GetTransportStatsByNames(
5114 const std::set<std::string>& transport_names) {
5115 if (!network_thread()->IsCurrent()) {
5116 return network_thread()
5117 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5118 RTC_FROM_HERE,
5119 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005120 }
Steve Anton5dfde182018-02-06 10:34:40 -08005121 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5122 for (const std::string& transport_name : transport_names) {
5123 cricket::TransportStats transport_stats;
5124 bool success =
5125 transport_controller_->GetStats(transport_name, &transport_stats);
5126 if (success) {
5127 transport_stats_by_name[transport_name] = std::move(transport_stats);
5128 } else {
5129 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5130 << transport_name;
5131 }
5132 }
5133 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005134}
5135
5136bool PeerConnection::GetLocalCertificate(
5137 const std::string& transport_name,
5138 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
5139 return transport_controller_->GetLocalCertificate(transport_name,
5140 certificate);
5141}
5142
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005143std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005144 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005145 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005146}
5147
5148cricket::DataChannelType PeerConnection::data_channel_type() const {
5149 return data_channel_type_;
5150}
5151
5152bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5153 return pending_ice_restarts_.find(content_name) !=
5154 pending_ice_restarts_.end();
5155}
5156
Steve Anton75737c02017-11-06 10:37:17 -08005157bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5158 return transport_controller_->NeedsIceRestart(content_name);
5159}
5160
5161void PeerConnection::OnCertificateReady(
5162 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5163 transport_controller_->SetLocalCertificate(certificate);
5164}
5165
5166void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005167 SetSessionError(SessionError::kTransport,
5168 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005169}
5170
5171void PeerConnection::OnTransportControllerConnectionState(
5172 cricket::IceConnectionState state) {
5173 switch (state) {
5174 case cricket::kIceConnectionConnecting:
5175 // If the current state is Connected or Completed, then there were
5176 // writable channels but now there are not, so the next state must
5177 // be Disconnected.
5178 // kIceConnectionConnecting is currently used as the default,
5179 // un-connected state by the TransportController, so its only use is
5180 // detecting disconnections.
5181 if (ice_connection_state_ ==
5182 PeerConnectionInterface::kIceConnectionConnected ||
5183 ice_connection_state_ ==
5184 PeerConnectionInterface::kIceConnectionCompleted) {
5185 SetIceConnectionState(
5186 PeerConnectionInterface::kIceConnectionDisconnected);
5187 }
5188 break;
5189 case cricket::kIceConnectionFailed:
5190 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5191 break;
5192 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005193 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005194 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005195 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5196 break;
5197 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005198 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005199 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005200 if (ice_connection_state_ !=
5201 PeerConnectionInterface::kIceConnectionConnected) {
5202 // If jumping directly from "checking" to "connected",
5203 // signal "connected" first.
5204 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5205 }
5206 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5207 if (metrics_observer()) {
5208 ReportTransportStats();
5209 }
5210 break;
5211 default:
5212 RTC_NOTREACHED();
5213 }
5214}
5215
5216void PeerConnection::OnTransportControllerCandidatesGathered(
5217 const std::string& transport_name,
5218 const cricket::Candidates& candidates) {
5219 RTC_DCHECK(signaling_thread()->IsCurrent());
5220 int sdp_mline_index;
5221 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005222 RTC_LOG(LS_ERROR)
5223 << "OnTransportControllerCandidatesGathered: content name "
5224 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005225 return;
5226 }
5227
5228 for (cricket::Candidates::const_iterator citer = candidates.begin();
5229 citer != candidates.end(); ++citer) {
5230 // Use transport_name as the candidate media id.
5231 std::unique_ptr<JsepIceCandidate> candidate(
5232 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5233 if (local_description()) {
5234 mutable_local_description()->AddCandidate(candidate.get());
5235 }
5236 OnIceCandidate(std::move(candidate));
5237 }
5238}
5239
5240void PeerConnection::OnTransportControllerCandidatesRemoved(
5241 const std::vector<cricket::Candidate>& candidates) {
5242 RTC_DCHECK(signaling_thread()->IsCurrent());
5243 // Sanity check.
5244 for (const cricket::Candidate& candidate : candidates) {
5245 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005246 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005247 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005248 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005249 return;
5250 }
5251 }
5252
5253 if (local_description()) {
5254 mutable_local_description()->RemoveCandidates(candidates);
5255 }
5256 OnIceCandidatesRemoved(candidates);
5257}
5258
5259void PeerConnection::OnTransportControllerDtlsHandshakeError(
5260 rtc::SSLHandshakeError error) {
5261 if (metrics_observer()) {
5262 metrics_observer()->IncrementEnumCounter(
5263 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5264 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5265 }
5266}
5267
Steve Antoned10bd92017-12-05 10:52:59 -08005268void PeerConnection::EnableSending() {
5269 for (auto transceiver : transceivers_) {
5270 cricket::BaseChannel* channel = transceiver->internal()->channel();
5271 if (channel && !channel->enabled()) {
5272 channel->Enable(true);
5273 }
Steve Anton75737c02017-11-06 10:37:17 -08005274 }
5275
Steve Anton4171afb2017-11-20 10:20:22 -08005276 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005277 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005278 }
Steve Anton75737c02017-11-06 10:37:17 -08005279}
5280
5281// Returns the media index for a local ice candidate given the content name.
5282bool PeerConnection::GetLocalCandidateMediaIndex(
5283 const std::string& content_name,
5284 int* sdp_mline_index) {
5285 if (!local_description() || !sdp_mline_index) {
5286 return false;
5287 }
5288
5289 bool content_found = false;
5290 const ContentInfos& contents = local_description()->description()->contents();
5291 for (size_t index = 0; index < contents.size(); ++index) {
5292 if (contents[index].name == content_name) {
5293 *sdp_mline_index = static_cast<int>(index);
5294 content_found = true;
5295 break;
5296 }
5297 }
5298 return content_found;
5299}
5300
5301bool PeerConnection::UseCandidatesInSessionDescription(
5302 const SessionDescriptionInterface* remote_desc) {
5303 if (!remote_desc) {
5304 return true;
5305 }
5306 bool ret = true;
5307
5308 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5309 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5310 for (size_t n = 0; n < candidates->count(); ++n) {
5311 const IceCandidateInterface* candidate = candidates->at(n);
5312 bool valid = false;
5313 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5314 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005315 RTC_LOG(LS_INFO)
5316 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005317 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005318 }
5319 continue;
5320 }
5321 ret = UseCandidate(candidate);
5322 if (!ret) {
5323 break;
5324 }
5325 }
5326 }
5327 return ret;
5328}
5329
5330bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5331 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5332 size_t remote_content_size =
5333 remote_description()->description()->contents().size();
5334 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005335 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005336 return false;
5337 }
5338
5339 cricket::ContentInfo content =
5340 remote_description()->description()->contents()[mediacontent_index];
5341 std::vector<cricket::Candidate> candidates;
5342 candidates.push_back(candidate->candidate());
5343 // Invoking BaseSession method to handle remote candidates.
5344 std::string error;
5345 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
5346 &error)) {
5347 // Candidates successfully submitted for checking.
5348 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5349 ice_connection_state_ ==
5350 PeerConnectionInterface::kIceConnectionDisconnected) {
5351 // If state is New, then the session has just gotten its first remote ICE
5352 // candidates, so go to Checking.
5353 // If state is Disconnected, the session is re-using old candidates or
5354 // receiving additional ones, so go to Checking.
5355 // If state is Connected, stay Connected.
5356 // TODO(bemasc): If state is Connected, and the new candidates are for a
5357 // newly added transport, then the state actually _should_ move to
5358 // checking. Add a way to distinguish that case.
5359 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5360 }
5361 // TODO(bemasc): If state is Completed, go back to Connected.
5362 } else {
5363 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005364 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08005365 }
5366 }
5367 return true;
5368}
5369
5370void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005371 // Destroy video channel first since it may have a pointer to the
5372 // voice channel.
5373 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005374 if (!video_info || video_info->rejected) {
5375 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005376 }
5377
Steve Anton6fec8802017-12-04 10:37:29 -08005378 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5379 if (!audio_info || audio_info->rejected) {
5380 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005381 }
5382
5383 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5384 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005385 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005386 }
5387}
5388
Steve Antoneda6ccd2017-12-04 10:21:55 -08005389std::string PeerConnection::GetTransportNameForMediaSection(
5390 const std::string& mid,
5391 const cricket::ContentGroup* bundle_group) const {
5392 if (!bundle_group) {
5393 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005394 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005395 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08005396 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005397 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08005398 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005399 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005400 if (!bundle_group->HasContentName(mid)) {
5401 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
5402 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08005403 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005404 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
5405 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005406}
5407
Steve Antondcc3c022017-12-22 16:02:54 -08005408RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5409 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005410 const cricket::ContentGroup* bundle_group = nullptr;
5411 if (configuration_.bundle_policy ==
5412 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005413 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005414 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005415 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5416 "max-bundle configured but session description "
5417 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005418 }
5419 }
Steve Antondcc3c022017-12-22 16:02:54 -08005420 return std::move(bundle_group);
5421}
5422
5423RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
5424 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
5425 if (!bundle_group_or_error.ok()) {
5426 return bundle_group_or_error.MoveError();
5427 }
5428 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08005429
Steve Antoneda6ccd2017-12-04 10:21:55 -08005430 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08005431 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005432 if (voice && !voice->rejected &&
5433 !GetAudioTransceiver()->internal()->channel()) {
5434 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
5435 voice->name,
5436 GetTransportNameForMediaSection(voice->name, bundle_group));
5437 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005438 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5439 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005440 }
5441 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5442 }
5443
Steve Antondcc3c022017-12-22 16:02:54 -08005444 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005445 if (video && !video->rejected &&
5446 !GetVideoTransceiver()->internal()->channel()) {
5447 cricket::VideoChannel* video_channel = CreateVideoChannel(
5448 video->name,
5449 GetTransportNameForMediaSection(video->name, bundle_group));
5450 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005451 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5452 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005453 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005454 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005455 }
5456
Steve Antondcc3c022017-12-22 16:02:54 -08005457 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005458 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5459 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005460 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
5461 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08005462 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5463 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005464 }
5465 }
5466
Steve Anton8a006912017-12-04 15:25:56 -08005467 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005468}
5469
Steve Anton4171afb2017-11-20 10:20:22 -08005470// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005471cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
5472 const std::string& mid,
5473 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005474 cricket::DtlsTransportInternal* rtp_dtls_transport =
5475 transport_controller_->CreateDtlsTransport(
5476 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5477 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5478 if (configuration_.rtcp_mux_policy !=
5479 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5480 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5481 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5482 }
5483
5484 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5485 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005486 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5487 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005488 if (!voice_channel) {
5489 transport_controller_->DestroyDtlsTransport(
5490 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5491 if (rtcp_dtls_transport) {
5492 transport_controller_->DestroyDtlsTransport(
5493 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5494 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005495 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005496 }
Steve Anton75737c02017-11-06 10:37:17 -08005497 voice_channel->SignalRtcpMuxFullyActive.connect(
5498 this, &PeerConnection::DestroyRtcpTransport_n);
5499 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5500 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005501 voice_channel->SignalSentPacket.connect(this,
5502 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005503 if (uma_observer_) {
5504 voice_channel->SetMetricsObserver(uma_observer_);
5505 }
Steve Anton4171afb2017-11-20 10:20:22 -08005506
Steve Antoneda6ccd2017-12-04 10:21:55 -08005507 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005508}
5509
Steve Anton4171afb2017-11-20 10:20:22 -08005510// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005511cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5512 const std::string& mid,
5513 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005514 cricket::DtlsTransportInternal* rtp_dtls_transport =
5515 transport_controller_->CreateDtlsTransport(
5516 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5517 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5518 if (configuration_.rtcp_mux_policy !=
5519 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5520 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5521 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5522 }
5523
5524 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5525 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005526 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5527 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005528
5529 if (!video_channel) {
5530 transport_controller_->DestroyDtlsTransport(
5531 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5532 if (rtcp_dtls_transport) {
5533 transport_controller_->DestroyDtlsTransport(
5534 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5535 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005536 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005537 }
Steve Anton75737c02017-11-06 10:37:17 -08005538 video_channel->SignalRtcpMuxFullyActive.connect(
5539 this, &PeerConnection::DestroyRtcpTransport_n);
5540 video_channel->SignalDtlsSrtpSetupFailure.connect(
5541 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005542 video_channel->SignalSentPacket.connect(this,
5543 &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005544 if (uma_observer_) {
5545 video_channel->SetMetricsObserver(uma_observer_);
5546 }
Steve Anton4171afb2017-11-20 10:20:22 -08005547
Steve Antoneda6ccd2017-12-04 10:21:55 -08005548 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005549}
5550
Steve Antoneda6ccd2017-12-04 10:21:55 -08005551bool PeerConnection::CreateDataChannel(const std::string& mid,
5552 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005553 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5554 if (sctp) {
5555 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005556 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005557 << "Trying to create SCTP transport, but didn't compile with "
5558 "SCTP support (HAVE_SCTP)";
5559 return false;
5560 }
5561 if (!network_thread()->Invoke<bool>(
5562 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005563 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005564 return false;
5565 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005566 for (const auto& channel : sctp_data_channels_) {
5567 channel->OnTransportChannelCreated();
5568 }
Steve Anton75737c02017-11-06 10:37:17 -08005569 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005570 cricket::DtlsTransportInternal* rtp_dtls_transport =
5571 transport_controller_->CreateDtlsTransport(
5572 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5573 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5574 if (configuration_.rtcp_mux_policy !=
5575 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5576 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5577 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5578 }
5579
5580 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5581 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005582 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005583
5584 if (!rtp_data_channel_) {
5585 transport_controller_->DestroyDtlsTransport(
5586 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5587 if (rtcp_dtls_transport) {
5588 transport_controller_->DestroyDtlsTransport(
5589 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5590 }
5591 return false;
5592 }
5593
5594 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5595 this, &PeerConnection::DestroyRtcpTransport_n);
5596 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5597 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5598 rtp_data_channel_->SignalSentPacket.connect(
5599 this, &PeerConnection::OnSentPacket_w);
Steve Antondb67ba12018-03-19 17:41:42 -07005600 if (uma_observer_) {
5601 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5602 }
Steve Anton75737c02017-11-06 10:37:17 -08005603 }
5604
Steve Anton75737c02017-11-06 10:37:17 -08005605 return true;
5606}
5607
5608Call::Stats PeerConnection::GetCallStats() {
5609 if (!worker_thread()->IsCurrent()) {
5610 return worker_thread()->Invoke<Call::Stats>(
5611 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5612 }
5613 if (call_) {
5614 return call_->GetStats();
5615 } else {
5616 return Call::Stats();
5617 }
5618}
5619
Steve Anton75737c02017-11-06 10:37:17 -08005620bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5621 const std::string& transport_name) {
5622 RTC_DCHECK(network_thread()->IsCurrent());
5623 RTC_DCHECK(sctp_factory_);
5624 cricket::DtlsTransportInternal* tc =
5625 transport_controller_->CreateDtlsTransport_n(
5626 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5627 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5628 RTC_DCHECK(sctp_transport_);
5629 sctp_invoker_.reset(new rtc::AsyncInvoker());
5630 sctp_transport_->SignalReadyToSendData.connect(
5631 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5632 sctp_transport_->SignalDataReceived.connect(
5633 this, &PeerConnection::OnSctpTransportDataReceived_n);
5634 sctp_transport_->SignalStreamClosedRemotely.connect(
5635 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005636 sctp_transport_name_ = transport_name;
5637 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005638 return true;
5639}
5640
5641void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5642 RTC_DCHECK(network_thread()->IsCurrent());
5643 RTC_DCHECK(sctp_transport_);
5644 RTC_DCHECK(sctp_transport_name_);
5645 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005646 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005647 cricket::DtlsTransportInternal* tc =
5648 transport_controller_->CreateDtlsTransport_n(
5649 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5650 sctp_transport_->SetTransportChannel(tc);
5651 transport_controller_->DestroyDtlsTransport_n(
5652 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5653}
5654
5655void PeerConnection::DestroySctpTransport_n() {
5656 RTC_DCHECK(network_thread()->IsCurrent());
5657 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005658 transport_controller_->DestroyDtlsTransport_n(
5659 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005660 sctp_content_name_.reset();
5661 sctp_transport_name_.reset();
5662 sctp_invoker_.reset(nullptr);
5663 sctp_ready_to_send_data_ = false;
5664}
5665
5666void PeerConnection::OnSctpTransportReadyToSendData_n() {
5667 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5668 RTC_DCHECK(network_thread()->IsCurrent());
5669 // Note: Cannot use rtc::Bind here because it will grab a reference to
5670 // PeerConnection and potentially cause PeerConnection to live longer than
5671 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5672 // be destroyed before PeerConnection is destroyed, and at that point all
5673 // pending tasks will be cleared.
5674 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5675 OnSctpTransportReadyToSendData_s(true);
5676 });
5677}
5678
5679void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5680 RTC_DCHECK(signaling_thread()->IsCurrent());
5681 sctp_ready_to_send_data_ = ready;
5682 SignalSctpReadyToSendData(ready);
5683}
5684
5685void PeerConnection::OnSctpTransportDataReceived_n(
5686 const cricket::ReceiveDataParams& params,
5687 const rtc::CopyOnWriteBuffer& payload) {
5688 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5689 RTC_DCHECK(network_thread()->IsCurrent());
5690 // Note: Cannot use rtc::Bind here because it will grab a reference to
5691 // PeerConnection and potentially cause PeerConnection to live longer than
5692 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5693 // be destroyed before PeerConnection is destroyed, and at that point all
5694 // pending tasks will be cleared.
5695 sctp_invoker_->AsyncInvoke<void>(
5696 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5697 OnSctpTransportDataReceived_s(params, payload);
5698 });
5699}
5700
5701void PeerConnection::OnSctpTransportDataReceived_s(
5702 const cricket::ReceiveDataParams& params,
5703 const rtc::CopyOnWriteBuffer& payload) {
5704 RTC_DCHECK(signaling_thread()->IsCurrent());
5705 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5706 // Received OPEN message; parse and signal that a new data channel should
5707 // be created.
5708 std::string label;
5709 InternalDataChannelInit config;
5710 config.id = params.ssrc;
5711 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005712 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5713 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005714 return;
5715 }
5716 config.open_handshake_role = InternalDataChannelInit::kAcker;
5717 OnDataChannelOpenMessage(label, config);
5718 } else {
5719 // Otherwise just forward the signal.
5720 SignalSctpDataReceived(params, payload);
5721 }
5722}
5723
5724void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5725 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5726 RTC_DCHECK(network_thread()->IsCurrent());
5727 sctp_invoker_->AsyncInvoke<void>(
5728 RTC_FROM_HERE, signaling_thread(),
5729 rtc::Bind(&sigslot::signal1<int>::operator(),
5730 &SignalSctpStreamClosedRemotely, sid));
5731}
5732
5733// Returns false if bundle is enabled and rtcp_mux is disabled.
5734bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5735 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5736 if (!bundle_enabled)
5737 return true;
5738
5739 const cricket::ContentGroup* bundle_group =
5740 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5741 RTC_DCHECK(bundle_group != NULL);
5742
5743 const cricket::ContentInfos& contents = desc->contents();
5744 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5745 citer != contents.end(); ++citer) {
5746 const cricket::ContentInfo* content = (&*citer);
5747 RTC_DCHECK(content != NULL);
5748 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005749 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005750 if (!HasRtcpMuxEnabled(content))
5751 return false;
5752 }
5753 }
5754 // RTCP-MUX is enabled in all the contents.
5755 return true;
5756}
5757
5758bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005759 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005760}
5761
Steve Anton8a006912017-12-04 15:25:56 -08005762RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005763 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005764 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005765 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005766 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005767 }
5768
5769 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005771 }
5772
Steve Anton3828c062017-12-06 10:34:51 -08005773 SdpType type = sdesc->GetType();
5774 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5775 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005776 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005777 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005778 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005779 }
5780
5781 // Verify crypto settings.
5782 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005783 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5784 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005785 RTCError crypto_error =
5786 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005787 if (!crypto_error.ok()) {
5788 return crypto_error;
5789 }
Steve Anton75737c02017-11-06 10:37:17 -08005790 }
5791
5792 // Verify ice-ufrag and ice-pwd.
5793 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005794 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5795 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005796 }
5797
5798 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005799 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5800 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005801 }
5802
5803 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5804 // m-lines that do not rtcp-mux enabled.
5805
5806 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005807 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005808 // With an answer we want to compare the new answer session description with
5809 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005810 const cricket::SessionDescription* offer_desc =
5811 (source == cricket::CS_LOCAL) ? remote_description()->description()
5812 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005813 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5814 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5815 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005816 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5817 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005818 }
5819 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005820 // The re-offers should respect the order of m= sections in current
5821 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005822 // With a re-offer, either the current local or current remote descriptions
5823 // could be the most up to date, so we would like to check against both of
5824 // them if they exist. It could be the case that one of them has a 0 port
5825 // for a media section, but the other does not. This is important to check
5826 // against in the case that we are recycling an m= section.
5827 const cricket::SessionDescription* current_desc = nullptr;
5828 const cricket::SessionDescription* secondary_current_desc = nullptr;
5829 if (local_description()) {
5830 current_desc = local_description()->description();
5831 if (remote_description()) {
5832 secondary_current_desc = remote_description()->description();
5833 }
5834 } else if (remote_description()) {
5835 current_desc = remote_description()->description();
5836 }
Steve Anton75737c02017-11-06 10:37:17 -08005837 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005838 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5839 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005840 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5841 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005842 }
5843 }
5844
Steve Anton8a006912017-12-04 15:25:56 -08005845 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005846}
5847
Steve Anton3828c062017-12-06 10:34:51 -08005848bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005849 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005850 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 return (state == PeerConnectionInterface::kStable) ||
5852 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005853 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005854 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005855 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5856 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5857 }
5858}
5859
Steve Anton3828c062017-12-06 10:34:51 -08005860bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005861 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005862 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005863 return (state == PeerConnectionInterface::kStable) ||
5864 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005865 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005866 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005867 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5868 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5869 }
5870}
5871
Steve Antonf8470812017-12-04 10:46:21 -08005872const char* PeerConnection::SessionErrorToString(SessionError error) const {
5873 switch (error) {
5874 case SessionError::kNone:
5875 return "ERROR_NONE";
5876 case SessionError::kContent:
5877 return "ERROR_CONTENT";
5878 case SessionError::kTransport:
5879 return "ERROR_TRANSPORT";
5880 }
5881 RTC_NOTREACHED();
5882 return "";
5883}
5884
Steve Anton75737c02017-11-06 10:37:17 -08005885std::string PeerConnection::GetSessionErrorMsg() {
5886 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005887 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5888 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005889 return desc.str();
5890}
5891
Steve Anton8e20f172018-03-06 10:55:04 -08005892void PeerConnection::ReportSdpFormatReceived(
5893 const SessionDescriptionInterface& remote_offer) {
5894 if (!uma_observer_) {
5895 return;
5896 }
5897 int num_audio_mlines = 0;
5898 int num_video_mlines = 0;
5899 int num_audio_tracks = 0;
5900 int num_video_tracks = 0;
5901 for (const ContentInfo& content : remote_offer.description()->contents()) {
5902 cricket::MediaType media_type = content.media_description()->type();
5903 int num_tracks = std::max(
5904 1, static_cast<int>(content.media_description()->streams().size()));
5905 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5906 num_audio_mlines += 1;
5907 num_audio_tracks += num_tracks;
5908 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5909 num_video_mlines += 1;
5910 num_video_tracks += num_tracks;
5911 }
5912 }
5913 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5914 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5915 format = kSdpFormatReceivedComplexUnifiedPlan;
5916 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5917 format = kSdpFormatReceivedComplexPlanB;
5918 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5919 format = kSdpFormatReceivedSimple;
5920 }
5921 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5922 kSdpFormatReceivedMax);
5923}
5924
Steve Anton0ffaaa22018-02-23 10:31:30 -08005925void PeerConnection::ReportNegotiatedSdpSemantics(
5926 const SessionDescriptionInterface& answer) {
5927 if (!uma_observer_) {
5928 return;
5929 }
5930 switch (answer.description()->msid_signaling()) {
5931 case 0:
5932 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5933 kSdpSemanticNegotiatedNone,
5934 kSdpSemanticNegotiatedMax);
5935 break;
5936 case cricket::kMsidSignalingMediaSection:
5937 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5938 kSdpSemanticNegotiatedUnifiedPlan,
5939 kSdpSemanticNegotiatedMax);
5940 break;
5941 case cricket::kMsidSignalingSsrcAttribute:
5942 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5943 kSdpSemanticNegotiatedPlanB,
5944 kSdpSemanticNegotiatedMax);
5945 break;
5946 case cricket::kMsidSignalingMediaSection |
5947 cricket::kMsidSignalingSsrcAttribute:
5948 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5949 kSdpSemanticNegotiatedMixed,
5950 kSdpSemanticNegotiatedMax);
5951 break;
5952 default:
5953 RTC_NOTREACHED();
5954 }
5955}
5956
Steve Anton75737c02017-11-06 10:37:17 -08005957// We need to check the local/remote description for the Transport instead of
5958// the session, because a new Transport added during renegotiation may have
5959// them unset while the session has them set from the previous negotiation.
5960// Not doing so may trigger the auto generation of transport description and
5961// mess up DTLS identity information, ICE credential, etc.
5962bool PeerConnection::ReadyToUseRemoteCandidate(
5963 const IceCandidateInterface* candidate,
5964 const SessionDescriptionInterface* remote_desc,
5965 bool* valid) {
5966 *valid = true;
5967
5968 const SessionDescriptionInterface* current_remote_desc =
5969 remote_desc ? remote_desc : remote_description();
5970
5971 if (!current_remote_desc) {
5972 return false;
5973 }
5974
5975 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5976 size_t remote_content_size =
5977 current_remote_desc->description()->contents().size();
5978 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005979 RTC_LOG(LS_ERROR)
5980 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5981 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005982
5983 *valid = false;
5984 return false;
5985 }
5986
5987 cricket::ContentInfo content =
5988 current_remote_desc->description()->contents()[mediacontent_index];
5989
5990 const std::string transport_name = GetTransportName(content.name);
5991 if (transport_name.empty()) {
5992 return false;
5993 }
5994 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5995}
5996
5997bool PeerConnection::SrtpRequired() const {
5998 return dtls_enabled_ ||
5999 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6000}
6001
6002void PeerConnection::OnTransportControllerGatheringState(
6003 cricket::IceGatheringState state) {
6004 RTC_DCHECK(signaling_thread()->IsCurrent());
6005 if (state == cricket::kIceGatheringGathering) {
6006 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6007 } else if (state == cricket::kIceGatheringComplete) {
6008 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6009 }
6010}
6011
6012void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006013 std::map<std::string, std::set<cricket::MediaType>>
6014 media_types_by_transport_name;
6015 for (auto transceiver : transceivers_) {
6016 if (transceiver->internal()->channel()) {
6017 const std::string& transport_name =
6018 transceiver->internal()->channel()->transport_name();
6019 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006020 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006021 }
Steve Anton75737c02017-11-06 10:37:17 -08006022 }
6023 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006024 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6025 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006026 }
6027 if (sctp_transport_name_) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006028 media_types_by_transport_name[*sctp_transport_name_].insert(
6029 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006030 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006031 for (const auto& entry : media_types_by_transport_name) {
6032 const std::string& transport_name = entry.first;
6033 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006034 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006035 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006036 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006037 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006038 }
6039 }
6040}
6041// Walk through the ConnectionInfos to gather best connection usage
6042// for IPv4 and IPv6.
6043void PeerConnection::ReportBestConnectionState(
6044 const cricket::TransportStats& stats) {
6045 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006046 for (const cricket::TransportChannelStats& channel_stats :
6047 stats.channel_stats) {
6048 for (const cricket::ConnectionInfo& connection_info :
6049 channel_stats.connection_infos) {
6050 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006051 continue;
6052 }
6053
6054 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006055 const cricket::Candidate& local = connection_info.local_candidate;
6056 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006057
6058 // Increment the counter for IceCandidatePairType.
6059 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6060 (local.type() == RELAY_PORT_TYPE &&
6061 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6062 type = kEnumCounterIceCandidatePairTypeTcp;
6063 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6064 type = kEnumCounterIceCandidatePairTypeUdp;
6065 } else {
6066 RTC_CHECK(0);
6067 }
6068 metrics_observer()->IncrementEnumCounter(
6069 type, GetIceCandidatePairCounter(local, remote),
6070 kIceCandidatePairMax);
6071
6072 // Increment the counter for IP type.
6073 if (local.address().family() == AF_INET) {
6074 metrics_observer()->IncrementEnumCounter(
6075 kEnumCounterAddressFamily, kBestConnections_IPv4,
6076 kPeerConnectionAddressFamilyCounter_Max);
6077
6078 } else if (local.address().family() == AF_INET6) {
6079 metrics_observer()->IncrementEnumCounter(
6080 kEnumCounterAddressFamily, kBestConnections_IPv6,
6081 kPeerConnectionAddressFamilyCounter_Max);
6082 } else {
6083 RTC_CHECK(0);
6084 }
6085
6086 return;
6087 }
6088 }
6089}
6090
6091void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006092 const cricket::TransportStats& stats,
6093 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006094 RTC_DCHECK(metrics_observer());
6095 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6096 return;
6097 }
6098
6099 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6100 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6101 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6102 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6103 return;
6104 }
6105
Steve Antonc7b964c2018-02-01 14:39:45 -08006106 for (cricket::MediaType media_type : media_types) {
6107 PeerConnectionEnumCounterType srtp_counter_type;
6108 PeerConnectionEnumCounterType ssl_counter_type;
6109 switch (media_type) {
6110 case cricket::MEDIA_TYPE_AUDIO:
6111 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6112 ssl_counter_type = kEnumCounterAudioSslCipher;
6113 break;
6114 case cricket::MEDIA_TYPE_VIDEO:
6115 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6116 ssl_counter_type = kEnumCounterVideoSslCipher;
6117 break;
6118 case cricket::MEDIA_TYPE_DATA:
6119 srtp_counter_type = kEnumCounterDataSrtpCipher;
6120 ssl_counter_type = kEnumCounterDataSslCipher;
6121 break;
6122 default:
6123 RTC_NOTREACHED();
6124 continue;
6125 }
6126 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6127 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6128 srtp_crypto_suite);
6129 }
6130 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6131 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6132 ssl_cipher_suite);
6133 }
Steve Anton75737c02017-11-06 10:37:17 -08006134 }
6135}
6136
6137void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6138 RTC_DCHECK(worker_thread()->IsCurrent());
6139 RTC_DCHECK(call_);
6140 call_->OnSentPacket(sent_packet);
6141}
6142
6143const std::string PeerConnection::GetTransportName(
6144 const std::string& content_name) {
6145 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006146 if (channel) {
6147 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006148 }
Steve Anton6fec8802017-12-04 10:37:29 -08006149 if (sctp_transport_) {
6150 RTC_DCHECK(sctp_content_name_);
6151 RTC_DCHECK(sctp_transport_name_);
6152 if (content_name == *sctp_content_name_) {
6153 return *sctp_transport_name_;
6154 }
6155 }
6156 // Return an empty string if failed to retrieve the transport name.
6157 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006158}
6159
6160void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
6161 RTC_DCHECK(network_thread()->IsCurrent());
6162 transport_controller_->DestroyDtlsTransport_n(
6163 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6164}
6165
Steve Anton6fec8802017-12-04 10:37:29 -08006166void PeerConnection::DestroyTransceiverChannel(
6167 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6168 transceiver) {
6169 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006170
Steve Anton6fec8802017-12-04 10:37:29 -08006171 cricket::BaseChannel* channel = transceiver->internal()->channel();
6172 if (channel) {
6173 transceiver->internal()->SetChannel(nullptr);
6174 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006175 }
6176}
6177
6178void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006179 if (rtp_data_channel_) {
6180 OnDataChannelDestroyed();
6181 DestroyBaseChannel(rtp_data_channel_);
6182 rtp_data_channel_ = nullptr;
6183 }
6184
6185 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6186 // grab a reference to this PeerConnection. If this is called from the
6187 // PeerConnection destructor, the RefCountedObject vtable will have already
6188 // been destroyed (since it is a subclass of PeerConnection) and using
6189 // rtc::Bind will cause "Pure virtual function called" error to appear.
6190
6191 if (sctp_transport_) {
6192 OnDataChannelDestroyed();
6193 network_thread()->Invoke<void>(RTC_FROM_HERE,
6194 [this] { DestroySctpTransport_n(); });
6195 }
6196}
6197
6198void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6199 RTC_DCHECK(channel);
Zhi Huang95e7dbb2018-03-29 00:08:03 +00006200 RTC_DCHECK(channel->rtp_dtls_transport());
6201
Steve Anton6fec8802017-12-04 10:37:29 -08006202 // Need to cache these before destroying the base channel so that we do not
6203 // access uninitialized memory.
Zhi Huang95e7dbb2018-03-29 00:08:03 +00006204 const std::string transport_name =
6205 channel->rtp_dtls_transport()->transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006206 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
6207
6208 switch (channel->media_type()) {
6209 case cricket::MEDIA_TYPE_AUDIO:
6210 channel_manager()->DestroyVoiceChannel(
6211 static_cast<cricket::VoiceChannel*>(channel));
6212 break;
6213 case cricket::MEDIA_TYPE_VIDEO:
6214 channel_manager()->DestroyVideoChannel(
6215 static_cast<cricket::VideoChannel*>(channel));
6216 break;
6217 case cricket::MEDIA_TYPE_DATA:
6218 channel_manager()->DestroyRtpDataChannel(
6219 static_cast<cricket::RtpDataChannel*>(channel));
6220 break;
6221 default:
6222 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6223 break;
6224 }
6225
6226 // |channel| can no longer be used.
6227
Steve Anton75737c02017-11-06 10:37:17 -08006228 transport_controller_->DestroyDtlsTransport(
6229 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
6230 if (need_to_delete_rtcp) {
6231 transport_controller_->DestroyDtlsTransport(
6232 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
6233 }
6234}
6235
Harald Alvestrand89061872018-01-02 14:08:34 +01006236void PeerConnection::ClearStatsCache() {
6237 if (stats_collector_) {
6238 stats_collector_->ClearCachedStatsReport();
6239 }
6240}
6241
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006242} // namespace webrtc