blob: 8431707b66b598f043f87fb7fd6769d86aa0b884 [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"
Elad Alon83ccca12017-10-04 13:18:26 +020025#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "logging/rtc_event_log/rtc_event_log.h"
27#include "media/sctp/sctptransport.h"
28#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080029#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "pc/channelmanager.h"
31#include "pc/dtmfsender.h"
32#include "pc/mediastream.h"
33#include "pc/mediastreamobserver.h"
34#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080035#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020036#include "pc/rtpreceiver.h"
37#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080038#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080039#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "pc/streamcollection.h"
41#include "pc/videocapturertracksource.h"
42#include "pc/videotrack.h"
43#include "rtc_base/bind.h"
44#include "rtc_base/checks.h"
45#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010046#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020047#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020048#include "rtc_base/stringencode.h"
49#include "rtc_base/stringutils.h"
50#include "rtc_base/trace_event.h"
51#include "system_wrappers/include/clock.h"
52#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000053
Steve Anton75737c02017-11-06 10:37:17 -080054using cricket::ContentInfo;
55using cricket::ContentInfos;
56using cricket::MediaContentDescription;
57using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080058using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080059using cricket::TransportInfo;
60
61using cricket::LOCAL_PORT_TYPE;
62using cricket::STUN_PORT_TYPE;
63using cricket::RELAY_PORT_TYPE;
64using cricket::PRFLX_PORT_TYPE;
65
Steve Antonba818672017-11-06 10:21:57 -080066namespace webrtc {
67
Steve Anton75737c02017-11-06 10:37:17 -080068// Error messages
69const char kBundleWithoutRtcpMux[] =
70 "rtcp-mux must be enabled when BUNDLE "
71 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080072const char kInvalidCandidates[] = "Description contains invalid candidates.";
73const char kInvalidSdp[] = "Invalid session description.";
74const char kMlineMismatchInAnswer[] =
75 "The order of m-lines in answer doesn't match order in offer. Rejecting "
76 "answer.";
77const char kMlineMismatchInSubsequentOffer[] =
78 "The order of m-lines in subsequent offer doesn't match order from "
79 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080080const char kSdpWithoutDtlsFingerprint[] =
81 "Called with SDP without DTLS fingerprint.";
82const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
83const char kSdpWithoutIceUfragPwd[] =
84 "Called with SDP without ice-ufrag and ice-pwd.";
85const char kSessionError[] = "Session error code: ";
86const char kSessionErrorDesc[] = "Session error description: ";
87const char kDtlsSrtpSetupFailureRtp[] =
88 "Couldn't set up DTLS-SRTP on RTP channel.";
89const char kDtlsSrtpSetupFailureRtcp[] =
90 "Couldn't set up DTLS-SRTP on RTCP channel.";
91const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
Steve Anton75737c02017-11-06 10:37:17 -080093namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
deadbeefab9b2d12015-10-14 11:33:11 -070095static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080096static const char kDefaultAudioSenderId[] = "defaulta0";
97static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070098
zhihuang8f65cdf2016-05-06 18:40:30 -070099// The length of RTCP CNAMEs.
100static const int kRtcpCnameLength = 16;
101
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000103 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700105 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800107 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108};
109
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000110struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000111 explicit SetSessionDescriptionMsg(
112 webrtc::SetSessionDescriptionObserver* observer)
113 : observer(observer) {
114 }
115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000117 std::string error;
118};
119
deadbeefab9b2d12015-10-14 11:33:11 -0700120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
126 std::string error;
127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
132 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000134 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000135 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000136};
137
deadbeefab9b2d12015-10-14 11:33:11 -0700138// Check if we can send |new_stream| on a PeerConnection.
139bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
140 webrtc::MediaStreamInterface* new_stream) {
141 if (!new_stream || !current_streams) {
142 return false;
143 }
144 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100145 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
146 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700147 return false;
148 }
149 return true;
150}
151
deadbeef5e97fb52015-10-15 12:49:08 -0700152// If the direction is "recvonly" or "inactive", treat the description
153// as containing no streams.
154// See: https://code.google.com/p/webrtc/issues/detail?id=5054
155std::vector<cricket::StreamParams> GetActiveStreams(
156 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800157 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700158 ? desc->streams()
159 : std::vector<cricket::StreamParams>();
160}
161
deadbeefab9b2d12015-10-14 11:33:11 -0700162bool IsValidOfferToReceiveMedia(int value) {
163 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
164 return (value >= Options::kUndefined) &&
165 (value <= Options::kMaxOfferToReceiveMedia);
166}
167
zhihuang1c378ed2017-08-17 14:10:50 -0700168// Add options to |[audio/video]_media_description_options| from |senders|.
169void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700170 const std::vector<rtc::scoped_refptr<
171 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700172 cricket::MediaDescriptionOptions* audio_media_description_options,
173 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700174 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700175 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
176 if (audio_media_description_options) {
177 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700178 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700179 }
180 } else {
181 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
182 if (video_media_description_options) {
183 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700184 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700185 }
186 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700187 }
zhihuang1c378ed2017-08-17 14:10:50 -0700188}
olka3c747662017-08-17 06:50:32 -0700189
zhihuang1c378ed2017-08-17 14:10:50 -0700190// Add options to |session_options| from |rtp_data_channels|.
191void AddRtpDataChannelOptions(
192 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
193 rtp_data_channels,
194 cricket::MediaDescriptionOptions* data_media_description_options) {
195 if (!data_media_description_options) {
196 return;
197 }
deadbeefab9b2d12015-10-14 11:33:11 -0700198 // Check for data channels.
199 for (const auto& kv : rtp_data_channels) {
200 const DataChannel* channel = kv.second;
201 if (channel->state() == DataChannel::kConnecting ||
202 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700203 // Legacy RTP data channels are signaled with the track/stream ID set to
204 // the data channel's label.
205 data_media_description_options->AddRtpDataChannel(channel->label(),
206 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700207 }
208 }
209}
210
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700211uint32_t ConvertIceTransportTypeToCandidateFilter(
212 PeerConnectionInterface::IceTransportsType type) {
213 switch (type) {
214 case PeerConnectionInterface::kNone:
215 return cricket::CF_NONE;
216 case PeerConnectionInterface::kRelay:
217 return cricket::CF_RELAY;
218 case PeerConnectionInterface::kNoHost:
219 return (cricket::CF_ALL & ~cricket::CF_HOST);
220 case PeerConnectionInterface::kAll:
221 return cricket::CF_ALL;
222 default:
nissec80e7412017-01-11 05:56:46 -0800223 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700224 }
225 return cricket::CF_NONE;
226}
227
deadbeef293e9262017-01-11 12:28:30 -0800228// Helper to set an error and return from a method.
229bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
230 if (error) {
231 error->set_type(type);
232 }
233 return type == webrtc::RTCErrorType::NONE;
234}
235
Steve Anton038834f2017-07-14 15:59:59 -0700236bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
237 if (error_out) {
238 *error_out = std::move(error);
239 }
240 return error.ok();
241}
242
Steve Antonba818672017-11-06 10:21:57 -0800243std::string GetSignalingStateString(
244 PeerConnectionInterface::SignalingState state) {
245 switch (state) {
246 case PeerConnectionInterface::kStable:
247 return "kStable";
248 case PeerConnectionInterface::kHaveLocalOffer:
249 return "kHaveLocalOffer";
250 case PeerConnectionInterface::kHaveLocalPrAnswer:
251 return "kHavePrAnswer";
252 case PeerConnectionInterface::kHaveRemoteOffer:
253 return "kHaveRemoteOffer";
254 case PeerConnectionInterface::kHaveRemotePrAnswer:
255 return "kHaveRemotePrAnswer";
256 case PeerConnectionInterface::kClosed:
257 return "kClosed";
258 }
259 RTC_NOTREACHED();
260 return "";
261}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700262
Steve Anton75737c02017-11-06 10:37:17 -0800263IceCandidatePairType GetIceCandidatePairCounter(
264 const cricket::Candidate& local,
265 const cricket::Candidate& remote) {
266 const auto& l = local.type();
267 const auto& r = remote.type();
268 const auto& host = LOCAL_PORT_TYPE;
269 const auto& srflx = STUN_PORT_TYPE;
270 const auto& relay = RELAY_PORT_TYPE;
271 const auto& prflx = PRFLX_PORT_TYPE;
272 if (l == host && r == host) {
273 bool local_private = IPIsPrivate(local.address().ipaddr());
274 bool remote_private = IPIsPrivate(remote.address().ipaddr());
275 if (local_private) {
276 if (remote_private) {
277 return kIceCandidatePairHostPrivateHostPrivate;
278 } else {
279 return kIceCandidatePairHostPrivateHostPublic;
280 }
281 } else {
282 if (remote_private) {
283 return kIceCandidatePairHostPublicHostPrivate;
284 } else {
285 return kIceCandidatePairHostPublicHostPublic;
286 }
287 }
288 }
289 if (l == host && r == srflx)
290 return kIceCandidatePairHostSrflx;
291 if (l == host && r == relay)
292 return kIceCandidatePairHostRelay;
293 if (l == host && r == prflx)
294 return kIceCandidatePairHostPrflx;
295 if (l == srflx && r == host)
296 return kIceCandidatePairSrflxHost;
297 if (l == srflx && r == srflx)
298 return kIceCandidatePairSrflxSrflx;
299 if (l == srflx && r == relay)
300 return kIceCandidatePairSrflxRelay;
301 if (l == srflx && r == prflx)
302 return kIceCandidatePairSrflxPrflx;
303 if (l == relay && r == host)
304 return kIceCandidatePairRelayHost;
305 if (l == relay && r == srflx)
306 return kIceCandidatePairRelaySrflx;
307 if (l == relay && r == relay)
308 return kIceCandidatePairRelayRelay;
309 if (l == relay && r == prflx)
310 return kIceCandidatePairRelayPrflx;
311 if (l == prflx && r == host)
312 return kIceCandidatePairPrflxHost;
313 if (l == prflx && r == srflx)
314 return kIceCandidatePairPrflxSrflx;
315 if (l == prflx && r == relay)
316 return kIceCandidatePairPrflxRelay;
317 return kIceCandidatePairMax;
318}
319
320// Verify that the order of media sections in |new_desc| matches
321// |existing_desc|. The number of m= sections in |new_desc| should be no less
322// than |existing_desc|.
323bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
324 const SessionDescription* new_desc) {
325 if (!existing_desc || !new_desc) {
326 return false;
327 }
328
329 if (existing_desc->contents().size() > new_desc->contents().size()) {
330 return false;
331 }
332
333 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
Steve Antondcc3c022017-12-22 16:02:54 -0800334 if (existing_desc->contents()[i].rejected) {
335 // If the media section can be recycled, it's valid for the MID and media
336 // type to change.
337 continue;
338 }
Steve Anton75737c02017-11-06 10:37:17 -0800339 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
340 return false;
341 }
342 const MediaContentDescription* new_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800343 new_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800344 const MediaContentDescription* existing_desc_mdesc =
Steve Antonb1c1de12017-12-21 15:14:30 -0800345 existing_desc->contents()[i].media_description();
Steve Anton75737c02017-11-06 10:37:17 -0800346 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
347 return false;
348 }
349 }
350 return true;
351}
352
353bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
354 const SessionDescription* desc2) {
355 if (!desc1 || !desc2) {
356 return false;
357 }
358 return desc1->contents().size() == desc2->contents().size();
359}
360
361// Checks that each non-rejected content has SDES crypto keys or a DTLS
362// fingerprint, unless it's in a BUNDLE group, in which case only the
363// BUNDLE-tag section (first media section/description in the BUNDLE group)
364// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
365// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
366// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800367RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800368 const cricket::ContentGroup* bundle =
369 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800370 for (const cricket::ContentInfo& content_info : desc->contents()) {
371 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 continue;
373 }
Steve Anton8a006912017-12-04 15:25:56 -0800374 const std::string& mid = content_info.name;
375 if (bundle && bundle->HasContentName(mid) &&
376 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800377 // This isn't the first media section in the BUNDLE group, so it's not
378 // required to have crypto attributes, since only the crypto attributes
379 // from the first section actually get used.
380 continue;
381 }
382
383 // If the content isn't rejected or bundled into another m= section, crypto
384 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800385 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800386 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800387 if (!media || !tinfo) {
388 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800389 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800390 }
391 if (dtls_enabled) {
392 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100393 RTC_LOG(LS_WARNING)
394 << "Session description must have DTLS fingerprint if "
395 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800396 return RTCError(RTCErrorType::INVALID_PARAMETER,
397 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800398 }
399 } else {
400 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100401 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800402 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800403 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800404 }
405 }
406 }
Steve Anton8a006912017-12-04 15:25:56 -0800407 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800408}
409
410// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
411// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
412// media section/description in the BUNDLE group) needs a ufrag and pwd.
413bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
414 const cricket::ContentGroup* bundle =
415 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800416 for (const cricket::ContentInfo& content_info : desc->contents()) {
417 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800418 continue;
419 }
Steve Anton8a006912017-12-04 15:25:56 -0800420 const std::string& mid = content_info.name;
421 if (bundle && bundle->HasContentName(mid) &&
422 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800423 // This isn't the first media section in the BUNDLE group, so it's not
424 // required to have ufrag/password, since only the ufrag/password from
425 // the first section actually get used.
426 continue;
427 }
428
429 // If the content isn't rejected or bundled into another m= section,
430 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800431 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800432 if (!tinfo) {
433 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800435 return false;
436 }
437 if (tinfo->description.ice_ufrag.empty() ||
438 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100439 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800440 return false;
441 }
442 }
443 return true;
444}
445
446bool GetTrackIdBySsrc(const SessionDescription* session_description,
447 uint32_t ssrc,
448 std::string* track_id) {
449 RTC_DCHECK(track_id != NULL);
450
Steve Antonb1c1de12017-12-21 15:14:30 -0800451 const cricket::AudioContentDescription* audio_desc =
452 cricket::GetFirstAudioContentDescription(session_description);
453 if (audio_desc) {
454 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800455 if (found) {
456 *track_id = found->id;
457 return true;
458 }
459 }
460
Steve Antonb1c1de12017-12-21 15:14:30 -0800461 const cricket::VideoContentDescription* video_desc =
462 cricket::GetFirstVideoContentDescription(session_description);
463 if (video_desc) {
464 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800465 if (found) {
466 *track_id = found->id;
467 return true;
468 }
469 }
470 return false;
471}
472
473// Get the SCTP port out of a SessionDescription.
474// Return -1 if not found.
475int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800476 const cricket::DataContentDescription* data_desc =
477 GetFirstDataContentDescription(session_description);
478 RTC_DCHECK(data_desc);
479 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 return -1;
481 }
Steve Anton75737c02017-11-06 10:37:17 -0800482 std::string value;
483 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
484 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800485 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 if (!codec.Matches(match_pattern)) {
487 continue;
488 }
489 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
490 return rtc::FromString<int>(value);
491 }
492 }
493 return -1;
494}
495
Steve Anton75737c02017-11-06 10:37:17 -0800496// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
497bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
498 const SessionDescriptionInterface* new_desc,
499 const std::string& content_name) {
500 if (!old_desc) {
501 return false;
502 }
503 const SessionDescription* new_sd = new_desc->description();
504 const SessionDescription* old_sd = old_desc->description();
505 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
506 if (!cinfo || cinfo->rejected) {
507 return false;
508 }
509 // If the content isn't rejected, check if ufrag and password has changed.
510 const cricket::TransportDescription* new_transport_desc =
511 new_sd->GetTransportDescriptionByName(content_name);
512 const cricket::TransportDescription* old_transport_desc =
513 old_sd->GetTransportDescriptionByName(content_name);
514 if (!new_transport_desc || !old_transport_desc) {
515 // No transport description exists. This is not an ICE restart.
516 return false;
517 }
518 if (cricket::IceCredentialsChanged(
519 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
520 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100521 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
522 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800523 return true;
524 }
525 return false;
526}
527
528} // namespace
529
Henrik Boström31638672017-11-23 17:48:32 +0100530// Upon completion, posts a task to execute the callback of the
531// SetSessionDescriptionObserver asynchronously on the same thread. At this
532// point, the state of the peer connection might no longer reflect the effects
533// of the SetRemoteDescription operation, as the peer connection could have been
534// modified during the post.
535// TODO(hbos): Remove this class once we remove the version of
536// PeerConnectionInterface::SetRemoteDescription() that takes a
537// SetSessionDescriptionObserver as an argument.
538class PeerConnection::SetRemoteDescriptionObserverAdapter
539 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
540 public:
541 SetRemoteDescriptionObserverAdapter(
542 rtc::scoped_refptr<PeerConnection> pc,
543 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
544 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
545
546 // SetRemoteDescriptionObserverInterface implementation.
547 void OnSetRemoteDescriptionComplete(RTCError error) override {
548 if (error.ok())
549 pc_->PostSetSessionDescriptionSuccess(wrapper_);
550 else
551 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
552 }
553
554 private:
555 rtc::scoped_refptr<PeerConnection> pc_;
556 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
557};
558
deadbeef293e9262017-01-11 12:28:30 -0800559bool PeerConnectionInterface::RTCConfiguration::operator==(
560 const PeerConnectionInterface::RTCConfiguration& o) const {
561 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700562 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800563 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000564 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700565 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800566 BundlePolicy bundle_policy;
567 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700568 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
569 int ice_candidate_pool_size;
570 bool disable_ipv6;
571 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700572 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700573 bool enable_rtp_data_channel;
574 rtc::Optional<int> screencast_min_bitrate;
575 rtc::Optional<bool> combined_audio_video_bwe;
576 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800577 TcpCandidatePolicy tcp_candidate_policy;
578 CandidateNetworkPolicy candidate_network_policy;
579 int audio_jitter_buffer_max_packets;
580 bool audio_jitter_buffer_fast_accelerate;
581 int ice_connection_receiving_timeout;
582 int ice_backup_candidate_pair_ping_interval;
583 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800584 bool prioritize_most_likely_ice_candidate_pairs;
585 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800586 bool prune_turn_ports;
587 bool presume_writable_when_fully_relayed;
588 bool enable_ice_renomination;
589 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800590 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700591 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200592 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800593 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800594 };
595 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
596 "Did you add something to RTCConfiguration and forget to "
597 "update operator==?");
598 return type == o.type && servers == o.servers &&
599 bundle_policy == o.bundle_policy &&
600 rtcp_mux_policy == o.rtcp_mux_policy &&
601 tcp_candidate_policy == o.tcp_candidate_policy &&
602 candidate_network_policy == o.candidate_network_policy &&
603 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
604 audio_jitter_buffer_fast_accelerate ==
605 o.audio_jitter_buffer_fast_accelerate &&
606 ice_connection_receiving_timeout ==
607 o.ice_connection_receiving_timeout &&
608 ice_backup_candidate_pair_ping_interval ==
609 o.ice_backup_candidate_pair_ping_interval &&
610 continual_gathering_policy == o.continual_gathering_policy &&
611 certificates == o.certificates &&
612 prioritize_most_likely_ice_candidate_pairs ==
613 o.prioritize_most_likely_ice_candidate_pairs &&
614 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800615 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700616 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800617 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800618 screencast_min_bitrate == o.screencast_min_bitrate &&
619 combined_audio_video_bwe == o.combined_audio_video_bwe &&
620 enable_dtls_srtp == o.enable_dtls_srtp &&
621 ice_candidate_pool_size == o.ice_candidate_pool_size &&
622 prune_turn_ports == o.prune_turn_ports &&
623 presume_writable_when_fully_relayed ==
624 o.presume_writable_when_fully_relayed &&
625 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800626 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700627 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200628 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800629 turn_customizer == o.turn_customizer &&
630 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800631}
632
633bool PeerConnectionInterface::RTCConfiguration::operator!=(
634 const PeerConnectionInterface::RTCConfiguration& o) const {
635 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800636}
637
zhihuang8f65cdf2016-05-06 18:40:30 -0700638// Generate a RTCP CNAME when a PeerConnection is created.
639std::string GenerateRtcpCname() {
640 std::string cname;
641 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100642 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800643 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700644 }
645 return cname;
646}
647
zhihuang1c378ed2017-08-17 14:10:50 -0700648bool ValidateOfferAnswerOptions(
649 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
650 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
651 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700652}
653
zhihuang1c378ed2017-08-17 14:10:50 -0700654// From |rtc_options|, fill parts of |session_options| shared by all generated
655// m= sections (in other words, nothing that involves a map/array).
656void ExtractSharedMediaSessionOptions(
657 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
658 cricket::MediaSessionOptions* session_options) {
659 session_options->vad_enabled = rtc_options.voice_activity_detection;
660 session_options->bundle_enabled = rtc_options.use_rtp_mux;
661}
zhihuanga77e6bb2017-08-14 18:17:48 -0700662
zhihuang1c378ed2017-08-17 14:10:50 -0700663bool ConvertConstraintsToOfferAnswerOptions(
664 const MediaConstraintsInterface* constraints,
665 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700666 if (!constraints) {
667 return true;
668 }
zhihuang1c378ed2017-08-17 14:10:50 -0700669
670 bool value = false;
671 size_t mandatory_constraints_satisfied = 0;
672
673 if (FindConstraint(constraints,
674 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
675 &mandatory_constraints_satisfied)) {
676 offer_answer_options->offer_to_receive_audio =
677 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
678 kOfferToReceiveMediaTrue
679 : 0;
680 }
681
682 if (FindConstraint(constraints,
683 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
684 &mandatory_constraints_satisfied)) {
685 offer_answer_options->offer_to_receive_video =
686 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
687 kOfferToReceiveMediaTrue
688 : 0;
689 }
690 if (FindConstraint(constraints,
691 MediaConstraintsInterface::kVoiceActivityDetection, &value,
692 &mandatory_constraints_satisfied)) {
693 offer_answer_options->voice_activity_detection = value;
694 }
695 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->use_rtp_mux = value;
698 }
699 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
700 &value, &mandatory_constraints_satisfied)) {
701 offer_answer_options->ice_restart = value;
702 }
703
deadbeefab9b2d12015-10-14 11:33:11 -0700704 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
705}
706
zhihuang38ede132017-06-15 12:52:32 -0700707PeerConnection::PeerConnection(PeerConnectionFactory* factory,
708 std::unique_ptr<RtcEventLog> event_log,
709 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000710 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700711 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700712 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700713 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700714 remote_streams_(StreamCollection::Create()),
715 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716
717PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100718 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800719 RTC_DCHECK_RUN_ON(signaling_thread());
720
Steve Anton8af21862017-12-15 11:20:13 -0800721 // Need to stop transceivers before destroying the stats collector because
722 // AudioRtpSender has a reference to the StatsCollector it will update when
723 // stopping.
724 for (auto transceiver : transceivers_) {
725 transceiver->Stop();
726 }
Steve Anton4171afb2017-11-20 10:20:22 -0800727
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700728 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800729 if (stats_collector_) {
730 stats_collector_->WaitForPendingRequest();
731 stats_collector_ = nullptr;
732 }
Steve Anton75737c02017-11-06 10:37:17 -0800733
Steve Anton8af21862017-12-15 11:20:13 -0800734 // Don't destroy BaseChannels until after stats has been cleaned up so that
735 // the last stats request can still read from the channels.
736 DestroyAllChannels();
737
Mirko Bonadei675513b2017-11-09 11:09:25 +0100738 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800739
740 webrtc_session_desc_factory_.reset();
741 sctp_invoker_.reset();
742 sctp_factory_.reset();
743 transport_controller_.reset();
744
deadbeef91dd5672016-05-18 16:55:30 -0700745 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700746 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700747 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700748 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700749 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700750 call_.reset();
751 event_log_.reset();
752 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000753}
754
Steve Anton8af21862017-12-15 11:20:13 -0800755void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800756 // Destroy video channels first since they may have a pointer to a voice
757 // channel.
758 for (auto transceiver : transceivers_) {
759 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
760 DestroyTransceiverChannel(transceiver);
761 }
762 }
763 for (auto transceiver : transceivers_) {
764 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
765 DestroyTransceiverChannel(transceiver);
766 }
767 }
768 DestroyDataChannel();
769}
770
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000771bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000772 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700773 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200774 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800775 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100776 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700777
778 RTCError config_error = ValidateConfiguration(configuration);
779 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100780 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700781 return false;
782 }
783
deadbeef293e9262017-01-11 12:28:30 -0800784 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100785 RTC_LOG(LS_ERROR)
786 << "PeerConnection initialized without a PortAllocator? "
787 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800788 return false;
789 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200790
deadbeef653b8e02015-11-11 12:55:10 -0800791 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800792 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100793 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
794 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800795 return false;
796 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000797 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800798 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800799
deadbeef91dd5672016-05-18 16:55:30 -0700800 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700801 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700802 if (!network_thread()->Invoke<bool>(
803 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
804 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 return false;
806 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807
Steve Anton75737c02017-11-06 10:37:17 -0800808 // RFC 3264: The numeric value of the session id and version in the
809 // o line MUST be representable with a "64 bit signed integer".
810 // Due to this constraint session id |session_id_| is max limited to
811 // LLONG_MAX.
812 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
813 transport_controller_.reset(factory_->CreateTransportController(
814 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
815 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
816 transport_controller_->SignalConnectionState.connect(
817 this, &PeerConnection::OnTransportControllerConnectionState);
818 transport_controller_->SignalGatheringState.connect(
819 this, &PeerConnection::OnTransportControllerGatheringState);
820 transport_controller_->SignalCandidatesGathered.connect(
821 this, &PeerConnection::OnTransportControllerCandidatesGathered);
822 transport_controller_->SignalCandidatesRemoved.connect(
823 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
824 transport_controller_->SignalDtlsHandshakeError.connect(
825 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
826
827 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700828
deadbeefab9b2d12015-10-14 11:33:11 -0700829 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700830 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
Steve Antonba818672017-11-06 10:21:57 -0800832 configuration_ = configuration;
833
Steve Anton75737c02017-11-06 10:37:17 -0800834 const PeerConnectionFactoryInterface::Options& options = factory_->options();
835
836 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
837
838 // Obtain a certificate from RTCConfiguration if any were provided (optional).
839 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
840 if (!configuration.certificates.empty()) {
841 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
842 // just picking the first one. The decision should be made based on the DTLS
843 // handshake. The DTLS negotiations need to know about all certificates.
844 certificate = configuration.certificates[0];
845 }
846
Steve Antond25da372017-11-06 14:50:29 -0800847 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800848
849 if (options.disable_encryption) {
850 dtls_enabled_ = false;
851 } else {
852 // Enable DTLS by default if we have an identity store or a certificate.
853 dtls_enabled_ = (cert_generator || certificate);
854 // |configuration| can override the default |dtls_enabled_| value.
855 if (configuration.enable_dtls_srtp) {
856 dtls_enabled_ = *(configuration.enable_dtls_srtp);
857 }
858 }
859
860 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
861 // It takes precendence over the disable_sctp_data_channels
862 // PeerConnectionFactoryInterface::Options.
863 if (configuration.enable_rtp_data_channel) {
864 data_channel_type_ = cricket::DCT_RTP;
865 } else {
866 // DTLS has to be enabled to use SCTP.
867 if (!options.disable_sctp_data_channels && dtls_enabled_) {
868 data_channel_type_ = cricket::DCT_SCTP;
869 }
870 }
871
872 video_options_.screencast_min_bitrate_kbps =
873 configuration.screencast_min_bitrate;
874 audio_options_.combined_audio_video_bwe =
875 configuration.combined_audio_video_bwe;
876
877 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100878 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800879
880 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100881 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800882
883 // Whether the certificate generator/certificate is null or not determines
884 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
885 // the right instructions by clearing the variables if needed.
886 if (!dtls_enabled_) {
887 cert_generator.reset();
888 certificate = nullptr;
889 } else if (certificate) {
890 // Favor generated certificate over the certificate generator.
891 cert_generator.reset();
892 }
893
894 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
895 signaling_thread(), channel_manager(), this, session_id(),
896 std::move(cert_generator), certificate));
897 webrtc_session_desc_factory_->SignalCertificateReady.connect(
898 this, &PeerConnection::OnCertificateReady);
899
900 if (options.disable_encryption) {
901 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
902 }
903
904 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
905 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906
Steve Anton4171afb2017-11-20 10:20:22 -0800907 // Add default audio/video transceivers for Plan B SDP.
908 if (!IsUnifiedPlan()) {
909 transceivers_.push_back(
910 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
911 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
912 transceivers_.push_back(
913 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
914 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
915 }
916
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return true;
918}
919
Steve Anton038834f2017-07-14 15:59:59 -0700920RTCError PeerConnection::ValidateConfiguration(
921 const RTCConfiguration& config) const {
922 if (config.ice_regather_interval_range &&
923 config.continual_gathering_policy == GATHER_ONCE) {
924 return RTCError(RTCErrorType::INVALID_PARAMETER,
925 "ice_regather_interval_range specified but continual "
926 "gathering policy is GATHER_ONCE");
927 }
928 return RTCError::OK();
929}
930
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000931rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700933 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000934}
935
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000936rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700938 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000939}
940
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000941bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100942 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000943 if (IsClosed()) {
944 return false;
945 }
deadbeefab9b2d12015-10-14 11:33:11 -0700946 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947 return false;
948 }
deadbeefab9b2d12015-10-14 11:33:11 -0700949
950 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800951 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
952 observer->SignalAudioTrackAdded.connect(this,
953 &PeerConnection::OnAudioTrackAdded);
954 observer->SignalAudioTrackRemoved.connect(
955 this, &PeerConnection::OnAudioTrackRemoved);
956 observer->SignalVideoTrackAdded.connect(this,
957 &PeerConnection::OnVideoTrackAdded);
958 observer->SignalVideoTrackRemoved.connect(
959 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700960 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700961
deadbeefab9b2d12015-10-14 11:33:11 -0700962 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700963 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700964 }
965 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700966 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700967 }
968
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000969 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000970 observer_->OnRenegotiationNeeded();
971 return true;
972}
973
974void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100975 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700976 if (!IsClosed()) {
977 for (const auto& track : local_stream->GetAudioTracks()) {
978 RemoveAudioTrack(track.get(), local_stream);
979 }
980 for (const auto& track : local_stream->GetVideoTracks()) {
981 RemoveVideoTrack(track.get(), local_stream);
982 }
deadbeefab9b2d12015-10-14 11:33:11 -0700983 }
deadbeefab9b2d12015-10-14 11:33:11 -0700984 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800985 stream_observers_.erase(
986 std::remove_if(
987 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700988 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800989 return observer->stream()->label().compare(local_stream->label()) ==
990 0;
991 }),
992 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700993
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000994 if (IsClosed()) {
995 return;
996 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997 observer_->OnRenegotiationNeeded();
998}
999
deadbeefe1f9d832016-01-14 15:35:42 -08001000rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1001 MediaStreamTrackInterface* track,
1002 std::vector<MediaStreamInterface*> streams) {
1003 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001004 std::vector<std::string> stream_labels;
1005 for (auto* stream : streams) {
1006 if (!stream) {
1007 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1008 return nullptr;
1009 }
1010 stream_labels.push_back(stream->label());
1011 }
Steve Anton2d6c76a2018-01-05 17:10:52 -08001012 auto sender_or_error = AddTrack(track, stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001013 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001014 return nullptr;
1015 }
Steve Antonf9381f02017-12-14 10:23:57 -08001016 return sender_or_error.MoveValue();
1017}
1018
Steve Anton2d6c76a2018-01-05 17:10:52 -08001019RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001020 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1021 const std::vector<std::string>& stream_labels) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001022 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001023 if (!track) {
1024 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1025 }
1026 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1027 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1028 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1029 "Track has invalid kind: " + track->kind());
1030 }
1031 // TODO(bugs.webrtc.org/7932): Support adding a track to multiple streams.
1032 if (stream_labels.size() > 1u) {
1033 LOG_AND_RETURN_ERROR(
1034 RTCErrorType::UNSUPPORTED_OPERATION,
1035 "AddTrack with more than one stream is not currently supported.");
1036 }
1037 if (IsClosed()) {
1038 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1039 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001040 }
Steve Anton4171afb2017-11-20 10:20:22 -08001041 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001042 LOG_AND_RETURN_ERROR(
1043 RTCErrorType::INVALID_PARAMETER,
1044 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001045 }
Steve Antonf9381f02017-12-14 10:23:57 -08001046 // TODO(bugs.webrtc.org/7933): MediaSession expects the sender to have exactly
1047 // one stream. AddTrackInternal will return an error if there is more than one
1048 // stream, but if the caller specifies none then we need to generate a random
1049 // stream label.
1050 std::vector<std::string> adjusted_stream_labels = stream_labels;
1051 if (stream_labels.empty()) {
1052 adjusted_stream_labels.push_back(rtc::CreateRandomUuid());
1053 }
1054 RTC_DCHECK_EQ(1, adjusted_stream_labels.size());
1055 auto sender_or_error =
1056 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, adjusted_stream_labels)
1057 : AddTrackPlanB(track, adjusted_stream_labels));
1058 if (sender_or_error.ok()) {
1059 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001060 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001061 }
1062 return sender_or_error;
1063}
deadbeefe1f9d832016-01-14 15:35:42 -08001064
Steve Antonf9381f02017-12-14 10:23:57 -08001065RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1066PeerConnection::AddTrackPlanB(
1067 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1068 const std::vector<std::string>& stream_labels) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001069 cricket::MediaType media_type =
1070 (track->kind() == MediaStreamTrackInterface::kAudioKind
1071 ? cricket::MEDIA_TYPE_AUDIO
1072 : cricket::MEDIA_TYPE_VIDEO);
1073 auto new_sender = CreateSender(media_type, track, stream_labels);
deadbeefe1f9d832016-01-14 15:35:42 -08001074 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton02ee47c2018-01-10 16:26:06 -08001075 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001076 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001077 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001078 const RtpSenderInfo* sender_info =
1079 FindSenderInfo(local_audio_sender_infos_,
1080 new_sender->internal()->stream_id(), track->id());
1081 if (sender_info) {
1082 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001083 }
Steve Antonf9381f02017-12-14 10:23:57 -08001084 } else {
1085 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton02ee47c2018-01-10 16:26:06 -08001086 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08001087 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001088 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001089 const RtpSenderInfo* sender_info =
1090 FindSenderInfo(local_video_sender_infos_,
1091 new_sender->internal()->stream_id(), track->id());
1092 if (sender_info) {
1093 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001094 }
deadbeefe1f9d832016-01-14 15:35:42 -08001095 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001096 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001097}
deadbeefe1f9d832016-01-14 15:35:42 -08001098
Steve Antonf9381f02017-12-14 10:23:57 -08001099RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1100PeerConnection::AddTrackUnifiedPlan(
1101 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1102 const std::vector<std::string>& stream_labels) {
1103 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1104 if (transceiver) {
1105 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
1106 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1107 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
1108 transceiver->SetDirection(RtpTransceiverDirection::kSendOnly);
1109 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001110 transceiver->sender()->SetTrack(track);
1111 transceiver->internal()->sender_internal()->set_stream_ids(stream_labels);
Steve Antonf9381f02017-12-14 10:23:57 -08001112 } else {
1113 cricket::MediaType media_type =
1114 (track->kind() == MediaStreamTrackInterface::kAudioKind
1115 ? cricket::MEDIA_TYPE_AUDIO
1116 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton02ee47c2018-01-10 16:26:06 -08001117 auto sender = CreateSender(media_type, track, stream_labels);
1118 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1119 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001120 transceiver->internal()->set_created_by_addtrack(true);
1121 transceiver->SetDirection(RtpTransceiverDirection::kSendRecv);
1122 }
Steve Antonf9381f02017-12-14 10:23:57 -08001123 return transceiver->sender();
1124}
1125
1126rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1127PeerConnection::FindFirstTransceiverForAddedTrack(
1128 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1129 RTC_DCHECK(track);
1130 for (auto transceiver : transceivers_) {
1131 if (!transceiver->sender()->track() &&
1132 cricket::MediaTypeToString(transceiver->internal()->media_type()) ==
1133 track->kind() &&
1134 !transceiver->internal()->has_ever_been_used_to_send()) {
1135 return transceiver;
1136 }
1137 }
1138 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001139}
1140
1141bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1142 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001143 return RemoveTrackInternal(sender).ok();
1144}
1145
1146RTCError PeerConnection::RemoveTrackInternal(
1147 rtc::scoped_refptr<RtpSenderInterface> sender) {
1148 if (!sender) {
1149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1150 }
deadbeefe1f9d832016-01-14 15:35:42 -08001151 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001152 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1153 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001154 }
Steve Antonf9381f02017-12-14 10:23:57 -08001155 if (IsUnifiedPlan()) {
1156 auto transceiver = FindTransceiverBySender(sender);
1157 if (!transceiver || !sender->track()) {
1158 return RTCError::OK();
1159 }
1160 sender->SetTrack(nullptr);
1161 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
1162 transceiver->internal()->SetDirection(RtpTransceiverDirection::kRecvOnly);
1163 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
1164 transceiver->internal()->SetDirection(RtpTransceiverDirection::kInactive);
1165 }
Steve Anton4171afb2017-11-20 10:20:22 -08001166 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001167 bool removed;
1168 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1169 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1170 } else {
1171 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1172 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1173 }
1174 if (!removed) {
1175 LOG_AND_RETURN_ERROR(
1176 RTCErrorType::INVALID_PARAMETER,
1177 "Couldn't find sender " + sender->id() + " to remove.");
1178 }
Steve Anton4171afb2017-11-20 10:20:22 -08001179 }
deadbeefe1f9d832016-01-14 15:35:42 -08001180 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001181 return RTCError::OK();
1182}
1183
1184rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1185PeerConnection::FindTransceiverBySender(
1186 rtc::scoped_refptr<RtpSenderInterface> sender) {
1187 for (auto transceiver : transceivers_) {
1188 if (transceiver->sender() == sender) {
1189 return transceiver;
1190 }
1191 }
1192 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001193}
1194
Steve Anton9158ef62017-11-27 13:01:52 -08001195RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1196PeerConnection::AddTransceiver(
1197 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1198 return AddTransceiver(track, RtpTransceiverInit());
1199}
1200
1201RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1202PeerConnection::AddTransceiver(
1203 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1204 const RtpTransceiverInit& init) {
1205 if (!IsUnifiedPlan()) {
1206 LOG_AND_RETURN_ERROR(
1207 RTCErrorType::INTERNAL_ERROR,
1208 "AddTransceiver only supported when Unified Plan is enabled.");
1209 }
1210 if (!track) {
1211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1212 }
1213 cricket::MediaType media_type;
1214 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1215 media_type = cricket::MEDIA_TYPE_AUDIO;
1216 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1217 media_type = cricket::MEDIA_TYPE_VIDEO;
1218 } else {
1219 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1220 "Track kind is not audio or video");
1221 }
1222 return AddTransceiver(media_type, track, init);
1223}
1224
1225RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1226PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1227 return AddTransceiver(media_type, RtpTransceiverInit());
1228}
1229
1230RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1231PeerConnection::AddTransceiver(cricket::MediaType media_type,
1232 const RtpTransceiverInit& init) {
1233 if (!IsUnifiedPlan()) {
1234 LOG_AND_RETURN_ERROR(
1235 RTCErrorType::INTERNAL_ERROR,
1236 "AddTransceiver only supported when Unified Plan is enabled.");
1237 }
1238 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1239 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1240 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1241 "media type is not audio or video");
1242 }
1243 return AddTransceiver(media_type, nullptr, init);
1244}
1245
1246RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1247PeerConnection::AddTransceiver(
1248 cricket::MediaType media_type,
1249 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1250 const RtpTransceiverInit& init) {
1251 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1252 media_type == cricket::MEDIA_TYPE_VIDEO));
1253 if (track) {
1254 RTC_DCHECK_EQ(media_type,
1255 (track->kind() == MediaStreamTrackInterface::kAudioKind
1256 ? cricket::MEDIA_TYPE_AUDIO
1257 : cricket::MEDIA_TYPE_VIDEO));
1258 }
1259
1260 // TODO(bugs.webrtc.org/7600): Verify init.
1261
Steve Anton02ee47c2018-01-10 16:26:06 -08001262 if (init.stream_labels.size() > 1u) {
1263 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1264 "More than one stream is not yet supported.");
Steve Antonf9381f02017-12-14 10:23:57 -08001265 }
1266
Steve Anton02ee47c2018-01-10 16:26:06 -08001267 std::vector<std::string> stream_labels = {!init.stream_labels.empty()
1268 ? init.stream_labels[0]
1269 : rtc::CreateRandomUuid()};
1270
1271 auto sender = CreateSender(media_type, track, stream_labels);
1272 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1273 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1274 transceiver->internal()->set_direction(init.direction);
1275
Steve Antonf9381f02017-12-14 10:23:57 -08001276 observer_->OnRenegotiationNeeded();
1277
1278 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1279}
1280
Steve Anton02ee47c2018-01-10 16:26:06 -08001281rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1282PeerConnection::CreateSender(
1283 cricket::MediaType media_type,
1284 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1285 const std::vector<std::string>& stream_labels) {
Steve Anton9158ef62017-11-27 13:01:52 -08001286 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001287 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1288 RTC_DCHECK(!track ||
1289 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1290 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1291 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001292 new AudioRtpSender(worker_thread(),
1293 static_cast<AudioTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001294 stream_labels, stats_.get()));
1295 } else {
1296 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1297 RTC_DCHECK(!track ||
1298 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1299 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1300 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001301 new VideoRtpSender(worker_thread(),
1302 static_cast<VideoTrackInterface*>(track.get()),
Steve Anton02ee47c2018-01-10 16:26:06 -08001303 stream_labels));
1304 }
1305 sender->internal()->set_stream_ids(stream_labels);
1306 return sender;
1307}
1308
1309rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1310PeerConnection::CreateReceiver(cricket::MediaType media_type,
1311 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001312 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1313 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001314 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001315 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001316 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001317 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001318 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001319 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001320 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1321 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001322 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001323 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001324 return receiver;
1325}
1326
1327rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1328PeerConnection::CreateAndAddTransceiver(
1329 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1330 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1331 receiver) {
1332 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1333 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001334 transceivers_.push_back(transceiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001335 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001336}
1337
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001338rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001339 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001340 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001341 if (IsClosed()) {
1342 return nullptr;
1343 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001345 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001346 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347 }
Steve Anton4171afb2017-11-20 10:20:22 -08001348 auto track_sender = FindSenderForTrack(track);
1349 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001350 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001351 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001352 }
1353
Steve Anton4171afb2017-11-20 10:20:22 -08001354 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001355}
1356
deadbeeffac06552015-11-25 11:26:01 -08001357rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001358 const std::string& kind,
1359 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001360 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001361 if (IsClosed()) {
1362 return nullptr;
1363 }
Steve Anton4171afb2017-11-20 10:20:22 -08001364
Steve Anton02ee47c2018-01-10 16:26:06 -08001365 std::vector<std::string> stream_labels;
1366 if (!stream_id.empty()) {
1367 stream_labels.push_back(stream_id);
1368 }
1369
Steve Anton4171afb2017-11-20 10:20:22 -08001370 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001371 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001372 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001373 auto* audio_sender = new AudioRtpSender(worker_thread(), nullptr,
1374 stream_labels, stats_.get());
1375 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001376 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001377 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001378 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001379 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001380 auto* video_sender =
1381 new VideoRtpSender(worker_thread(), nullptr, stream_labels);
1382 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001383 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001384 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001385 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001386 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001387 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001388 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001389 }
Steve Anton4171afb2017-11-20 10:20:22 -08001390
deadbeefe1f9d832016-01-14 15:35:42 -08001391 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001392}
1393
deadbeef70ab1a12015-09-28 16:53:55 -07001394std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1395 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001396 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001397 for (auto sender : GetSendersInternal()) {
1398 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001399 }
1400 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001401}
1402
Steve Anton4171afb2017-11-20 10:20:22 -08001403std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1404PeerConnection::GetSendersInternal() const {
1405 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1406 all_senders;
1407 for (auto transceiver : transceivers_) {
1408 auto senders = transceiver->internal()->senders();
1409 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1410 }
1411 return all_senders;
1412}
1413
deadbeef70ab1a12015-09-28 16:53:55 -07001414std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1415PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001416 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001417 for (const auto& receiver : GetReceiversInternal()) {
1418 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001419 }
1420 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001421}
1422
Steve Anton4171afb2017-11-20 10:20:22 -08001423std::vector<
1424 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1425PeerConnection::GetReceiversInternal() const {
1426 std::vector<
1427 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1428 all_receivers;
1429 for (auto transceiver : transceivers_) {
1430 auto receivers = transceiver->internal()->receivers();
1431 all_receivers.insert(all_receivers.end(), receivers.begin(),
1432 receivers.end());
1433 }
1434 return all_receivers;
1435}
1436
Steve Anton9158ef62017-11-27 13:01:52 -08001437std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1438PeerConnection::GetTransceivers() const {
1439 RTC_DCHECK(IsUnifiedPlan());
1440 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1441 for (auto transceiver : transceivers_) {
1442 all_transceivers.push_back(transceiver);
1443 }
1444 return all_transceivers;
1445}
1446
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001447bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001448 MediaStreamTrackInterface* track,
1449 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001450 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001451 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001452 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001453 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454 return false;
1455 }
1456
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001457 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001458 // The StatsCollector is used to tell if a track is valid because it may
1459 // remember tracks that the PeerConnection previously removed.
1460 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001461 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1462 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001463 return false;
1464 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001465 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001466 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467 return true;
1468}
1469
hbos74e1a4f2016-09-15 23:33:01 -07001470void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1471 RTC_DCHECK(stats_collector_);
1472 stats_collector_->GetStatsReport(callback);
1473}
1474
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1476 return signaling_state_;
1477}
1478
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479PeerConnectionInterface::IceConnectionState
1480PeerConnection::ice_connection_state() {
1481 return ice_connection_state_;
1482}
1483
1484PeerConnectionInterface::IceGatheringState
1485PeerConnection::ice_gathering_state() {
1486 return ice_gathering_state_;
1487}
1488
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001489rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001490PeerConnection::CreateDataChannel(
1491 const std::string& label,
1492 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001493 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001494
deadbeefab9b2d12015-10-14 11:33:11 -07001495 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001496
kwibergd1fe2812016-04-27 06:47:29 -07001497 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001498 if (config) {
1499 internal_config.reset(new InternalDataChannelInit(*config));
1500 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001501 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001502 InternalCreateDataChannel(label, internal_config.get()));
1503 if (!channel.get()) {
1504 return nullptr;
1505 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001506
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001507 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1508 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001509 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001510 observer_->OnRenegotiationNeeded();
1511 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001512
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001513 return DataChannelProxy::Create(signaling_thread(), channel.get());
1514}
1515
1516void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1517 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001518 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001519
zhihuang1c378ed2017-08-17 14:10:50 -07001520 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1521 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1522 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1523 // compares the mandatory fields parsed with the mandatory fields added in the
1524 // |constraints| and some downstream applications might create offers with
1525 // mandatory fields which would not be parsed in the helper method. For
1526 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1527 // |constraints| as a mandatory field but it is not parsed.
1528 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001529
zhihuang1c378ed2017-08-17 14:10:50 -07001530 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001531}
1532
1533void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1534 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001535 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001536
nisse7ce109a2017-01-31 00:57:56 -08001537 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001538 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001539 return;
1540 }
deadbeefab9b2d12015-10-14 11:33:11 -07001541
Steve Anton8d3444d2017-10-20 15:30:51 -07001542 if (IsClosed()) {
1543 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001544 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001545 PostCreateSessionDescriptionFailure(observer, error);
1546 return;
1547 }
1548
zhihuang1c378ed2017-08-17 14:10:50 -07001549 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001550 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001551 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001552 PostCreateSessionDescriptionFailure(observer, error);
1553 return;
1554 }
1555
zhihuang1c378ed2017-08-17 14:10:50 -07001556 cricket::MediaSessionOptions session_options;
1557 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001558 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559}
1560
1561void PeerConnection::CreateAnswer(
1562 CreateSessionDescriptionObserver* observer,
1563 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001564 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001565
nisse7ce109a2017-01-31 00:57:56 -08001566 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001567 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001568 return;
1569 }
deadbeefab9b2d12015-10-14 11:33:11 -07001570
zhihuang1c378ed2017-08-17 14:10:50 -07001571 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1572 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1573 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001574 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001575 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001576 PostCreateSessionDescriptionFailure(observer, error);
1577 return;
1578 }
1579
Steve Anton8d3444d2017-10-20 15:30:51 -07001580 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001581}
1582
1583void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1584 const RTCOfferAnswerOptions& options) {
1585 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001586 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001587 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001588 return;
1589 }
1590
Steve Anton8d3444d2017-10-20 15:30:51 -07001591 if (IsClosed()) {
1592 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001593 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001594 PostCreateSessionDescriptionFailure(observer, error);
1595 return;
1596 }
1597
Steve Anton75737c02017-11-06 10:37:17 -08001598 if (remote_description() &&
Steve Antona3a92c22017-12-07 10:27:41 -08001599 remote_description()->GetType() != SdpType::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001600 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001601 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001602 PostCreateSessionDescriptionFailure(observer, error);
1603 return;
1604 }
1605
htaa2a49d92016-03-04 02:51:39 -08001606 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001607 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001608
Steve Antond25da372017-11-06 14:50:29 -08001609 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001610}
1611
1612void PeerConnection::SetLocalDescription(
1613 SetSessionDescriptionObserver* observer,
1614 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001615 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001616
nisse7ce109a2017-01-31 00:57:56 -08001617 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001618 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619 return;
1620 }
Steve Anton8a006912017-12-04 15:25:56 -08001621
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001622 if (!desc) {
1623 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1624 return;
1625 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001626
Steve Antona3a92c22017-12-07 10:27:41 -08001627 SdpType type = desc->GetType();
Steve Anton8d3444d2017-10-20 15:30:51 -07001628
Steve Anton8a006912017-12-04 15:25:56 -08001629 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1630 // |desc| may be destroyed at this point.
1631
1632 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001633 std::ostringstream oss;
1634 oss << "Failed to set local " << SdpTypeToString(type)
1635 << " sdp: " << error.message();
1636 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001637 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1638 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001639 return;
1640 }
Steve Anton8a006912017-12-04 15:25:56 -08001641 RTC_DCHECK(local_description());
1642
1643 PostSetSessionDescriptionSuccess(observer);
1644
1645 // According to JSEP, after setLocalDescription, changing the candidate pool
1646 // size is not allowed, and changing the set of ICE servers will not result
1647 // in new candidates being gathered.
1648 port_allocator_->FreezeCandidatePool();
1649
1650 // MaybeStartGathering needs to be called after posting
1651 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1652 // before signaling that SetLocalDescription completed.
1653 transport_controller_->MaybeStartGathering();
1654
Steve Antona3a92c22017-12-07 10:27:41 -08001655 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001656 // TODO(deadbeef): We already had to hop to the network thread for
1657 // MaybeStartGathering...
1658 network_thread()->Invoke<void>(
1659 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1660 port_allocator_.get()));
1661 }
1662}
1663
1664RTCError PeerConnection::ApplyLocalDescription(
1665 std::unique_ptr<SessionDescriptionInterface> desc) {
1666 RTC_DCHECK_RUN_ON(signaling_thread());
1667 RTC_DCHECK(desc);
1668
1669 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1670 if (!error.ok()) {
1671 return error;
1672 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001673
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001674 // Update stats here so that we have the most recent stats for tracks and
1675 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001676 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001677
1678 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001679 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001680 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001681 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001682 if (*initial_offerer_) {
1683 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1684 } else {
1685 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1686 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687 }
Steve Anton8a006912017-12-04 15:25:56 -08001688
Steve Antondcc3c022017-12-22 16:02:54 -08001689 // Take a reference to the old local description since it's used below to
1690 // compare against the new local description. When setting the new local
1691 // description, grab ownership of the replaced session description in case it
1692 // is the same as |old_local_description|, to keep it alive for the duration
1693 // of the method.
1694 const SessionDescriptionInterface* old_local_description =
1695 local_description();
1696 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Steve Anton3828c062017-12-06 10:34:51 -08001697 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001698 replaced_local_description = pending_local_description_
1699 ? std::move(pending_local_description_)
1700 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001701 current_local_description_ = std::move(desc);
1702 pending_local_description_ = nullptr;
1703 current_remote_description_ = std::move(pending_remote_description_);
1704 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001705 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001706 pending_local_description_ = std::move(desc);
1707 }
1708 // The session description to apply now must be accessed by
1709 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001710 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001711
Steve Antondcc3c022017-12-22 16:02:54 -08001712 if (IsUnifiedPlan()) {
1713 RTCError error = UpdateTransceiversAndDataChannels(
1714 cricket::CS_LOCAL, old_local_description, *local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001715 if (!error.ok()) {
1716 return error;
1717 }
Steve Antondcc3c022017-12-22 16:02:54 -08001718 for (auto transceiver : transceivers_) {
1719 const ContentInfo* content =
1720 FindMediaSectionForTransceiver(transceiver, local_description());
1721 if (!content) {
1722 continue;
1723 }
1724 const MediaContentDescription* media_desc = content->media_description();
1725 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
1726 transceiver->internal()->set_current_direction(media_desc->direction());
1727 }
1728 if (content->rejected && !transceiver->stopped()) {
1729 transceiver->Stop();
1730 }
1731 }
1732 } else {
1733 // Transport and Media channels will be created only when offer is set.
1734 if (type == SdpType::kOffer) {
1735 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1736 // description is applied. Restore back to old description.
1737 RTCError error = CreateChannels(*local_description()->description());
1738 if (!error.ok()) {
1739 return error;
1740 }
1741 }
Steve Anton8a006912017-12-04 15:25:56 -08001742
Steve Antondcc3c022017-12-22 16:02:54 -08001743 // Remove unused channels if MediaContentDescription is rejected.
1744 RemoveUnusedChannels(local_description()->description());
1745 }
Steve Anton8a006912017-12-04 15:25:56 -08001746
Steve Anton3828c062017-12-06 10:34:51 -08001747 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001748 if (!error.ok()) {
1749 return error;
1750 }
Steve Antondcc3c022017-12-22 16:02:54 -08001751
Steve Anton8a006912017-12-04 15:25:56 -08001752 if (remote_description()) {
1753 // Now that we have a local description, we can push down remote candidates.
1754 UseCandidatesInSessionDescription(remote_description());
1755 }
1756
1757 pending_ice_restarts_.clear();
1758 if (session_error() != SessionError::kNone) {
1759 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1760 }
1761
deadbeefab9b2d12015-10-14 11:33:11 -07001762 // If setting the description decided our SSL role, allocate any necessary
1763 // SCTP sids.
1764 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001765 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001766 AllocateSctpSids(role);
1767 }
1768
Steve Antond3679212018-01-17 17:41:02 -08001769 if (IsUnifiedPlan()) {
1770 for (auto transceiver : transceivers_) {
1771 const ContentInfo* content =
1772 FindMediaSectionForTransceiver(transceiver, local_description());
1773 if (!content) {
1774 continue;
1775 }
1776 if (content->rejected && !transceiver->stopped()) {
1777 transceiver->Stop();
1778 }
1779 if (!content->rejected) {
1780 const auto& stream = content->media_description()->streams()[0];
1781 transceiver->internal()->sender_internal()->set_stream_ids(
1782 {stream.sync_label});
1783 transceiver->internal()->sender_internal()->SetSsrc(
1784 stream.first_ssrc());
1785 }
1786 }
1787 } else {
1788 // Plan B semantics.
1789
Steve Antondcc3c022017-12-22 16:02:54 -08001790 // Update state and SSRC of local MediaStreams and DataChannels based on the
1791 // local session description.
1792 const cricket::ContentInfo* audio_content =
1793 GetFirstAudioContent(local_description()->description());
1794 if (audio_content) {
1795 if (audio_content->rejected) {
1796 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
1797 } else {
1798 const cricket::AudioContentDescription* audio_desc =
1799 audio_content->media_description()->as_audio();
1800 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
1801 }
deadbeeffaac4972015-11-12 15:33:07 -08001802 }
deadbeefab9b2d12015-10-14 11:33:11 -07001803
Steve Antondcc3c022017-12-22 16:02:54 -08001804 const cricket::ContentInfo* video_content =
1805 GetFirstVideoContent(local_description()->description());
1806 if (video_content) {
1807 if (video_content->rejected) {
1808 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
1809 } else {
1810 const cricket::VideoContentDescription* video_desc =
1811 video_content->media_description()->as_video();
1812 UpdateLocalSenders(video_desc->streams(), video_desc->type());
1813 }
deadbeeffaac4972015-11-12 15:33:07 -08001814 }
deadbeefab9b2d12015-10-14 11:33:11 -07001815 }
1816
1817 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001818 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001819 if (data_content) {
1820 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08001821 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07001822 if (rtc::starts_with(data_desc->protocol().data(),
1823 cricket::kMediaProtocolRtpPrefix)) {
1824 UpdateLocalRtpDataChannels(data_desc->streams());
1825 }
1826 }
1827
Steve Anton8a006912017-12-04 15:25:56 -08001828 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001829}
1830
1831void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001832 SetSessionDescriptionObserver* observer,
1833 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001834 SetRemoteDescription(
1835 std::unique_ptr<SessionDescriptionInterface>(desc),
1836 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1837 new SetRemoteDescriptionObserverAdapter(this, observer)));
1838}
1839
1840void PeerConnection::SetRemoteDescription(
1841 std::unique_ptr<SessionDescriptionInterface> desc,
1842 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001843 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001844
nisse7ce109a2017-01-31 00:57:56 -08001845 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001846 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847 return;
1848 }
Steve Anton8a006912017-12-04 15:25:56 -08001849
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001851 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001852 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853 return;
1854 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001855
Steve Antona3a92c22017-12-07 10:27:41 -08001856 const SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001857
1858 RTCError error = ApplyRemoteDescription(std::move(desc));
1859 // |desc| may be destroyed at this point.
1860
1861 if (!error.ok()) {
Steve Antona3a92c22017-12-07 10:27:41 -08001862 std::ostringstream oss;
1863 oss << "Failed to set remote " << SdpTypeToString(type)
1864 << " sdp: " << error.message();
1865 std::string error_message = oss.str();
Steve Anton8a006912017-12-04 15:25:56 -08001866 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001867 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001868 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001869 return;
1870 }
1871
Steve Antona3a92c22017-12-07 10:27:41 -08001872 if (remote_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001873 // TODO(deadbeef): We already had to hop to the network thread for
1874 // MaybeStartGathering...
1875 network_thread()->Invoke<void>(
1876 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1877 port_allocator_.get()));
1878 }
1879
1880 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1881}
1882
1883RTCError PeerConnection::ApplyRemoteDescription(
1884 std::unique_ptr<SessionDescriptionInterface> desc) {
1885 RTC_DCHECK_RUN_ON(signaling_thread());
1886 RTC_DCHECK(desc);
1887
1888 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1889 if (!error.ok()) {
1890 return error;
1891 }
1892
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 // Update stats here so that we have the most recent stats for tracks and
1894 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001895 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001896
Steve Antondcc3c022017-12-22 16:02:54 -08001897 // Take a reference to the old remote description since it's used below to
1898 // compare against the new remote description. When setting the new remote
1899 // description, grab ownership of the replaced session description in case it
1900 // is the same as |old_remote_description|, to keep it alive for the duration
1901 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08001902 const SessionDescriptionInterface* old_remote_description =
1903 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08001904 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001905 SdpType type = desc->GetType();
1906 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001907 replaced_remote_description = pending_remote_description_
1908 ? std::move(pending_remote_description_)
1909 : std::move(current_remote_description_);
1910 current_remote_description_ = std::move(desc);
1911 pending_remote_description_ = nullptr;
1912 current_local_description_ = std::move(pending_local_description_);
1913 } else {
1914 replaced_remote_description = std::move(pending_remote_description_);
1915 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916 }
Steve Anton8a006912017-12-04 15:25:56 -08001917 // The session description to apply now must be accessed by
1918 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001919 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001920
Steve Anton8a006912017-12-04 15:25:56 -08001921 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08001922 if (IsUnifiedPlan()) {
1923 RTCError error = UpdateTransceiversAndDataChannels(
1924 cricket::CS_REMOTE, old_remote_description, *remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001925 if (!error.ok()) {
1926 return error;
1927 }
Steve Antondcc3c022017-12-22 16:02:54 -08001928 } else {
1929 if (type == SdpType::kOffer) {
1930 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
1931 // description is applied. Restore back to old description.
1932 RTCError error = CreateChannels(*remote_description()->description());
1933 if (!error.ok()) {
1934 return error;
1935 }
1936 }
Steve Anton8a006912017-12-04 15:25:56 -08001937
Steve Antondcc3c022017-12-22 16:02:54 -08001938 // Remove unused channels if MediaContentDescription is rejected.
1939 RemoveUnusedChannels(remote_description()->description());
1940 }
Steve Anton8a006912017-12-04 15:25:56 -08001941
1942 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1943 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001944 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001945 if (!error.ok()) {
1946 return error;
1947 }
1948
1949 if (local_description() &&
1950 !UseCandidatesInSessionDescription(remote_description())) {
1951 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1952 }
1953
1954 if (old_remote_description) {
1955 for (const cricket::ContentInfo& content :
1956 old_remote_description->description()->contents()) {
1957 // Check if this new SessionDescription contains new ICE ufrag and
1958 // password that indicates the remote peer requests an ICE restart.
1959 // TODO(deadbeef): When we start storing both the current and pending
1960 // remote description, this should reset pending_ice_restarts and compare
1961 // against the current description.
1962 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1963 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001964 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001965 pending_ice_restarts_.insert(content.name);
1966 }
1967 } else {
1968 // We retain all received candidates only if ICE is not restarted.
1969 // When ICE is restarted, all previous candidates belong to an old
1970 // generation and should not be kept.
1971 // TODO(deadbeef): This goes against the W3C spec which says the remote
1972 // description should only contain candidates from the last set remote
1973 // description plus any candidates added since then. We should remove
1974 // this once we're sure it won't break anything.
1975 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1976 old_remote_description, content.name, mutable_remote_description());
1977 }
1978 }
1979 }
1980
1981 if (session_error() != SessionError::kNone) {
1982 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1983 }
1984
1985 // Set the the ICE connection state to connecting since the connection may
1986 // become writable with peer reflexive candidates before any remote candidate
1987 // is signaled.
1988 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1989 // is to have a new signal the indicates a change in checking state from the
1990 // transport and expose a new checking() member from transport that can be
1991 // read to determine the current checking state. The existing SignalConnecting
1992 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08001993 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08001994 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1995 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1996 }
1997
deadbeefab9b2d12015-10-14 11:33:11 -07001998 // If setting the description decided our SSL role, allocate any necessary
1999 // SCTP sids.
2000 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002001 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002002 AllocateSctpSids(role);
2003 }
2004
Steve Antondcc3c022017-12-22 16:02:54 -08002005 if (IsUnifiedPlan()) {
Steve Antonef65ef12018-01-10 17:15:20 -08002006 std::vector<TrackEvent> track_events;
Steve Antondcc3c022017-12-22 16:02:54 -08002007 for (auto transceiver : transceivers_) {
2008 const ContentInfo* content =
2009 FindMediaSectionForTransceiver(transceiver, remote_description());
2010 if (!content) {
2011 continue;
2012 }
2013 const MediaContentDescription* media_desc = content->media_description();
2014 RtpTransceiverDirection local_direction =
2015 RtpTransceiverDirectionReversed(media_desc->direction());
2016 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2017 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2018 // transceiver's current direction is neither sendrecv nor recvonly,
2019 // process the addition of a remote track for the media description.
2020 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2021 (!transceiver->current_direction() ||
2022 !RtpTransceiverDirectionHasRecv(
2023 *transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002024 const std::string& sync_label = media_desc->streams()[0].sync_label;
2025 rtc::scoped_refptr<MediaStreamInterface> stream =
2026 remote_streams_->find(sync_label);
2027 if (!stream) {
2028 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2029 MediaStream::Create(sync_label));
2030 remote_streams_->AddStream(stream);
2031 }
2032 transceiver->internal()->receiver_internal()->SetStreams({stream});
2033 TrackEvent track_event;
2034 track_event.receiver = transceiver->receiver();
2035 track_event.streams = transceiver->receiver()->streams();
2036 track_events.push_back(std::move(track_event));
Steve Antondcc3c022017-12-22 16:02:54 -08002037 }
2038 // If direction is sendonly or inactive, and transceiver's current
2039 // direction is neither sendonly nor inactive, process the removal of a
2040 // remote track for the media description.
2041 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002042 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002043 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Antonef65ef12018-01-10 17:15:20 -08002044 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002045 }
2046 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2047 transceiver->internal()->set_current_direction(local_direction);
2048 }
2049 if (content->rejected && !transceiver->stopped()) {
2050 transceiver->Stop();
2051 }
Steve Antond3679212018-01-17 17:41:02 -08002052 if (!content->rejected) {
2053 const auto& stream = content->media_description()->streams()[0];
2054 transceiver->internal()->receiver_internal()->SetupMediaChannel(
2055 stream.first_ssrc());
2056 }
Steve Antondcc3c022017-12-22 16:02:54 -08002057 }
Steve Antonef65ef12018-01-10 17:15:20 -08002058 for (auto event : track_events) {
2059 observer_->OnAddTrack(event.receiver, event.streams);
2060 }
Steve Antondcc3c022017-12-22 16:02:54 -08002061 }
2062
Henrik Boströmfdb92012017-11-09 19:55:44 +01002063 const cricket::ContentInfo* audio_content =
2064 GetFirstAudioContent(remote_description()->description());
2065 const cricket::ContentInfo* video_content =
2066 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002067 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002068 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002069 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002070 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002071 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002072 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002073
2074 // Check if the descriptions include streams, just in case the peer supports
2075 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002076 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002077 (audio_desc && !audio_desc->streams().empty()) ||
2078 (video_desc && !video_desc->streams().empty())) {
2079 remote_peer_supports_msid_ = true;
2080 }
deadbeefab9b2d12015-10-14 11:33:11 -07002081
2082 // We wait to signal new streams until we finish processing the description,
2083 // since only at that point will new streams have all their tracks.
2084 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2085
Steve Antondcc3c022017-12-22 16:02:54 -08002086 if (!IsUnifiedPlan()) {
2087 // TODO(steveanton): When removing RTP senders/receivers in response to a
2088 // rejected media section, there is some cleanup logic that expects the
2089 // voice/ video channel to still be set. But in this method the voice/video
2090 // channel would have been destroyed by the SetRemoteDescription caller
2091 // above so the cleanup that relies on them fails to run. The RemoveSenders
2092 // calls should be moved to right before the DestroyChannel calls to fix
2093 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002094
Steve Antondcc3c022017-12-22 16:02:54 -08002095 // Find all audio rtp streams and create corresponding remote AudioTracks
2096 // and MediaStreams.
2097 if (audio_content) {
2098 if (audio_content->rejected) {
2099 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2100 } else {
2101 bool default_audio_track_needed =
2102 !remote_peer_supports_msid_ &&
2103 RtpTransceiverDirectionHasSend(audio_desc->direction());
2104 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2105 default_audio_track_needed, audio_desc->type(),
2106 new_streams);
2107 }
deadbeeffaac4972015-11-12 15:33:07 -08002108 }
deadbeefab9b2d12015-10-14 11:33:11 -07002109
Steve Antondcc3c022017-12-22 16:02:54 -08002110 // Find all video rtp streams and create corresponding remote VideoTracks
2111 // and MediaStreams.
2112 if (video_content) {
2113 if (video_content->rejected) {
2114 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2115 } else {
2116 bool default_video_track_needed =
2117 !remote_peer_supports_msid_ &&
2118 RtpTransceiverDirectionHasSend(video_desc->direction());
2119 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2120 default_video_track_needed, video_desc->type(),
2121 new_streams);
2122 }
deadbeeffaac4972015-11-12 15:33:07 -08002123 }
deadbeefab9b2d12015-10-14 11:33:11 -07002124
Steve Antondcc3c022017-12-22 16:02:54 -08002125 // Update the DataChannels with the information from the remote peer.
2126 if (data_desc) {
2127 if (rtc::starts_with(data_desc->protocol().data(),
2128 cricket::kMediaProtocolRtpPrefix)) {
2129 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2130 }
deadbeefab9b2d12015-10-14 11:33:11 -07002131 }
deadbeefab9b2d12015-10-14 11:33:11 -07002132
Steve Antondcc3c022017-12-22 16:02:54 -08002133 // Iterate new_streams and notify the observer about new MediaStreams.
2134 for (size_t i = 0; i < new_streams->count(); ++i) {
2135 MediaStreamInterface* new_stream = new_streams->at(i);
2136 stats_->AddStream(new_stream);
2137 observer_->OnAddStream(
2138 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2139 }
deadbeefab9b2d12015-10-14 11:33:11 -07002140
Steve Antondcc3c022017-12-22 16:02:54 -08002141 UpdateEndedRemoteMediaStreams();
2142 }
deadbeefab9b2d12015-10-14 11:33:11 -07002143
Steve Anton8a006912017-12-04 15:25:56 -08002144 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002145}
2146
Steve Antondcc3c022017-12-22 16:02:54 -08002147RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2148 cricket::ContentSource source,
2149 const SessionDescriptionInterface* old_session,
2150 const SessionDescriptionInterface& new_session) {
2151 RTC_DCHECK(IsUnifiedPlan());
2152
Steve Anton7464fca2018-01-19 11:10:37 -08002153 const cricket::ContentGroup* bundle_group = nullptr;
2154 if (new_session.GetType() == SdpType::kOffer) {
2155 auto bundle_group_or_error =
2156 GetEarlyBundleGroup(*new_session.description());
2157 if (!bundle_group_or_error.ok()) {
2158 return bundle_group_or_error.MoveError();
2159 }
2160 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002161 }
Steve Antondcc3c022017-12-22 16:02:54 -08002162
2163 const ContentInfos& old_contents =
2164 (old_session ? old_session->description()->contents() : ContentInfos());
2165 const ContentInfos& new_contents = new_session.description()->contents();
2166
2167 for (size_t i = 0; i < new_contents.size(); ++i) {
2168 const cricket::ContentInfo& new_content = new_contents[i];
2169 const cricket::ContentInfo* old_content =
2170 (i < old_contents.size() ? &old_contents[i] : nullptr);
2171 cricket::MediaType media_type = new_content.media_description()->type();
2172 seen_mids_.insert(new_content.name);
2173 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2174 media_type == cricket::MEDIA_TYPE_VIDEO) {
2175 auto transceiver_or_error =
2176 AssociateTransceiver(source, i, new_content, old_content);
2177 if (!transceiver_or_error.ok()) {
2178 return transceiver_or_error.MoveError();
2179 }
2180 auto transceiver = transceiver_or_error.MoveValue();
2181 if (source == cricket::CS_LOCAL && transceiver->stopped()) {
2182 continue;
2183 }
2184 RTCError error =
2185 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2186 if (!error.ok()) {
2187 return error;
2188 }
2189 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002190 if (GetDataMid() && new_content.name != *GetDataMid()) {
2191 // Ignore all but the first data section.
2192 continue;
2193 }
2194 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2195 if (!error.ok()) {
2196 return error;
2197 }
Steve Antondcc3c022017-12-22 16:02:54 -08002198 } else {
2199 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2200 "Unknown section type.");
2201 }
2202 }
2203
2204 return RTCError::OK();
2205}
2206
2207RTCError PeerConnection::UpdateTransceiverChannel(
2208 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2209 transceiver,
2210 const cricket::ContentInfo& content,
2211 const cricket::ContentGroup* bundle_group) {
2212 RTC_DCHECK(IsUnifiedPlan());
2213 RTC_DCHECK(transceiver);
2214 cricket::BaseChannel* channel = transceiver->internal()->channel();
2215 if (content.rejected) {
2216 if (channel) {
2217 transceiver->internal()->SetChannel(nullptr);
2218 DestroyBaseChannel(channel);
2219 }
2220 } else {
2221 if (!channel) {
2222 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2223 channel = CreateVoiceChannel(
2224 content.name,
2225 GetTransportNameForMediaSection(content.name, bundle_group));
2226 } else {
2227 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO,
2228 transceiver->internal()->media_type());
2229 channel = CreateVideoChannel(
2230 content.name,
2231 GetTransportNameForMediaSection(content.name, bundle_group));
2232 }
2233 if (!channel) {
2234 LOG_AND_RETURN_ERROR(
2235 RTCErrorType::INTERNAL_ERROR,
2236 "Failed to create channel for mid=" + content.name);
2237 }
2238 transceiver->internal()->SetChannel(channel);
2239 }
2240 }
2241 return RTCError::OK();
2242}
2243
Steve Antonfa2260d2017-12-28 16:38:23 -08002244RTCError PeerConnection::UpdateDataChannel(
2245 cricket::ContentSource source,
2246 const cricket::ContentInfo& content,
2247 const cricket::ContentGroup* bundle_group) {
2248 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002249 // If data channels are disabled, ignore this media section. CreateAnswer
2250 // will take care of rejecting it.
2251 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002252 }
2253 if (content.rejected) {
2254 DestroyDataChannel();
2255 } else {
2256 if (!rtp_data_channel_ && !sctp_transport_) {
2257 if (!CreateDataChannel(content.name, GetTransportNameForMediaSection(
2258 content.name, bundle_group))) {
2259 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2260 "Failed to create data channel.");
2261 }
2262 }
2263 if (source == cricket::CS_REMOTE) {
2264 const MediaContentDescription* data_desc = content.media_description();
2265 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2266 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2267 }
2268 }
2269 }
2270 return RTCError::OK();
2271}
2272
Steve Antondcc3c022017-12-22 16:02:54 -08002273RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2274PeerConnection::AssociateTransceiver(cricket::ContentSource source,
2275 size_t mline_index,
2276 const ContentInfo& content,
2277 const ContentInfo* old_content) {
2278 RTC_DCHECK(IsUnifiedPlan());
2279 // If the m= section is being recycled (rejected in previous remote
2280 // description, not rejected in current description), dissociate the currently
2281 // associated RtpTransceiver by setting its mid property to null, and discard
2282 // the mapping between the transceiver and its m= section index.
2283 if (old_content && old_content->rejected && !content.rejected) {
2284 auto old_transceiver = GetAssociatedTransceiver(old_content->name);
2285 if (old_transceiver) {
2286 old_transceiver->internal()->set_mid(rtc::nullopt);
2287 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2288 }
2289 }
2290 const MediaContentDescription* media_desc = content.media_description();
2291 auto transceiver = GetAssociatedTransceiver(content.name);
2292 if (source == cricket::CS_LOCAL) {
2293 // Find the RtpTransceiver that corresponds to this m= section, using the
2294 // mapping between transceivers and m= section indices established when
2295 // creating the offer.
2296 if (!transceiver) {
2297 transceiver = GetTransceiverByMLineIndex(mline_index);
2298 }
2299 if (!transceiver) {
2300 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2301 "Unknown transceiver");
2302 }
2303 } else {
2304 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2305 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2306 // of the same type...
2307 if (!transceiver &&
2308 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2309 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2310 }
2311 // If no RtpTransceiver was found in the previous step, create one with a
2312 // recvonly direction.
2313 if (!transceiver) {
Steve Anton02ee47c2018-01-10 16:26:06 -08002314 auto sender =
2315 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
2316 auto receiver =
2317 CreateReceiver(media_desc->type(), media_desc->streams()[0].id);
2318 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002319 transceiver->internal()->set_direction(
2320 RtpTransceiverDirection::kRecvOnly);
2321 }
2322 }
2323 RTC_DCHECK(transceiver);
2324 if (transceiver->internal()->media_type() != media_desc->type()) {
2325 LOG_AND_RETURN_ERROR(
2326 RTCErrorType::INVALID_PARAMETER,
2327 "Transceiver type does not match media description type.");
2328 }
2329 // Associate the found or created RtpTransceiver with the m= section by
2330 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2331 // section, and establish a mapping between the transceiver and the index of
2332 // the m= section.
2333 transceiver->internal()->set_mid(content.name);
2334 transceiver->internal()->set_mline_index(mline_index);
2335 return std::move(transceiver);
2336}
2337
2338rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2339PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2340 RTC_DCHECK(IsUnifiedPlan());
2341 for (auto transceiver : transceivers_) {
2342 if (transceiver->mid() == mid) {
2343 return transceiver;
2344 }
2345 }
2346 return nullptr;
2347}
2348
2349rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2350PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2351 RTC_DCHECK(IsUnifiedPlan());
2352 for (auto transceiver : transceivers_) {
2353 if (transceiver->internal()->mline_index() == mline_index) {
2354 return transceiver;
2355 }
2356 }
2357 return nullptr;
2358}
2359
2360rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2361PeerConnection::FindAvailableTransceiverToReceive(
2362 cricket::MediaType media_type) const {
2363 RTC_DCHECK(IsUnifiedPlan());
2364 // From JSEP section 5.10 (Applying a Remote Description):
2365 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2366 // the same type that were added to the PeerConnection by addTrack and are not
2367 // associated with any m= section and are not stopped, find the first such
2368 // RtpTransceiver.
2369 for (auto transceiver : transceivers_) {
2370 if (transceiver->internal()->media_type() == media_type &&
2371 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2372 !transceiver->stopped()) {
2373 return transceiver;
2374 }
2375 }
2376 return nullptr;
2377}
2378
Steve Antoned10bd92017-12-05 10:52:59 -08002379const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2380 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2381 transceiver,
2382 const SessionDescriptionInterface* sdesc) const {
2383 RTC_DCHECK(transceiver);
2384 RTC_DCHECK(sdesc);
2385 if (IsUnifiedPlan()) {
2386 if (!transceiver->internal()->mid()) {
2387 // This transceiver is not associated with a media section yet.
2388 return nullptr;
2389 }
2390 return sdesc->description()->GetContentByName(
2391 *transceiver->internal()->mid());
2392 } else {
2393 // Plan B only allows at most one audio and one video section, so use the
2394 // first media section of that type.
2395 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
2396 transceiver->internal()->media_type());
2397 }
2398}
2399
deadbeef46c73892016-11-16 19:42:04 -08002400PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2401 return configuration_;
2402}
2403
deadbeef293e9262017-01-11 12:28:30 -08002404bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2405 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002406 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002407
Steve Anton75737c02017-11-06 10:37:17 -08002408 if (local_description() && configuration.ice_candidate_pool_size !=
2409 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002410 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2411 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002412 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002413 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002414
deadbeef293e9262017-01-11 12:28:30 -08002415 // The simplest (and most future-compatible) way to tell if the config was
2416 // modified in an invalid way is to copy each property we do support
2417 // modifying, then use operator==. There are far more properties we don't
2418 // support modifying than those we do, and more could be added.
2419 RTCConfiguration modified_config = configuration_;
2420 modified_config.servers = configuration.servers;
2421 modified_config.type = configuration.type;
2422 modified_config.ice_candidate_pool_size =
2423 configuration.ice_candidate_pool_size;
2424 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002425 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002426 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08002427 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002428 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002429 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2430 }
2431
Steve Anton038834f2017-07-14 15:59:59 -07002432 // Validate the modified configuration.
2433 RTCError validate_error = ValidateConfiguration(modified_config);
2434 if (!validate_error.ok()) {
2435 return SafeSetError(std::move(validate_error), error);
2436 }
2437
deadbeef293e9262017-01-11 12:28:30 -08002438 // Note that this isn't possible through chromium, since it's an unsigned
2439 // short in WebIDL.
2440 if (configuration.ice_candidate_pool_size < 0 ||
2441 configuration.ice_candidate_pool_size > UINT16_MAX) {
2442 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2443 }
2444
2445 // Parse ICE servers before hopping to network thread.
2446 cricket::ServerAddresses stun_servers;
2447 std::vector<cricket::RelayServerConfig> turn_servers;
2448 RTCErrorType parse_error =
2449 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2450 if (parse_error != RTCErrorType::NONE) {
2451 return SafeSetError(parse_error, error);
2452 }
2453
2454 // In theory this shouldn't fail.
2455 if (!network_thread()->Invoke<bool>(
2456 RTC_FROM_HERE,
2457 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2458 stun_servers, turn_servers, modified_config.type,
2459 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002460 modified_config.prune_turn_ports,
2461 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002462 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002463 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2464 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002465
deadbeefd1a38b52016-12-10 13:15:33 -08002466 // As described in JSEP, calling setConfiguration with new ICE servers or
2467 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2468 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002469 if (modified_config.servers != configuration_.servers ||
2470 modified_config.type != configuration_.type ||
2471 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002472 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002473 }
skvladd1f5fda2017-02-03 16:54:05 -08002474
2475 if (modified_config.ice_check_min_interval !=
2476 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08002477 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002478 }
2479
deadbeef293e9262017-01-11 12:28:30 -08002480 configuration_ = modified_config;
2481 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002482}
2483
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002484bool PeerConnection::AddIceCandidate(
2485 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002486 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002487 if (IsClosed()) {
2488 return false;
2489 }
Steve Antond25da372017-11-06 14:50:29 -08002490
2491 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002492 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
2493 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002494 return false;
2495 }
2496
2497 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002498 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002499 return false;
2500 }
2501
2502 bool valid = false;
2503 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2504 if (!valid) {
2505 return false;
2506 }
2507
2508 // Add this candidate to the remote session description.
2509 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002510 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002511 return false;
2512 }
2513
2514 if (ready) {
2515 return UseCandidate(ice_candidate);
2516 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002517 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002518 return true;
2519 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002520}
2521
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002522bool PeerConnection::RemoveIceCandidates(
2523 const std::vector<cricket::Candidate>& candidates) {
2524 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002525 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002526 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2527 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002528 return false;
2529 }
2530
2531 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002532 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002533 return false;
2534 }
2535
2536 size_t number_removed =
2537 mutable_remote_description()->RemoveCandidates(candidates);
2538 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002539 RTC_LOG(LS_ERROR)
2540 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2541 << "Requested " << candidates.size() << " but only " << number_removed
2542 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002543 }
2544
2545 // Remove the candidates from the transport controller.
2546 std::string error;
2547 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2548 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002549 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002550 }
2551 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002552}
2553
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002554void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002555 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002556 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002557
Steve Anton75737c02017-11-06 10:37:17 -08002558 if (transport_controller()) {
2559 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002560 }
2561
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002562 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002563 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002564 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002565 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002566 uma_observer_->IncrementEnumCounter(
2567 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2568 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002569 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002570 uma_observer_->IncrementEnumCounter(
2571 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2572 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002573 }
2574 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002575}
2576
zstein4b979802017-06-02 14:37:37 -07002577RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002578 if (!worker_thread()->IsCurrent()) {
2579 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002580 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2581 }
2582
2583 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2584 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2585 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2586 if (has_min && *bitrate.min_bitrate_bps < 0) {
2587 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2588 "min_bitrate_bps <= 0");
2589 }
2590 if (has_current) {
2591 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2592 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2593 "current_bitrate_bps < min_bitrate_bps");
2594 } else if (*bitrate.current_bitrate_bps < 0) {
2595 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2596 "curent_bitrate_bps < 0");
2597 }
2598 }
2599 if (has_max) {
2600 if (has_current &&
2601 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2602 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2603 "max_bitrate_bps < current_bitrate_bps");
2604 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2605 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2606 "max_bitrate_bps < min_bitrate_bps");
2607 } else if (*bitrate.max_bitrate_bps < 0) {
2608 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2609 "max_bitrate_bps < 0");
2610 }
2611 }
2612
2613 Call::Config::BitrateConfigMask mask;
2614 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2615 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2616 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2617
2618 RTC_DCHECK(call_.get());
2619 call_->SetBitrateConfigMask(mask);
2620
2621 return RTCError::OK();
2622}
2623
Alex Narest78609d52017-10-20 10:37:47 +02002624void PeerConnection::SetBitrateAllocationStrategy(
2625 std::unique_ptr<rtc::BitrateAllocationStrategy>
2626 bitrate_allocation_strategy) {
2627 rtc::Thread* worker_thread = factory_->worker_thread();
2628 if (!worker_thread->IsCurrent()) {
2629 rtc::BitrateAllocationStrategy* strategy_raw =
2630 bitrate_allocation_strategy.release();
2631 auto functor = [this, strategy_raw]() {
2632 call_->SetBitrateAllocationStrategy(
2633 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2634 };
2635 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2636 return;
2637 }
2638 RTC_DCHECK(call_.get());
2639 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2640}
2641
henrika5f6bf242017-11-01 11:06:56 +01002642void PeerConnection::SetAudioPlayout(bool playout) {
2643 if (!worker_thread()->IsCurrent()) {
2644 worker_thread()->Invoke<void>(
2645 RTC_FROM_HERE,
2646 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2647 return;
2648 }
2649 auto audio_state =
2650 factory_->channel_manager()->media_engine()->GetAudioState();
2651 audio_state->SetPlayout(playout);
2652}
2653
2654void PeerConnection::SetAudioRecording(bool recording) {
2655 if (!worker_thread()->IsCurrent()) {
2656 worker_thread()->Invoke<void>(
2657 RTC_FROM_HERE,
2658 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2659 return;
2660 }
2661 auto audio_state =
2662 factory_->channel_manager()->media_engine()->GetAudioState();
2663 audio_state->SetRecording(recording);
2664}
2665
Steve Anton8c0f7a72017-10-03 10:03:10 -07002666std::unique_ptr<rtc::SSLCertificate>
2667PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002668 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002669 return nullptr;
2670 }
Steve Anton75737c02017-11-06 10:37:17 -08002671 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002672}
2673
ivoc14d5dbe2016-07-04 07:06:55 -07002674bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2675 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002676 // TODO(eladalon): It would be better to not allow negative values into PC.
2677 const size_t max_size = (max_size_bytes < 0)
2678 ? RtcEventLog::kUnlimitedOutput
2679 : rtc::saturated_cast<size_t>(max_size_bytes);
2680 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002681 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2682 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002683}
2684
Bjorn Tereliusde939432017-11-20 17:38:14 +01002685bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2686 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002687 // TODO(eladalon): In C++14, this can be done with a lambda.
2688 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002689 bool operator()() {
2690 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2691 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002692 PeerConnection* const pc;
2693 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002694 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002695 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002696 return worker_thread()->Invoke<bool>(
2697 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002698}
2699
2700void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002701 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002702 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2703}
2704
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002705const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002706 return pending_local_description_ ? pending_local_description_.get()
2707 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002708}
2709
2710const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002711 return pending_remote_description_ ? pending_remote_description_.get()
2712 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002713}
2714
deadbeeffe4a8a42016-12-20 17:56:17 -08002715const SessionDescriptionInterface* PeerConnection::current_local_description()
2716 const {
Steve Anton75737c02017-11-06 10:37:17 -08002717 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002718}
2719
2720const SessionDescriptionInterface* PeerConnection::current_remote_description()
2721 const {
Steve Anton75737c02017-11-06 10:37:17 -08002722 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002723}
2724
2725const SessionDescriptionInterface* PeerConnection::pending_local_description()
2726 const {
Steve Anton75737c02017-11-06 10:37:17 -08002727 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002728}
2729
2730const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2731 const {
Steve Anton75737c02017-11-06 10:37:17 -08002732 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002733}
2734
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002735void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002736 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002737 // Update stats here so that we have the most recent stats for tracks and
2738 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002739 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002740
Steve Anton75737c02017-11-06 10:37:17 -08002741 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08002742
Steve Anton8af21862017-12-15 11:20:13 -08002743 for (auto transceiver : transceivers_) {
2744 transceiver->Stop();
2745 }
2746 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08002747
deadbeef42a42632017-03-10 15:18:00 -08002748 network_thread()->Invoke<void>(
2749 RTC_FROM_HERE,
2750 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2751 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002752
Steve Anton978b8762017-09-29 12:15:02 -07002753 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002754 call_.reset();
2755 // The event log must outlive call (and any other object that uses it).
2756 event_log_.reset();
2757 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002758}
2759
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002760void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002761 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002762 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2763 SetSessionDescriptionMsg* param =
2764 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2765 param->observer->OnSuccess();
2766 delete param;
2767 break;
2768 }
2769 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2770 SetSessionDescriptionMsg* param =
2771 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2772 param->observer->OnFailure(param->error);
2773 delete param;
2774 break;
2775 }
deadbeefab9b2d12015-10-14 11:33:11 -07002776 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2777 CreateSessionDescriptionMsg* param =
2778 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2779 param->observer->OnFailure(param->error);
2780 delete param;
2781 break;
2782 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002783 case MSG_GETSTATS: {
2784 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002785 StatsReports reports;
2786 stats_->GetStats(param->track, &reports);
2787 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002788 delete param;
2789 break;
2790 }
deadbeefbd292462015-12-14 18:15:29 -08002791 case MSG_FREE_DATACHANNELS: {
2792 sctp_data_channels_to_free_.clear();
2793 break;
2794 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002795 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002796 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002797 break;
2798 }
2799}
2800
Steve Anton4171afb2017-11-20 10:20:22 -08002801void PeerConnection::CreateAudioReceiver(
2802 MediaStreamInterface* stream,
2803 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002804 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2805 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002806 auto* audio_receiver = new AudioRtpReceiver(
2807 worker_thread(), remote_sender_info.sender_id, streams);
2808 audio_receiver->SetMediaChannel(voice_media_channel());
2809 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2810 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2811 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002812 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002813 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002814}
2815
Steve Anton4171afb2017-11-20 10:20:22 -08002816void PeerConnection::CreateVideoReceiver(
2817 MediaStreamInterface* stream,
2818 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002819 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2820 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08002821 auto* video_receiver = new VideoRtpReceiver(
2822 worker_thread(), remote_sender_info.sender_id, streams);
2823 video_receiver->SetMediaChannel(video_media_channel());
2824 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
2825 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
2826 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08002827 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002828 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002829}
2830
deadbeef70ab1a12015-09-28 16:53:55 -07002831// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2832// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002833rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002834 const RtpSenderInfo& remote_sender_info) {
2835 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2836 if (!receiver) {
2837 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2838 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002839 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002840 }
Steve Anton4171afb2017-11-20 10:20:22 -08002841 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2842 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2843 } else {
2844 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2845 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002846 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002847}
2848
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002849void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2850 MediaStreamInterface* stream) {
2851 RTC_DCHECK(!IsClosed());
2852 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002853 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002854 // We already have a sender for this track, so just change the stream_id
2855 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002856 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002857 return;
2858 }
2859
2860 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002861 auto new_sender =
2862 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->label()});
2863 static_cast<AudioRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002864 ->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002865 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002866 // If the sender has already been configured in SDP, we call SetSsrc,
2867 // which will connect the sender to the underlying transport. This can
2868 // occur if a local session description that contains the ID of the sender
2869 // is set before AddStream is called. It can also occur if the local
2870 // session description is not changed and RemoveStream is called, and
2871 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002872 const RtpSenderInfo* sender_info =
2873 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2874 if (sender_info) {
2875 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002876 }
2877}
2878
2879// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2880// indefinitely, when we have unified plan SDP.
2881void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2882 MediaStreamInterface* stream) {
2883 RTC_DCHECK(!IsClosed());
2884 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002885 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002886 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2887 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002888 return;
2889 }
Steve Anton4171afb2017-11-20 10:20:22 -08002890 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002891}
2892
2893void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2894 MediaStreamInterface* stream) {
2895 RTC_DCHECK(!IsClosed());
2896 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002897 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002898 // We already have a sender for this track, so just change the stream_id
2899 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002900 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002901 return;
2902 }
2903
2904 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08002905 auto new_sender =
2906 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->label()});
2907 static_cast<VideoRtpSender*>(new_sender->internal())
Steve Anton47136dd2018-01-12 10:49:35 -08002908 ->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08002909 GetVideoTransceiver()->internal()->AddSender(new_sender);
2910 const RtpSenderInfo* sender_info =
2911 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2912 if (sender_info) {
2913 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002914 }
2915}
2916
2917void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2918 MediaStreamInterface* stream) {
2919 RTC_DCHECK(!IsClosed());
2920 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002921 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002922 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2923 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002924 return;
2925 }
Steve Anton4171afb2017-11-20 10:20:22 -08002926 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002927}
2928
Steve Antonba818672017-11-06 10:21:57 -08002929void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002930 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002931 if (ice_connection_state_ == new_state) {
2932 return;
2933 }
2934
deadbeefcbecd352015-09-23 11:50:27 -07002935 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002936 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002937 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002938 return;
2939 }
Steve Antonba818672017-11-06 10:21:57 -08002940
Mirko Bonadei675513b2017-11-09 11:09:25 +01002941 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2942 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002943 RTC_DCHECK(ice_connection_state_ !=
2944 PeerConnectionInterface::kIceConnectionClosed);
2945
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002946 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002947 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002948}
2949
2950void PeerConnection::OnIceGatheringChange(
2951 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002952 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002953 if (IsClosed()) {
2954 return;
2955 }
2956 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002957 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002958}
2959
jbauch81bf7b02017-03-25 08:31:12 -07002960void PeerConnection::OnIceCandidate(
2961 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002962 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002963 if (IsClosed()) {
2964 return;
2965 }
jbauch81bf7b02017-03-25 08:31:12 -07002966 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002967}
2968
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002969void PeerConnection::OnIceCandidatesRemoved(
2970 const std::vector<cricket::Candidate>& candidates) {
2971 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002972 if (IsClosed()) {
2973 return;
2974 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002975 observer_->OnIceCandidatesRemoved(candidates);
2976}
2977
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002978void PeerConnection::ChangeSignalingState(
2979 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002980 RTC_DCHECK(signaling_thread()->IsCurrent());
2981 if (signaling_state_ == signaling_state) {
2982 return;
2983 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002984 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2985 << GetSignalingStateString(signaling_state_)
2986 << " New state: "
2987 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002988 signaling_state_ = signaling_state;
2989 if (signaling_state == kClosed) {
2990 ice_connection_state_ = kIceConnectionClosed;
2991 observer_->OnIceConnectionChange(ice_connection_state_);
2992 if (ice_gathering_state_ != kIceGatheringComplete) {
2993 ice_gathering_state_ = kIceGatheringComplete;
2994 observer_->OnIceGatheringChange(ice_gathering_state_);
2995 }
2996 }
2997 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998}
2999
deadbeefeb459812015-12-15 19:24:43 -08003000void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3001 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003002 if (IsClosed()) {
3003 return;
3004 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003005 AddAudioTrack(track, stream);
3006 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003007}
3008
deadbeefeb459812015-12-15 19:24:43 -08003009void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3010 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003011 if (IsClosed()) {
3012 return;
3013 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003014 RemoveAudioTrack(track, stream);
3015 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003016}
3017
3018void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3019 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003020 if (IsClosed()) {
3021 return;
3022 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003023 AddVideoTrack(track, stream);
3024 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003025}
3026
3027void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3028 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003029 if (IsClosed()) {
3030 return;
3031 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003032 RemoveVideoTrack(track, stream);
3033 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003034}
3035
Henrik Boström31638672017-11-23 17:48:32 +01003036void PeerConnection::PostSetSessionDescriptionSuccess(
3037 SetSessionDescriptionObserver* observer) {
3038 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3039 signaling_thread()->Post(RTC_FROM_HERE, this,
3040 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3041}
3042
deadbeefab9b2d12015-10-14 11:33:11 -07003043void PeerConnection::PostSetSessionDescriptionFailure(
3044 SetSessionDescriptionObserver* observer,
3045 const std::string& error) {
3046 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3047 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003048 signaling_thread()->Post(RTC_FROM_HERE, this,
3049 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003050}
3051
3052void PeerConnection::PostCreateSessionDescriptionFailure(
3053 CreateSessionDescriptionObserver* observer,
3054 const std::string& error) {
3055 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3056 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003057 signaling_thread()->Post(RTC_FROM_HERE, this,
3058 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003059}
3060
zhihuang1c378ed2017-08-17 14:10:50 -07003061void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003062 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003063 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003064 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003065
Steve Antondcc3c022017-12-22 16:02:54 -08003066 if (IsUnifiedPlan()) {
3067 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3068 } else {
3069 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3070 }
3071
Steve Antonfa2260d2017-12-28 16:38:23 -08003072 // Intentionally unset the data channel type for RTP data channel with the
3073 // second condition. Otherwise the RTP data channels would be successfully
3074 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3075 // when building with chromium. We want to leave RTP data channels broken, so
3076 // people won't try to use them.
3077 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3078 session_options->data_channel_type = data_channel_type();
3079 }
3080
Steve Antondcc3c022017-12-22 16:02:54 -08003081 // Apply ICE restart flag and renomination flag.
3082 for (auto& options : session_options->media_description_options) {
3083 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3084 options.transport_options.enable_ice_renomination =
3085 configuration_.enable_ice_renomination;
3086 }
3087
3088 session_options->rtcp_cname = rtcp_cname_;
3089 session_options->crypto_options = factory_->options().crypto_options;
3090}
3091
3092void PeerConnection::GetOptionsForPlanBOffer(
3093 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3094 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003095 // Figure out transceiver directional preferences.
3096 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3097 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3098
3099 // By default, generate sendrecv/recvonly m= sections.
3100 bool recv_audio = true;
3101 bool recv_video = true;
3102
3103 // By default, only offer a new m= section if we have media to send with it.
3104 bool offer_new_audio_description = send_audio;
3105 bool offer_new_video_description = send_video;
3106 bool offer_new_data_description = HasDataChannels();
3107
3108 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003109 if (offer_answer_options.offer_to_receive_audio !=
3110 RTCOfferAnswerOptions::kUndefined) {
3111 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003112 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003113 offer_new_audio_description ||
3114 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003115 }
Steve Antondcc3c022017-12-22 16:02:54 -08003116 if (offer_answer_options.offer_to_receive_video !=
3117 RTCOfferAnswerOptions::kUndefined) {
3118 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003119 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003120 offer_new_video_description ||
3121 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003122 }
3123
3124 rtc::Optional<size_t> audio_index;
3125 rtc::Optional<size_t> video_index;
3126 rtc::Optional<size_t> data_index;
3127 // If a current description exists, generate m= sections in the same order,
3128 // using the first audio/video/data section that appears and rejecting
3129 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003130 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003131 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003132 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003133 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3134 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3135 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003136 }
3137
zhihuang1c378ed2017-08-17 14:10:50 -07003138 // Add audio/video/data m= sections to the end if needed.
3139 if (!audio_index && offer_new_audio_description) {
3140 session_options->media_description_options.push_back(
3141 cricket::MediaDescriptionOptions(
3142 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003143 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3144 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003145 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003146 }
zhihuang1c378ed2017-08-17 14:10:50 -07003147 if (!video_index && offer_new_video_description) {
3148 session_options->media_description_options.push_back(
3149 cricket::MediaDescriptionOptions(
3150 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003151 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3152 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003153 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003154 }
zhihuang1c378ed2017-08-17 14:10:50 -07003155 if (!data_index && offer_new_data_description) {
3156 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003157 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003158 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003159 }
3160
3161 cricket::MediaDescriptionOptions* audio_media_description_options =
3162 !audio_index ? nullptr
3163 : &session_options->media_description_options[*audio_index];
3164 cricket::MediaDescriptionOptions* video_media_description_options =
3165 !video_index ? nullptr
3166 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003167
Steve Anton4171afb2017-11-20 10:20:22 -08003168 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003169 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003170}
3171
3172// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3173// and return a reference to it.
3174// Generated MIDs should be no more than 3 bytes long to take up less space in
3175// the RTP packet.
3176static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3177 RTC_DCHECK(used_mids);
3178 // We're boring: just generate MIDs 0, 1, 2, ...
3179 size_t i = 0;
3180 std::set<std::string>::iterator it;
3181 bool inserted;
3182 do {
3183 std::string mid = rtc::ToString(i++);
3184 auto insert_result = used_mids->insert(mid);
3185 it = insert_result.first;
3186 inserted = insert_result.second;
3187 } while (!inserted);
3188 return *it;
3189}
3190
3191static cricket::MediaDescriptionOptions
3192GetMediaDescriptionOptionsForTransceiver(
3193 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3194 transceiver,
3195 const std::string& mid) {
3196 cricket::MediaDescriptionOptions media_description_options(
3197 transceiver->internal()->media_type(), mid, transceiver->direction(),
3198 transceiver->stopped());
3199 cricket::SenderOptions sender_options;
3200 sender_options.track_id = transceiver->sender()->id();
3201 sender_options.stream_ids = transceiver->sender()->stream_ids();
3202 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3203 // set in the RTP parameters when the transceiver was added.
3204 sender_options.num_sim_layers = 1;
3205 media_description_options.sender_options.push_back(sender_options);
3206 return media_description_options;
3207}
3208
3209void PeerConnection::GetOptionsForUnifiedPlanOffer(
3210 const RTCOfferAnswerOptions& offer_answer_options,
3211 cricket::MediaSessionOptions* session_options) {
3212 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3213 // Offers) and 5.2.2 (Subsequent Offers).
3214 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3215 const ContentInfos& local_contents =
3216 (local_description() ? local_description()->description()->contents()
3217 : ContentInfos());
3218 const ContentInfos& remote_contents =
3219 (remote_description() ? remote_description()->description()->contents()
3220 : ContentInfos());
3221 // The mline indices that can be recycled. New transceivers should reuse these
3222 // slots first.
3223 std::queue<size_t> recycleable_mline_indices;
3224 // Track the MIDs used in previous offer/answer exchanges and the current
3225 // offer so that new, unique MIDs are generated.
3226 std::set<std::string> used_mids = seen_mids_;
3227 // First, go through each media section that exists in either the local or
3228 // remote description and generate a media section in this offer for the
3229 // associated transceiver. If a media section can be recycled, generate a
3230 // default, rejected media section here that can be later overwritten.
3231 for (size_t i = 0;
3232 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3233 // Either |local_content| or |remote_content| is non-null.
3234 const ContentInfo* local_content =
3235 (i < local_contents.size() ? &local_contents[i] : nullptr);
3236 const ContentInfo* remote_content =
3237 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3238 bool had_been_rejected = (local_content && local_content->rejected) ||
3239 (remote_content && remote_content->rejected);
3240 const std::string& mid =
3241 (local_content ? local_content->name : remote_content->name);
3242 cricket::MediaType media_type =
3243 (local_content ? local_content->media_description()->type()
3244 : remote_content->media_description()->type());
3245 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3246 media_type == cricket::MEDIA_TYPE_VIDEO) {
3247 auto transceiver = GetAssociatedTransceiver(mid);
3248 RTC_CHECK(transceiver);
3249 // A media section is considered eligible for recycling if it is marked as
3250 // rejected in either the local or remote description.
3251 if (had_been_rejected) {
3252 session_options->media_description_options.push_back(
3253 cricket::MediaDescriptionOptions(
3254 transceiver->internal()->media_type(), mid,
3255 RtpTransceiverDirection::kInactive,
3256 /*stopped=*/true));
3257 recycleable_mline_indices.push(i);
3258 } else {
3259 session_options->media_description_options.push_back(
3260 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3261 // CreateOffer shouldn't really cause any state changes in
3262 // PeerConnection, but we need a way to match new transceivers to new
3263 // media sections in SetLocalDescription and JSEP specifies this is done
3264 // by recording the index of the media section generated for the
3265 // transceiver in the offer.
3266 transceiver->internal()->set_mline_index(i);
3267 }
3268 } else {
3269 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003270 RTC_CHECK(GetDataMid());
3271 if (had_been_rejected || mid != *GetDataMid()) {
3272 session_options->media_description_options.push_back(
3273 GetMediaDescriptionOptionsForRejectedData(mid));
3274 } else {
3275 session_options->media_description_options.push_back(
3276 GetMediaDescriptionOptionsForActiveData(mid));
3277 }
Steve Antondcc3c022017-12-22 16:02:54 -08003278 }
3279 }
3280 // Next, look for transceivers that are newly added (that is, are not stopped
3281 // and not associated). Reuse media sections marked as recyclable first,
3282 // otherwise append to the end of the offer. New media sections should be
3283 // added in the order they were added to the PeerConnection.
3284 for (auto transceiver : transceivers_) {
3285 if (transceiver->mid() || transceiver->stopped()) {
3286 continue;
3287 }
3288 size_t mline_index;
3289 if (!recycleable_mline_indices.empty()) {
3290 mline_index = recycleable_mline_indices.front();
3291 recycleable_mline_indices.pop();
3292 session_options->media_description_options[mline_index] =
3293 GetMediaDescriptionOptionsForTransceiver(transceiver,
3294 AllocateMid(&used_mids));
3295 } else {
3296 mline_index = session_options->media_description_options.size();
3297 session_options->media_description_options.push_back(
3298 GetMediaDescriptionOptionsForTransceiver(transceiver,
3299 AllocateMid(&used_mids)));
3300 }
3301 // See comment above for why CreateOffer changes the transceiver's state.
3302 transceiver->internal()->set_mline_index(mline_index);
3303 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003304 // Lastly, add a m-section if we have local data channels and an m section
3305 // does not already exist.
3306 if (!GetDataMid() && HasDataChannels()) {
3307 session_options->media_description_options.push_back(
3308 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3309 }
Steve Antondcc3c022017-12-22 16:02:54 -08003310}
3311
3312void PeerConnection::GetOptionsForAnswer(
3313 const RTCOfferAnswerOptions& offer_answer_options,
3314 cricket::MediaSessionOptions* session_options) {
3315 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3316
3317 if (IsUnifiedPlan()) {
3318 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3319 } else {
3320 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3321 }
3322
Steve Antonfa2260d2017-12-28 16:38:23 -08003323 // Intentionally unset the data channel type for RTP data channel. Otherwise
3324 // the RTP data channels would be successfully negotiated by default and the
3325 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3326 // We want to leave RTP data channels broken, so people won't try to use them.
3327 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3328 session_options->data_channel_type = data_channel_type();
3329 }
3330
Steve Antondcc3c022017-12-22 16:02:54 -08003331 // Apply ICE renomination flag.
3332 for (auto& options : session_options->media_description_options) {
3333 options.transport_options.enable_ice_renomination =
3334 configuration_.enable_ice_renomination;
3335 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003336
3337 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003338 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07003339}
3340
Steve Antondcc3c022017-12-22 16:02:54 -08003341void PeerConnection::GetOptionsForPlanBAnswer(
3342 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003343 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003344 // Figure out transceiver directional preferences.
3345 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3346 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3347
3348 // By default, generate sendrecv/recvonly m= sections. The direction is also
3349 // restricted by the direction in the offer.
3350 bool recv_audio = true;
3351 bool recv_video = true;
3352
3353 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003354 if (offer_answer_options.offer_to_receive_audio !=
3355 RTCOfferAnswerOptions::kUndefined) {
3356 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003357 }
Steve Antondcc3c022017-12-22 16:02:54 -08003358 if (offer_answer_options.offer_to_receive_video !=
3359 RTCOfferAnswerOptions::kUndefined) {
3360 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003361 }
3362
3363 rtc::Optional<size_t> audio_index;
3364 rtc::Optional<size_t> video_index;
3365 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08003366 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07003367 // The pending remote description should be an offer.
Steve Antona3a92c22017-12-07 10:27:41 -08003368 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
zhihuang141aacb2017-08-29 13:23:53 -07003369 // Generate m= sections that match those in the offer.
3370 // Note that mediasession.cc will handle intersection our preferred
3371 // direction with the offered direction.
3372 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003373 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003374 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3375 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3376 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07003377 }
zhihuang1c378ed2017-08-17 14:10:50 -07003378
3379 cricket::MediaDescriptionOptions* audio_media_description_options =
3380 !audio_index ? nullptr
3381 : &session_options->media_description_options[*audio_index];
3382 cricket::MediaDescriptionOptions* video_media_description_options =
3383 !video_index ? nullptr
3384 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003385
Steve Anton4171afb2017-11-20 10:20:22 -08003386 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003387 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003388}
zhihuangaf388472016-11-02 16:49:48 -07003389
Steve Antondcc3c022017-12-22 16:02:54 -08003390void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3391 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3392 cricket::MediaSessionOptions* session_options) {
3393 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3394 // Answers) and 5.3.2 (Subsequent Answers).
3395 RTC_DCHECK(remote_description());
3396 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3397 for (const ContentInfo& content :
3398 remote_description()->description()->contents()) {
3399 cricket::MediaType media_type = content.media_description()->type();
3400 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3401 media_type == cricket::MEDIA_TYPE_VIDEO) {
3402 auto transceiver = GetAssociatedTransceiver(content.name);
3403 RTC_CHECK(transceiver);
3404 session_options->media_description_options.push_back(
3405 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3406 } else {
3407 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003408 // Reject all data sections if data channels are disabled.
3409 // Reject a data section if it has already been rejected.
3410 // Reject all data sections except for the first one.
3411 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3412 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003413 session_options->media_description_options.push_back(
3414 GetMediaDescriptionOptionsForRejectedData(content.name));
3415 } else {
3416 session_options->media_description_options.push_back(
3417 GetMediaDescriptionOptionsForActiveData(content.name));
3418 }
Steve Antondcc3c022017-12-22 16:02:54 -08003419 }
3420 }
htaa2a49d92016-03-04 02:51:39 -08003421}
3422
zhihuang1c378ed2017-08-17 14:10:50 -07003423void PeerConnection::GenerateMediaDescriptionOptions(
3424 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003425 RtpTransceiverDirection audio_direction,
3426 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003427 rtc::Optional<size_t>* audio_index,
3428 rtc::Optional<size_t>* video_index,
3429 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003430 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003431 for (const cricket::ContentInfo& content :
3432 session_desc->description()->contents()) {
3433 if (IsAudioContent(&content)) {
3434 // If we already have an audio m= section, reject this extra one.
3435 if (*audio_index) {
3436 session_options->media_description_options.push_back(
3437 cricket::MediaDescriptionOptions(
3438 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003439 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003440 } else {
3441 session_options->media_description_options.push_back(
3442 cricket::MediaDescriptionOptions(
3443 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003444 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003445 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003446 }
3447 } else if (IsVideoContent(&content)) {
3448 // If we already have an video m= section, reject this extra one.
3449 if (*video_index) {
3450 session_options->media_description_options.push_back(
3451 cricket::MediaDescriptionOptions(
3452 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003453 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003454 } else {
3455 session_options->media_description_options.push_back(
3456 cricket::MediaDescriptionOptions(
3457 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003458 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003459 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003460 }
3461 } else {
3462 RTC_DCHECK(IsDataContent(&content));
3463 // If we already have an data m= section, reject this extra one.
3464 if (*data_index) {
3465 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003466 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003467 } else {
3468 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003469 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003470 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003471 }
3472 }
htaa2a49d92016-03-04 02:51:39 -08003473 }
deadbeefab9b2d12015-10-14 11:33:11 -07003474}
3475
Steve Antonfa2260d2017-12-28 16:38:23 -08003476cricket::MediaDescriptionOptions
3477PeerConnection::GetMediaDescriptionOptionsForActiveData(
3478 const std::string& mid) const {
3479 // Direction for data sections is meaningless, but legacy endpoints might
3480 // expect sendrecv.
3481 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3482 RtpTransceiverDirection::kSendRecv,
3483 /*stopped=*/false);
3484 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3485 return options;
3486}
3487
3488cricket::MediaDescriptionOptions
3489PeerConnection::GetMediaDescriptionOptionsForRejectedData(
3490 const std::string& mid) const {
3491 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3492 RtpTransceiverDirection::kInactive,
3493 /*stopped=*/true);
3494 AddRtpDataChannelOptions(rtp_data_channels_, &options);
3495 return options;
3496}
3497
3498rtc::Optional<std::string> PeerConnection::GetDataMid() const {
3499 switch (data_channel_type_) {
3500 case cricket::DCT_RTP:
3501 if (!rtp_data_channel_) {
3502 return rtc::nullopt;
3503 }
3504 return rtp_data_channel_->content_name();
3505 case cricket::DCT_SCTP:
3506 return sctp_content_name_;
3507 default:
3508 return rtc::nullopt;
3509 }
3510}
3511
Steve Anton4171afb2017-11-20 10:20:22 -08003512void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
3513 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
3514 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08003515 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08003516}
3517
Steve Anton4171afb2017-11-20 10:20:22 -08003518void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07003519 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08003520 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07003521 cricket::MediaType media_type,
3522 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08003523 std::vector<RtpSenderInfo>* current_senders =
3524 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003525
Steve Anton4171afb2017-11-20 10:20:22 -08003526 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08003527 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003528 for (auto sender_it = current_senders->begin();
3529 sender_it != current_senders->end();
3530 /* incremented manually */) {
3531 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003532 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003533 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3534 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08003535 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08003536 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
3537 sender_exists) {
3538 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08003539 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003540 OnRemoteSenderRemoved(info, media_type);
3541 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003542 }
3543 }
3544
Steve Anton4171afb2017-11-20 10:20:22 -08003545 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003546 for (const cricket::StreamParams& params : streams) {
3547 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003548 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003549 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003550 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003551 uint32_t ssrc = params.first_ssrc();
3552
3553 rtc::scoped_refptr<MediaStreamInterface> stream =
3554 remote_streams_->find(stream_label);
3555 if (!stream) {
3556 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003557 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
3558 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07003559 remote_streams_->AddStream(stream);
3560 new_streams->AddStream(stream);
3561 }
3562
Steve Anton4171afb2017-11-20 10:20:22 -08003563 const RtpSenderInfo* sender_info =
3564 FindSenderInfo(*current_senders, stream_label, sender_id);
3565 if (!sender_info) {
3566 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3567 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003568 }
3569 }
deadbeefbda7e0b2015-12-08 17:13:40 -08003570
Steve Anton4171afb2017-11-20 10:20:22 -08003571 // Add default sender if necessary.
3572 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08003573 rtc::scoped_refptr<MediaStreamInterface> default_stream =
3574 remote_streams_->find(kDefaultStreamLabel);
3575 if (!default_stream) {
3576 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07003577 default_stream = MediaStreamProxy::Create(
3578 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08003579 remote_streams_->AddStream(default_stream);
3580 new_streams->AddStream(default_stream);
3581 }
Steve Anton4171afb2017-11-20 10:20:22 -08003582 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
3583 ? kDefaultAudioSenderId
3584 : kDefaultVideoSenderId;
3585 const RtpSenderInfo* default_sender_info = FindSenderInfo(
3586 *current_senders, kDefaultStreamLabel, default_sender_id);
3587 if (!default_sender_info) {
3588 current_senders->push_back(
3589 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
3590 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08003591 }
3592 }
deadbeefab9b2d12015-10-14 11:33:11 -07003593}
3594
Steve Anton4171afb2017-11-20 10:20:22 -08003595void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
3596 cricket::MediaType media_type) {
3597 MediaStreamInterface* stream =
3598 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003599
3600 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003601 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003602 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08003603 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003604 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08003605 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003606 }
3607}
3608
Steve Anton4171afb2017-11-20 10:20:22 -08003609void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
3610 cricket::MediaType media_type) {
3611 MediaStreamInterface* stream =
3612 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07003613
Henrik Boström933d8b02017-10-10 10:05:16 -07003614 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07003615 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07003616 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
3617 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003618 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003619 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003620 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003621 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07003622 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003623 }
3624 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07003625 // Stopping or destroying a VideoRtpReceiver will end the
3626 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08003627 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07003628 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08003629 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07003630 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07003631 // There's no guarantee the track is still available, e.g. the track may
3632 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07003633 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07003634 }
3635 } else {
nisseede5da42017-01-12 05:15:36 -08003636 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07003637 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003638 if (receiver) {
3639 observer_->OnRemoveTrack(receiver);
3640 }
deadbeefab9b2d12015-10-14 11:33:11 -07003641}
3642
3643void PeerConnection::UpdateEndedRemoteMediaStreams() {
3644 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
3645 for (size_t i = 0; i < remote_streams_->count(); ++i) {
3646 MediaStreamInterface* stream = remote_streams_->at(i);
3647 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
3648 streams_to_remove.push_back(stream);
3649 }
3650 }
3651
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003652 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07003653 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003654 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07003655 }
3656}
3657
Steve Anton4171afb2017-11-20 10:20:22 -08003658void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07003659 const std::vector<cricket::StreamParams>& streams,
3660 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08003661 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003662
3663 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
3664 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08003665 for (auto sender_it = current_senders->begin();
3666 sender_it != current_senders->end();
3667 /* incremented manually */) {
3668 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003669 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08003670 cricket::GetStreamBySsrc(streams, info.first_ssrc);
3671 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07003672 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08003673 OnLocalSenderRemoved(info, media_type);
3674 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07003675 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08003676 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07003677 }
3678 }
3679
Steve Anton4171afb2017-11-20 10:20:22 -08003680 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07003681 for (const cricket::StreamParams& params : streams) {
3682 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08003683 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07003684 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08003685 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07003686 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08003687 const RtpSenderInfo* sender_info =
3688 FindSenderInfo(*current_senders, stream_label, sender_id);
3689 if (!sender_info) {
3690 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
3691 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07003692 }
3693 }
3694}
3695
Steve Anton4171afb2017-11-20 10:20:22 -08003696void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
3697 cricket::MediaType media_type) {
3698 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003699 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08003700 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
3701 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01003702 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07003703 return;
3704 }
3705
deadbeeffac06552015-11-25 11:26:01 -08003706 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003707 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3708 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003709 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003710 }
deadbeeffac06552015-11-25 11:26:01 -08003711
Steve Anton4171afb2017-11-20 10:20:22 -08003712 sender->internal()->set_stream_id(sender_info.stream_label);
3713 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07003714}
3715
Steve Anton4171afb2017-11-20 10:20:22 -08003716void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
3717 cricket::MediaType media_type) {
3718 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08003719 if (!sender) {
3720 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07003721 // SessionDescriptions has been renegotiated.
3722 return;
3723 }
deadbeeffac06552015-11-25 11:26:01 -08003724
3725 // A sender has been removed from the SessionDescription but it's still
3726 // associated with the PeerConnection. This only occurs if the SDP doesn't
3727 // match with the calls to CreateSender, AddStream and RemoveStream.
3728 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003729 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
3730 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003731 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003732 }
deadbeeffac06552015-11-25 11:26:01 -08003733
Steve Anton4171afb2017-11-20 10:20:22 -08003734 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003735}
3736
3737void PeerConnection::UpdateLocalRtpDataChannels(
3738 const cricket::StreamParamsVec& streams) {
3739 std::vector<std::string> existing_channels;
3740
3741 // Find new and active data channels.
3742 for (const cricket::StreamParams& params : streams) {
3743 // |it->sync_label| is actually the data channel label. The reason is that
3744 // we use the same naming of data channels as we do for
3745 // MediaStreams and Tracks.
3746 // For MediaStreams, the sync_label is the MediaStream label and the
3747 // track label is the same as |streamid|.
3748 const std::string& channel_label = params.sync_label;
3749 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003750 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003751 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003752 continue;
3753 }
3754 // Set the SSRC the data channel should use for sending.
3755 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3756 existing_channels.push_back(data_channel_it->first);
3757 }
3758
3759 UpdateClosingRtpDataChannels(existing_channels, true);
3760}
3761
3762void PeerConnection::UpdateRemoteRtpDataChannels(
3763 const cricket::StreamParamsVec& streams) {
3764 std::vector<std::string> existing_channels;
3765
3766 // Find new and active data channels.
3767 for (const cricket::StreamParams& params : streams) {
3768 // The data channel label is either the mslabel or the SSRC if the mslabel
3769 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3770 std::string label = params.sync_label.empty()
3771 ? rtc::ToString(params.first_ssrc())
3772 : params.sync_label;
3773 auto data_channel_it = rtp_data_channels_.find(label);
3774 if (data_channel_it == rtp_data_channels_.end()) {
3775 // This is a new data channel.
3776 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3777 } else {
3778 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3779 }
3780 existing_channels.push_back(label);
3781 }
3782
3783 UpdateClosingRtpDataChannels(existing_channels, false);
3784}
3785
3786void PeerConnection::UpdateClosingRtpDataChannels(
3787 const std::vector<std::string>& active_channels,
3788 bool is_local_update) {
3789 auto it = rtp_data_channels_.begin();
3790 while (it != rtp_data_channels_.end()) {
3791 DataChannel* data_channel = it->second;
3792 if (std::find(active_channels.begin(), active_channels.end(),
3793 data_channel->label()) != active_channels.end()) {
3794 ++it;
3795 continue;
3796 }
3797
3798 if (is_local_update) {
3799 data_channel->SetSendSsrc(0);
3800 } else {
3801 data_channel->RemotePeerRequestClose();
3802 }
3803
3804 if (data_channel->state() == DataChannel::kClosed) {
3805 rtp_data_channels_.erase(it);
3806 it = rtp_data_channels_.begin();
3807 } else {
3808 ++it;
3809 }
3810 }
3811}
3812
3813void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3814 uint32_t remote_ssrc) {
3815 rtc::scoped_refptr<DataChannel> channel(
3816 InternalCreateDataChannel(label, nullptr));
3817 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003818 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3819 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003820 return;
3821 }
3822 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003823 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3824 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003825 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003826}
3827
3828rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3829 const std::string& label,
3830 const InternalDataChannelInit* config) {
3831 if (IsClosed()) {
3832 return nullptr;
3833 }
Steve Anton75737c02017-11-06 10:37:17 -08003834 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003835 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003836 << "InternalCreateDataChannel: Data is not supported in this call.";
3837 return nullptr;
3838 }
3839 InternalDataChannelInit new_config =
3840 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003841 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003842 if (new_config.id < 0) {
3843 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003844 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003845 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003846 RTC_LOG(LS_ERROR)
3847 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003848 return nullptr;
3849 }
3850 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003851 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3852 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003853 return nullptr;
3854 }
3855 }
3856
Steve Anton75737c02017-11-06 10:37:17 -08003857 rtc::scoped_refptr<DataChannel> channel(
3858 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003859 if (!channel) {
3860 sid_allocator_.ReleaseSid(new_config.id);
3861 return nullptr;
3862 }
3863
3864 if (channel->data_channel_type() == cricket::DCT_RTP) {
3865 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003866 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3867 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003868 return nullptr;
3869 }
3870 rtp_data_channels_[channel->label()] = channel;
3871 } else {
3872 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3873 sctp_data_channels_.push_back(channel);
3874 channel->SignalClosed.connect(this,
3875 &PeerConnection::OnSctpDataChannelClosed);
3876 }
3877
hbos82ebe022016-11-14 01:41:09 -08003878 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003879 return channel;
3880}
3881
3882bool PeerConnection::HasDataChannels() const {
3883 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3884}
3885
3886void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3887 for (const auto& channel : sctp_data_channels_) {
3888 if (channel->id() < 0) {
3889 int sid;
3890 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003891 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003892 continue;
3893 }
3894 channel->SetSctpSid(sid);
3895 }
3896 }
3897}
3898
3899void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003900 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003901 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3902 ++it) {
3903 if (it->get() == channel) {
3904 if (channel->id() >= 0) {
3905 sid_allocator_.ReleaseSid(channel->id());
3906 }
deadbeefbd292462015-12-14 18:15:29 -08003907 // Since this method is triggered by a signal from the DataChannel,
3908 // we can't free it directly here; we need to free it asynchronously.
3909 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003910 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003911 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3912 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003913 return;
3914 }
3915 }
3916}
3917
deadbeefab9b2d12015-10-14 11:33:11 -07003918void PeerConnection::OnDataChannelDestroyed() {
3919 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3920 // DataChannel may callback to us and try to modify the list.
3921 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3922 temp_rtp_dcs.swap(rtp_data_channels_);
3923 for (const auto& kv : temp_rtp_dcs) {
3924 kv.second->OnTransportChannelDestroyed();
3925 }
3926
3927 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3928 temp_sctp_dcs.swap(sctp_data_channels_);
3929 for (const auto& channel : temp_sctp_dcs) {
3930 channel->OnTransportChannelDestroyed();
3931 }
3932}
3933
3934void PeerConnection::OnDataChannelOpenMessage(
3935 const std::string& label,
3936 const InternalDataChannelInit& config) {
3937 rtc::scoped_refptr<DataChannel> channel(
3938 InternalCreateDataChannel(label, &config));
3939 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003940 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003941 return;
3942 }
3943
deadbeefa601f5c2016-06-06 14:27:39 -07003944 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3945 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003946 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003947}
3948
Steve Anton4171afb2017-11-20 10:20:22 -08003949rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3950PeerConnection::GetAudioTransceiver() const {
3951 // This method only works with Plan B SDP, where there is a single
3952 // audio/video transceiver.
3953 RTC_DCHECK(!IsUnifiedPlan());
3954 for (auto transceiver : transceivers_) {
3955 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3956 return transceiver;
3957 }
3958 }
3959 RTC_NOTREACHED();
3960 return nullptr;
3961}
3962
3963rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3964PeerConnection::GetVideoTransceiver() const {
3965 // This method only works with Plan B SDP, where there is a single
3966 // audio/video transceiver.
3967 RTC_DCHECK(!IsUnifiedPlan());
3968 for (auto transceiver : transceivers_) {
3969 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3970 return transceiver;
3971 }
3972 }
3973 RTC_NOTREACHED();
3974 return nullptr;
3975}
3976
3977// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3978// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003979bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003980 switch (type) {
3981 case cricket::MEDIA_TYPE_AUDIO:
3982 return !GetAudioTransceiver()->internal()->senders().empty();
3983 case cricket::MEDIA_TYPE_VIDEO:
3984 return !GetVideoTransceiver()->internal()->senders().empty();
3985 case cricket::MEDIA_TYPE_DATA:
3986 return false;
3987 }
3988 RTC_NOTREACHED();
3989 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003990}
3991
Steve Anton4171afb2017-11-20 10:20:22 -08003992rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3993PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3994 for (auto transceiver : transceivers_) {
3995 for (auto sender : transceiver->internal()->senders()) {
3996 if (sender->track() == track) {
3997 return sender;
3998 }
3999 }
4000 }
4001 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004002}
4003
Steve Anton4171afb2017-11-20 10:20:22 -08004004rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4005PeerConnection::FindSenderById(const std::string& sender_id) const {
4006 for (auto transceiver : transceivers_) {
4007 for (auto sender : transceiver->internal()->senders()) {
4008 if (sender->id() == sender_id) {
4009 return sender;
4010 }
4011 }
4012 }
4013 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004014}
4015
Steve Anton4171afb2017-11-20 10:20:22 -08004016rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4017PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4018 for (auto transceiver : transceivers_) {
4019 for (auto receiver : transceiver->internal()->receivers()) {
4020 if (receiver->id() == receiver_id) {
4021 return receiver;
4022 }
4023 }
4024 }
4025 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004026}
4027
Steve Anton4171afb2017-11-20 10:20:22 -08004028std::vector<PeerConnection::RtpSenderInfo>*
4029PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4030 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4031 media_type == cricket::MEDIA_TYPE_VIDEO);
4032 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4033 ? &remote_audio_sender_infos_
4034 : &remote_video_sender_infos_;
4035}
4036
4037std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004038 cricket::MediaType media_type) {
4039 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4040 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004041 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4042 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004043}
4044
Steve Anton4171afb2017-11-20 10:20:22 -08004045const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4046 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07004047 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08004048 const std::string sender_id) const {
4049 for (const RtpSenderInfo& sender_info : infos) {
4050 if (sender_info.stream_label == stream_label &&
4051 sender_info.sender_id == sender_id) {
4052 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004053 }
4054 }
4055 return nullptr;
4056}
4057
4058DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4059 for (const auto& channel : sctp_data_channels_) {
4060 if (channel->id() == sid) {
4061 return channel;
4062 }
4063 }
4064 return nullptr;
4065}
4066
deadbeef91dd5672016-05-18 16:55:30 -07004067bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004068 const RTCConfiguration& configuration) {
4069 cricket::ServerAddresses stun_servers;
4070 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004071 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4072 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004073 return false;
4074 }
4075
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004076 port_allocator_->Initialize();
4077
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004078 // To handle both internal and externally created port allocator, we will
4079 // enable BUNDLE here.
4080 int portallocator_flags = port_allocator_->flags();
4081 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08004082 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4083 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004084 // If the disable-IPv6 flag was specified, we'll not override it
4085 // by experiment.
4086 if (configuration.disable_ipv6) {
4087 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004088 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4089 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004090 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
4091 }
4092
zhihuangb09b3f92017-03-07 14:40:51 -08004093 if (configuration.disable_ipv6_on_wifi) {
4094 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004095 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004096 }
4097
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004098 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
4099 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004100 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004101 }
4102
honghaiz60347052016-05-31 18:29:12 -07004103 if (configuration.candidate_network_policy ==
4104 kCandidateNetworkPolicyLowCost) {
4105 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004106 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004107 }
4108
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004109 port_allocator_->set_flags(portallocator_flags);
4110 // No step delay is used while allocating ports.
4111 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4112 port_allocator_->set_candidate_filter(
4113 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004114 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004115
4116 // Call this last since it may create pooled allocator sessions using the
4117 // properties set above.
4118 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07004119 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004120 configuration.prune_turn_ports,
4121 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004122 return true;
4123}
4124
deadbeef91dd5672016-05-18 16:55:30 -07004125bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004126 const cricket::ServerAddresses& stun_servers,
4127 const std::vector<cricket::RelayServerConfig>& turn_servers,
4128 IceTransportsType type,
4129 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004130 bool prune_turn_ports,
4131 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004132 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004133 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004134 // Call this last since it may create pooled allocator sessions using the
4135 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004136 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004137 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
4138 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004139}
4140
Steve Antonba818672017-11-06 10:21:57 -08004141cricket::ChannelManager* PeerConnection::channel_manager() const {
4142 return factory_->channel_manager();
4143}
4144
4145MetricsObserverInterface* PeerConnection::metrics_observer() const {
4146 return uma_observer_;
4147}
4148
Elad Alon99c3fe52017-10-13 16:29:40 +02004149bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004150 std::unique_ptr<RtcEventLogOutput> output,
4151 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004152 if (!event_log_) {
4153 return false;
4154 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004155 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004156}
4157
4158void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004159 if (event_log_) {
4160 event_log_->StopLogging();
4161 }
ivoc14d5dbe2016-07-04 07:06:55 -07004162}
nisseeaabdf62017-05-05 02:23:02 -07004163
Steve Anton75737c02017-11-06 10:37:17 -08004164cricket::BaseChannel* PeerConnection::GetChannel(
4165 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004166 for (auto transceiver : transceivers_) {
4167 cricket::BaseChannel* channel = transceiver->internal()->channel();
4168 if (channel && channel->content_name() == content_name) {
4169 return channel;
4170 }
Steve Anton75737c02017-11-06 10:37:17 -08004171 }
4172 if (rtp_data_channel() &&
4173 rtp_data_channel()->content_name() == content_name) {
4174 return rtp_data_channel();
4175 }
4176 return nullptr;
4177}
4178
4179bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4180 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004181 RTC_LOG(LS_INFO)
4182 << "Local and Remote descriptions must be applied to get the "
4183 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004184 return false;
4185 }
4186 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004187 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
4188 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004189 return false;
4190 }
4191
4192 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
4193}
4194
4195bool PeerConnection::GetSslRole(const std::string& content_name,
4196 rtc::SSLRole* role) {
4197 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004198 RTC_LOG(LS_INFO)
4199 << "Local and Remote descriptions must be applied to get the "
4200 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004201 return false;
4202 }
4203
4204 return transport_controller_->GetSslRole(GetTransportName(content_name),
4205 role);
4206}
4207
Steve Anton75737c02017-11-06 10:37:17 -08004208// TODO(steveanton): Eventually it'd be nice to store the channels as a single
4209// vector of BaseChannel pointers instead of separate voice and video channel
4210// vectors. At that point, this will become a simple getter.
4211std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
4212 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08004213 if (voice_channel()) {
4214 channels.push_back(voice_channel());
4215 }
4216 if (video_channel()) {
4217 channels.push_back(video_channel());
4218 }
Steve Anton75737c02017-11-06 10:37:17 -08004219 if (rtp_data_channel_) {
4220 channels.push_back(rtp_data_channel_);
4221 }
4222 return channels;
4223}
4224
Steve Antonf8470812017-12-04 10:46:21 -08004225void PeerConnection::SetSessionError(SessionError error,
4226 const std::string& error_desc) {
4227 RTC_DCHECK_RUN_ON(signaling_thread());
4228 if (error != session_error_) {
4229 session_error_ = error;
4230 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004231 }
4232}
4233
Steve Anton3828c062017-12-06 10:34:51 -08004234RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004235 cricket::ContentSource source) {
4236 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004237
4238 // If there's already a pending error then no state transition should happen.
4239 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004240 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004241
4242 // If this is an answer then we know whether to BUNDLE or not. If both the
4243 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08004244 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004245 const cricket::ContentGroup* local_bundle =
4246 local_description()->description()->GetGroupByName(
4247 cricket::GROUP_TYPE_BUNDLE);
4248 const cricket::ContentGroup* remote_bundle =
4249 remote_description()->description()->GetGroupByName(
4250 cricket::GROUP_TYPE_BUNDLE);
4251 if (local_bundle && remote_bundle) {
4252 // The answerer decides the transport to bundle on.
4253 const cricket::ContentGroup* answer_bundle =
4254 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
4255 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08004256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4257 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08004258 }
4259 }
Steve Anton75737c02017-11-06 10:37:17 -08004260 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004261
4262 // Only push down the transport description after potentially enabling BUNDLE;
4263 // we don't want to push down a description on a transport about to be
4264 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08004265 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004266 if (!error.ok()) {
4267 return error;
4268 }
4269
4270 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004271 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004272 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004273 }
4274
4275 // Update the signaling state according to the specified state machine (see
4276 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004277 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004278 ChangeSignalingState(source == cricket::CS_LOCAL
4279 ? PeerConnectionInterface::kHaveLocalOffer
4280 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004281 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004282 ChangeSignalingState(source == cricket::CS_LOCAL
4283 ? PeerConnectionInterface::kHaveLocalPrAnswer
4284 : PeerConnectionInterface::kHaveRemotePrAnswer);
4285 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004286 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004287 ChangeSignalingState(PeerConnectionInterface::kStable);
4288 }
4289
4290 // Update internal objects according to the session description's media
4291 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08004292 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004293 if (!error.ok()) {
4294 SetSessionError(SessionError::kContent, error.message());
4295 }
4296 if (session_error() != SessionError::kNone) {
4297 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
4298 }
4299
Steve Anton8a006912017-12-04 15:25:56 -08004300 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004301}
4302
Steve Anton8a006912017-12-04 15:25:56 -08004303RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004304 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004305 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004306 const SessionDescriptionInterface* sdesc =
4307 (source == cricket::CS_LOCAL ? local_description()
4308 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004309 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004310
4311 // Push down the new SDP media section for each audio/video transceiver.
4312 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004313 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004314 FindMediaSectionForTransceiver(transceiver, sdesc);
4315 cricket::BaseChannel* channel = transceiver->internal()->channel();
4316 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004317 continue;
4318 }
4319 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004320 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004321 if (!content_desc) {
4322 continue;
4323 }
4324 std::string error;
4325 bool success =
4326 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004327 ? channel->SetLocalContent(content_desc, type, &error)
4328 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004329 if (!success) {
4330 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4331 }
4332 }
4333
4334 // If using the RtpDataChannel, push down the new SDP section for it too.
4335 if (rtp_data_channel_) {
4336 const ContentInfo* data_content =
4337 cricket::GetFirstDataContent(sdesc->description());
4338 if (data_content && !data_content->rejected) {
4339 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004340 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004341 if (data_desc) {
4342 std::string error;
4343 bool success =
4344 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004345 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4346 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004347 &error);
4348 if (!success) {
4349 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4350 std::move(error));
4351 }
Steve Anton75737c02017-11-06 10:37:17 -08004352 }
4353 }
4354 }
Steve Antoned10bd92017-12-05 10:52:59 -08004355
Steve Anton75737c02017-11-06 10:37:17 -08004356 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4357 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4358 if (sctp_transport_ && local_description() && remote_description() &&
4359 cricket::GetFirstDataContent(local_description()->description()) &&
4360 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004361 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004362 RTC_FROM_HERE,
4363 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004364 if (!success) {
4365 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4366 "Failed to push down SCTP parameters.");
4367 }
Steve Anton75737c02017-11-06 10:37:17 -08004368 }
Steve Antoned10bd92017-12-05 10:52:59 -08004369
Steve Anton8a006912017-12-04 15:25:56 -08004370 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004371}
4372
4373bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4374 RTC_DCHECK(network_thread()->IsCurrent());
4375 RTC_DCHECK(local_description());
4376 RTC_DCHECK(remote_description());
4377 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4378 // When we support "max-message-size", that would also be pushed down here.
4379 return sctp_transport_->Start(
4380 GetSctpPort(local_description()->description()),
4381 GetSctpPort(remote_description()->description()));
4382}
4383
Steve Anton8a006912017-12-04 15:25:56 -08004384RTCError PeerConnection::PushdownTransportDescription(
4385 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004386 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004387 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004388
Steve Anton8a006912017-12-04 15:25:56 -08004389 const SessionDescriptionInterface* sdesc =
4390 (source == cricket::CS_LOCAL ? local_description()
4391 : remote_description());
4392 RTC_DCHECK(sdesc);
4393 for (const cricket::TransportInfo& tinfo :
4394 sdesc->description()->transport_infos()) {
4395 std::string error;
4396 bool success;
4397 if (source == cricket::CS_LOCAL) {
4398 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004399 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004400 } else {
4401 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004402 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08004403 }
4404 if (!success) {
Steve Antondcc3c022017-12-22 16:02:54 -08004405 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4406 "Failed to push down transport description for " +
4407 tinfo.content_name + ": " + error);
Steve Anton75737c02017-11-06 10:37:17 -08004408 }
4409 }
4410
Steve Anton8a006912017-12-04 15:25:56 -08004411 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004412}
4413
4414bool PeerConnection::GetTransportDescription(
4415 const SessionDescription* description,
4416 const std::string& content_name,
4417 cricket::TransportDescription* tdesc) {
4418 if (!description || !tdesc) {
4419 return false;
4420 }
4421 const TransportInfo* transport_info =
4422 description->GetTransportInfoByName(content_name);
4423 if (!transport_info) {
4424 return false;
4425 }
4426 *tdesc = transport_info->description;
4427 return true;
4428}
4429
4430bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
4431 const std::string* first_content_name = bundle.FirstContentName();
4432 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004433 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004434 return false;
4435 }
4436 const std::string& transport_name = *first_content_name;
4437
4438 auto maybe_set_transport = [this, bundle,
4439 transport_name](cricket::BaseChannel* ch) {
4440 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08004441 return;
Steve Anton75737c02017-11-06 10:37:17 -08004442 }
4443
4444 std::string old_transport_name = ch->transport_name();
4445 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004446 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
4447 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08004448 return;
Steve Anton75737c02017-11-06 10:37:17 -08004449 }
4450
4451 cricket::DtlsTransportInternal* rtp_dtls_transport =
4452 transport_controller_->CreateDtlsTransport(
4453 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4454 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
4455 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4456 if (need_rtcp) {
4457 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4458 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4459 }
4460
4461 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004462 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
4463 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004464 transport_controller_->DestroyDtlsTransport(
4465 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4466 // If the channel needs rtcp, it means that the channel used to have a
4467 // rtcp transport which needs to be deleted now.
4468 if (need_rtcp) {
4469 transport_controller_->DestroyDtlsTransport(
4470 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4471 }
Steve Anton75737c02017-11-06 10:37:17 -08004472 };
4473
Steve Antoned10bd92017-12-05 10:52:59 -08004474 for (auto transceiver : transceivers_) {
4475 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08004476 }
Steve Antoned10bd92017-12-05 10:52:59 -08004477 maybe_set_transport(rtp_data_channel_);
4478
Steve Anton75737c02017-11-06 10:37:17 -08004479 // For SCTP, transport creation/deletion happens here instead of in the
4480 // object itself.
4481 if (sctp_transport_) {
4482 RTC_DCHECK(sctp_transport_name_);
4483 RTC_DCHECK(sctp_content_name_);
4484 if (transport_name != *sctp_transport_name_ &&
4485 bundle.HasContentName(*sctp_content_name_)) {
4486 network_thread()->Invoke<void>(
4487 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
4488 transport_name));
4489 }
4490 }
4491
4492 return true;
4493}
4494
Steve Anton75737c02017-11-06 10:37:17 -08004495cricket::IceConfig PeerConnection::ParseIceConfig(
4496 const PeerConnectionInterface::RTCConfiguration& config) const {
4497 cricket::ContinualGatheringPolicy gathering_policy;
4498 // TODO(honghaiz): Add the third continual gathering policy in
4499 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4500 switch (config.continual_gathering_policy) {
4501 case PeerConnectionInterface::GATHER_ONCE:
4502 gathering_policy = cricket::GATHER_ONCE;
4503 break;
4504 case PeerConnectionInterface::GATHER_CONTINUALLY:
4505 gathering_policy = cricket::GATHER_CONTINUALLY;
4506 break;
4507 default:
4508 RTC_NOTREACHED();
4509 gathering_policy = cricket::GATHER_ONCE;
4510 }
4511 cricket::IceConfig ice_config;
4512 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
4513 ice_config.prioritize_most_likely_candidate_pairs =
4514 config.prioritize_most_likely_ice_candidate_pairs;
4515 ice_config.backup_connection_ping_interval =
4516 config.ice_backup_candidate_pair_ping_interval;
4517 ice_config.continual_gathering_policy = gathering_policy;
4518 ice_config.presume_writable_when_fully_relayed =
4519 config.presume_writable_when_fully_relayed;
4520 ice_config.ice_check_min_interval = config.ice_check_min_interval;
4521 ice_config.regather_all_networks_interval_range =
4522 config.ice_regather_interval_range;
4523 return ice_config;
4524}
4525
Steve Anton75737c02017-11-06 10:37:17 -08004526bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4527 std::string* track_id) {
4528 if (!local_description()) {
4529 return false;
4530 }
4531 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4532 track_id);
4533}
4534
4535bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4536 std::string* track_id) {
4537 if (!remote_description()) {
4538 return false;
4539 }
4540 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4541 track_id);
4542}
4543
4544bool PeerConnection::SendData(const cricket::SendDataParams& params,
4545 const rtc::CopyOnWriteBuffer& payload,
4546 cricket::SendDataResult* result) {
4547 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004548 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
4549 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004550 return false;
4551 }
4552 return rtp_data_channel_
4553 ? rtp_data_channel_->SendData(params, payload, result)
4554 : network_thread()->Invoke<bool>(
4555 RTC_FROM_HERE,
4556 Bind(&cricket::SctpTransportInternal::SendData,
4557 sctp_transport_.get(), params, payload, result));
4558}
4559
4560bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
4561 if (!rtp_data_channel_ && !sctp_transport_) {
4562 // Don't log an error here, because DataChannels are expected to call
4563 // ConnectDataChannel in this state. It's the only way to initially tell
4564 // whether or not the underlying transport is ready.
4565 return false;
4566 }
4567 if (rtp_data_channel_) {
4568 rtp_data_channel_->SignalReadyToSendData.connect(
4569 webrtc_data_channel, &DataChannel::OnChannelReady);
4570 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
4571 &DataChannel::OnDataReceived);
4572 } else {
4573 SignalSctpReadyToSendData.connect(webrtc_data_channel,
4574 &DataChannel::OnChannelReady);
4575 SignalSctpDataReceived.connect(webrtc_data_channel,
4576 &DataChannel::OnDataReceived);
4577 SignalSctpStreamClosedRemotely.connect(
4578 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
4579 }
4580 return true;
4581}
4582
4583void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
4584 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004585 RTC_LOG(LS_ERROR)
4586 << "DisconnectDataChannel called when rtp_data_channel_ and "
4587 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004588 return;
4589 }
4590 if (rtp_data_channel_) {
4591 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
4592 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
4593 } else {
4594 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
4595 SignalSctpDataReceived.disconnect(webrtc_data_channel);
4596 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
4597 }
4598}
4599
4600void PeerConnection::AddSctpDataStream(int sid) {
4601 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004602 RTC_LOG(LS_ERROR)
4603 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004604 return;
4605 }
4606 network_thread()->Invoke<void>(
4607 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
4608 sctp_transport_.get(), sid));
4609}
4610
4611void PeerConnection::RemoveSctpDataStream(int sid) {
4612 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004613 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
4614 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08004615 return;
4616 }
4617 network_thread()->Invoke<void>(
4618 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
4619 sctp_transport_.get(), sid));
4620}
4621
4622bool PeerConnection::ReadyToSendData() const {
4623 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
4624 sctp_ready_to_send_data_;
4625}
4626
4627std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
4628 RTC_DCHECK(signaling_thread()->IsCurrent());
4629 ChannelNamePairs channel_name_pairs;
4630 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004631 channel_name_pairs.voice = ChannelNamePair(
4632 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004633 }
4634 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004635 channel_name_pairs.video = ChannelNamePair(
4636 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004637 }
4638 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004639 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08004640 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004641 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08004642 }
4643 if (sctp_transport_) {
4644 RTC_DCHECK(sctp_content_name_);
4645 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004646 channel_name_pairs.data =
4647 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08004648 }
4649 return GetSessionStats(channel_name_pairs);
4650}
4651
4652std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
4653 const ChannelNamePairs& channel_name_pairs) {
4654 if (network_thread()->IsCurrent()) {
4655 return GetSessionStats_n(channel_name_pairs);
4656 }
4657 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
4658 RTC_FROM_HERE,
4659 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
4660}
4661
4662bool PeerConnection::GetLocalCertificate(
4663 const std::string& transport_name,
4664 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
4665 return transport_controller_->GetLocalCertificate(transport_name,
4666 certificate);
4667}
4668
4669std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
4670 const std::string& transport_name) {
4671 return transport_controller_->GetRemoteSSLCertificate(transport_name);
4672}
4673
4674cricket::DataChannelType PeerConnection::data_channel_type() const {
4675 return data_channel_type_;
4676}
4677
4678bool PeerConnection::IceRestartPending(const std::string& content_name) const {
4679 return pending_ice_restarts_.find(content_name) !=
4680 pending_ice_restarts_.end();
4681}
4682
Steve Anton75737c02017-11-06 10:37:17 -08004683bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
4684 return transport_controller_->NeedsIceRestart(content_name);
4685}
4686
4687void PeerConnection::OnCertificateReady(
4688 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
4689 transport_controller_->SetLocalCertificate(certificate);
4690}
4691
4692void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08004693 SetSessionError(SessionError::kTransport,
4694 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08004695}
4696
4697void PeerConnection::OnTransportControllerConnectionState(
4698 cricket::IceConnectionState state) {
4699 switch (state) {
4700 case cricket::kIceConnectionConnecting:
4701 // If the current state is Connected or Completed, then there were
4702 // writable channels but now there are not, so the next state must
4703 // be Disconnected.
4704 // kIceConnectionConnecting is currently used as the default,
4705 // un-connected state by the TransportController, so its only use is
4706 // detecting disconnections.
4707 if (ice_connection_state_ ==
4708 PeerConnectionInterface::kIceConnectionConnected ||
4709 ice_connection_state_ ==
4710 PeerConnectionInterface::kIceConnectionCompleted) {
4711 SetIceConnectionState(
4712 PeerConnectionInterface::kIceConnectionDisconnected);
4713 }
4714 break;
4715 case cricket::kIceConnectionFailed:
4716 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
4717 break;
4718 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004719 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
4720 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08004721 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4722 break;
4723 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01004724 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
4725 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08004726 if (ice_connection_state_ !=
4727 PeerConnectionInterface::kIceConnectionConnected) {
4728 // If jumping directly from "checking" to "connected",
4729 // signal "connected" first.
4730 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4731 }
4732 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4733 if (metrics_observer()) {
4734 ReportTransportStats();
4735 }
4736 break;
4737 default:
4738 RTC_NOTREACHED();
4739 }
4740}
4741
4742void PeerConnection::OnTransportControllerCandidatesGathered(
4743 const std::string& transport_name,
4744 const cricket::Candidates& candidates) {
4745 RTC_DCHECK(signaling_thread()->IsCurrent());
4746 int sdp_mline_index;
4747 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004748 RTC_LOG(LS_ERROR)
4749 << "OnTransportControllerCandidatesGathered: content name "
4750 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004751 return;
4752 }
4753
4754 for (cricket::Candidates::const_iterator citer = candidates.begin();
4755 citer != candidates.end(); ++citer) {
4756 // Use transport_name as the candidate media id.
4757 std::unique_ptr<JsepIceCandidate> candidate(
4758 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4759 if (local_description()) {
4760 mutable_local_description()->AddCandidate(candidate.get());
4761 }
4762 OnIceCandidate(std::move(candidate));
4763 }
4764}
4765
4766void PeerConnection::OnTransportControllerCandidatesRemoved(
4767 const std::vector<cricket::Candidate>& candidates) {
4768 RTC_DCHECK(signaling_thread()->IsCurrent());
4769 // Sanity check.
4770 for (const cricket::Candidate& candidate : candidates) {
4771 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004772 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4773 << "empty content name in candidate "
4774 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004775 return;
4776 }
4777 }
4778
4779 if (local_description()) {
4780 mutable_local_description()->RemoveCandidates(candidates);
4781 }
4782 OnIceCandidatesRemoved(candidates);
4783}
4784
4785void PeerConnection::OnTransportControllerDtlsHandshakeError(
4786 rtc::SSLHandshakeError error) {
4787 if (metrics_observer()) {
4788 metrics_observer()->IncrementEnumCounter(
4789 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4790 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4791 }
4792}
4793
Steve Antoned10bd92017-12-05 10:52:59 -08004794void PeerConnection::EnableSending() {
4795 for (auto transceiver : transceivers_) {
4796 cricket::BaseChannel* channel = transceiver->internal()->channel();
4797 if (channel && !channel->enabled()) {
4798 channel->Enable(true);
4799 }
Steve Anton75737c02017-11-06 10:37:17 -08004800 }
4801
Steve Anton4171afb2017-11-20 10:20:22 -08004802 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004803 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004804 }
Steve Anton75737c02017-11-06 10:37:17 -08004805}
4806
4807// Returns the media index for a local ice candidate given the content name.
4808bool PeerConnection::GetLocalCandidateMediaIndex(
4809 const std::string& content_name,
4810 int* sdp_mline_index) {
4811 if (!local_description() || !sdp_mline_index) {
4812 return false;
4813 }
4814
4815 bool content_found = false;
4816 const ContentInfos& contents = local_description()->description()->contents();
4817 for (size_t index = 0; index < contents.size(); ++index) {
4818 if (contents[index].name == content_name) {
4819 *sdp_mline_index = static_cast<int>(index);
4820 content_found = true;
4821 break;
4822 }
4823 }
4824 return content_found;
4825}
4826
4827bool PeerConnection::UseCandidatesInSessionDescription(
4828 const SessionDescriptionInterface* remote_desc) {
4829 if (!remote_desc) {
4830 return true;
4831 }
4832 bool ret = true;
4833
4834 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4835 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4836 for (size_t n = 0; n < candidates->count(); ++n) {
4837 const IceCandidateInterface* candidate = candidates->at(n);
4838 bool valid = false;
4839 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4840 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004841 RTC_LOG(LS_INFO)
4842 << "UseCandidatesInSessionDescription: Not ready to use "
4843 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004844 }
4845 continue;
4846 }
4847 ret = UseCandidate(candidate);
4848 if (!ret) {
4849 break;
4850 }
4851 }
4852 }
4853 return ret;
4854}
4855
4856bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4857 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4858 size_t remote_content_size =
4859 remote_description()->description()->contents().size();
4860 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004861 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004862 return false;
4863 }
4864
4865 cricket::ContentInfo content =
4866 remote_description()->description()->contents()[mediacontent_index];
4867 std::vector<cricket::Candidate> candidates;
4868 candidates.push_back(candidate->candidate());
4869 // Invoking BaseSession method to handle remote candidates.
4870 std::string error;
4871 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4872 &error)) {
4873 // Candidates successfully submitted for checking.
4874 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4875 ice_connection_state_ ==
4876 PeerConnectionInterface::kIceConnectionDisconnected) {
4877 // If state is New, then the session has just gotten its first remote ICE
4878 // candidates, so go to Checking.
4879 // If state is Disconnected, the session is re-using old candidates or
4880 // receiving additional ones, so go to Checking.
4881 // If state is Connected, stay Connected.
4882 // TODO(bemasc): If state is Connected, and the new candidates are for a
4883 // newly added transport, then the state actually _should_ move to
4884 // checking. Add a way to distinguish that case.
4885 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4886 }
4887 // TODO(bemasc): If state is Completed, go back to Connected.
4888 } else {
4889 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004890 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004891 }
4892 }
4893 return true;
4894}
4895
4896void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004897 // Destroy video channel first since it may have a pointer to the
4898 // voice channel.
4899 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004900 if (!video_info || video_info->rejected) {
4901 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004902 }
4903
Steve Anton6fec8802017-12-04 10:37:29 -08004904 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4905 if (!audio_info || audio_info->rejected) {
4906 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004907 }
4908
4909 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4910 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004911 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004912 }
4913}
4914
Steve Antoneda6ccd2017-12-04 10:21:55 -08004915std::string PeerConnection::GetTransportNameForMediaSection(
4916 const std::string& mid,
4917 const cricket::ContentGroup* bundle_group) const {
4918 if (!bundle_group) {
4919 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004920 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004921 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004922 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004923 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004924 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004925 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004926 if (!bundle_group->HasContentName(mid)) {
4927 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4928 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004929 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004930 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4931 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004932}
4933
Steve Antondcc3c022017-12-22 16:02:54 -08004934RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
4935 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08004936 const cricket::ContentGroup* bundle_group = nullptr;
4937 if (configuration_.bundle_policy ==
4938 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08004939 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08004940 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004941 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4942 "max-bundle configured but session description "
4943 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004944 }
4945 }
Steve Antondcc3c022017-12-22 16:02:54 -08004946 return std::move(bundle_group);
4947}
4948
4949RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
4950 auto bundle_group_or_error = GetEarlyBundleGroup(desc);
4951 if (!bundle_group_or_error.ok()) {
4952 return bundle_group_or_error.MoveError();
4953 }
4954 const cricket::ContentGroup* bundle_group = bundle_group_or_error.MoveValue();
Steve Anton75737c02017-11-06 10:37:17 -08004955
Steve Antoneda6ccd2017-12-04 10:21:55 -08004956 // Creating the media channels and transport proxies.
Steve Antondcc3c022017-12-22 16:02:54 -08004957 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004958 if (voice && !voice->rejected &&
4959 !GetAudioTransceiver()->internal()->channel()) {
4960 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4961 voice->name,
4962 GetTransportNameForMediaSection(voice->name, bundle_group));
4963 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004964 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4965 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004966 }
4967 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4968 }
4969
Steve Antondcc3c022017-12-22 16:02:54 -08004970 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004971 if (video && !video->rejected &&
4972 !GetVideoTransceiver()->internal()->channel()) {
4973 cricket::VideoChannel* video_channel = CreateVideoChannel(
4974 video->name,
4975 GetTransportNameForMediaSection(video->name, bundle_group));
4976 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004977 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4978 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004979 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004980 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004981 }
4982
Steve Antondcc3c022017-12-22 16:02:54 -08004983 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08004984 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4985 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004986 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4987 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004988 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4989 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004990 }
4991 }
4992
Steve Anton8a006912017-12-04 15:25:56 -08004993 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004994}
4995
Steve Anton4171afb2017-11-20 10:20:22 -08004996// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004997cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4998 const std::string& mid,
4999 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005000 cricket::DtlsTransportInternal* rtp_dtls_transport =
5001 transport_controller_->CreateDtlsTransport(
5002 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5003 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5004 if (configuration_.rtcp_mux_policy !=
5005 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5006 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5007 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5008 }
5009
5010 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
5011 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005012 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5013 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005014 if (!voice_channel) {
5015 transport_controller_->DestroyDtlsTransport(
5016 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5017 if (rtcp_dtls_transport) {
5018 transport_controller_->DestroyDtlsTransport(
5019 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5020 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005021 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005022 }
Steve Anton75737c02017-11-06 10:37:17 -08005023 voice_channel->SignalRtcpMuxFullyActive.connect(
5024 this, &PeerConnection::DestroyRtcpTransport_n);
5025 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5026 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005027 voice_channel->SignalSentPacket.connect(this,
5028 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005029
Steve Antoneda6ccd2017-12-04 10:21:55 -08005030 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005031}
5032
Steve Anton4171afb2017-11-20 10:20:22 -08005033// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005034cricket::VideoChannel* PeerConnection::CreateVideoChannel(
5035 const std::string& mid,
5036 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005037 cricket::DtlsTransportInternal* rtp_dtls_transport =
5038 transport_controller_->CreateDtlsTransport(
5039 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5040 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5041 if (configuration_.rtcp_mux_policy !=
5042 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5043 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5044 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5045 }
5046
5047 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
5048 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005049 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
5050 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005051
5052 if (!video_channel) {
5053 transport_controller_->DestroyDtlsTransport(
5054 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5055 if (rtcp_dtls_transport) {
5056 transport_controller_->DestroyDtlsTransport(
5057 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5058 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005059 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005060 }
Steve Anton75737c02017-11-06 10:37:17 -08005061 video_channel->SignalRtcpMuxFullyActive.connect(
5062 this, &PeerConnection::DestroyRtcpTransport_n);
5063 video_channel->SignalDtlsSrtpSetupFailure.connect(
5064 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005065 video_channel->SignalSentPacket.connect(this,
5066 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08005067
Steve Antoneda6ccd2017-12-04 10:21:55 -08005068 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005069}
5070
Steve Antoneda6ccd2017-12-04 10:21:55 -08005071bool PeerConnection::CreateDataChannel(const std::string& mid,
5072 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08005073 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5074 if (sctp) {
5075 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005076 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005077 << "Trying to create SCTP transport, but didn't compile with "
5078 "SCTP support (HAVE_SCTP)";
5079 return false;
5080 }
5081 if (!network_thread()->Invoke<bool>(
5082 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005083 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08005084 return false;
5085 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005086 for (const auto& channel : sctp_data_channels_) {
5087 channel->OnTransportChannelCreated();
5088 }
Steve Anton75737c02017-11-06 10:37:17 -08005089 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005090 cricket::DtlsTransportInternal* rtp_dtls_transport =
5091 transport_controller_->CreateDtlsTransport(
5092 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5093 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
5094 if (configuration_.rtcp_mux_policy !=
5095 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
5096 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
5097 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5098 }
5099
5100 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5101 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08005102 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08005103
5104 if (!rtp_data_channel_) {
5105 transport_controller_->DestroyDtlsTransport(
5106 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5107 if (rtcp_dtls_transport) {
5108 transport_controller_->DestroyDtlsTransport(
5109 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5110 }
5111 return false;
5112 }
5113
5114 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
5115 this, &PeerConnection::DestroyRtcpTransport_n);
5116 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5117 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5118 rtp_data_channel_->SignalSentPacket.connect(
5119 this, &PeerConnection::OnSentPacket_w);
5120 }
5121
Steve Anton75737c02017-11-06 10:37:17 -08005122 return true;
5123}
5124
5125Call::Stats PeerConnection::GetCallStats() {
5126 if (!worker_thread()->IsCurrent()) {
5127 return worker_thread()->Invoke<Call::Stats>(
5128 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5129 }
5130 if (call_) {
5131 return call_->GetStats();
5132 } else {
5133 return Call::Stats();
5134 }
5135}
5136
5137std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
5138 const ChannelNamePairs& channel_name_pairs) {
5139 RTC_DCHECK(network_thread()->IsCurrent());
5140 std::unique_ptr<SessionStats> session_stats(new SessionStats());
5141 for (const auto channel_name_pair :
5142 {&channel_name_pairs.voice, &channel_name_pairs.video,
5143 &channel_name_pairs.data}) {
5144 if (*channel_name_pair) {
5145 cricket::TransportStats transport_stats;
5146 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
5147 &transport_stats)) {
5148 return nullptr;
5149 }
Steve Anton75737c02017-11-06 10:37:17 -08005150 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
5151 std::move(transport_stats);
5152 }
5153 }
5154 return session_stats;
5155}
5156
5157bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
5158 const std::string& transport_name) {
5159 RTC_DCHECK(network_thread()->IsCurrent());
5160 RTC_DCHECK(sctp_factory_);
5161 cricket::DtlsTransportInternal* tc =
5162 transport_controller_->CreateDtlsTransport_n(
5163 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5164 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
5165 RTC_DCHECK(sctp_transport_);
5166 sctp_invoker_.reset(new rtc::AsyncInvoker());
5167 sctp_transport_->SignalReadyToSendData.connect(
5168 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5169 sctp_transport_->SignalDataReceived.connect(
5170 this, &PeerConnection::OnSctpTransportDataReceived_n);
5171 sctp_transport_->SignalStreamClosedRemotely.connect(
5172 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005173 sctp_transport_name_ = transport_name;
5174 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08005175 return true;
5176}
5177
5178void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
5179 RTC_DCHECK(network_thread()->IsCurrent());
5180 RTC_DCHECK(sctp_transport_);
5181 RTC_DCHECK(sctp_transport_name_);
5182 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01005183 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005184 cricket::DtlsTransportInternal* tc =
5185 transport_controller_->CreateDtlsTransport_n(
5186 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5187 sctp_transport_->SetTransportChannel(tc);
5188 transport_controller_->DestroyDtlsTransport_n(
5189 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5190}
5191
5192void PeerConnection::DestroySctpTransport_n() {
5193 RTC_DCHECK(network_thread()->IsCurrent());
5194 sctp_transport_.reset(nullptr);
Taylor Brandstetter389a97c2018-01-03 16:26:06 -08005195 transport_controller_->DestroyDtlsTransport_n(
5196 *sctp_transport_name_, cricket::ICE_CANDIDATE_COMPONENT_RTP);
Steve Anton75737c02017-11-06 10:37:17 -08005197 sctp_content_name_.reset();
5198 sctp_transport_name_.reset();
5199 sctp_invoker_.reset(nullptr);
5200 sctp_ready_to_send_data_ = false;
5201}
5202
5203void PeerConnection::OnSctpTransportReadyToSendData_n() {
5204 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5205 RTC_DCHECK(network_thread()->IsCurrent());
5206 // Note: Cannot use rtc::Bind here because it will grab a reference to
5207 // PeerConnection and potentially cause PeerConnection to live longer than
5208 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5209 // be destroyed before PeerConnection is destroyed, and at that point all
5210 // pending tasks will be cleared.
5211 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5212 OnSctpTransportReadyToSendData_s(true);
5213 });
5214}
5215
5216void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5217 RTC_DCHECK(signaling_thread()->IsCurrent());
5218 sctp_ready_to_send_data_ = ready;
5219 SignalSctpReadyToSendData(ready);
5220}
5221
5222void PeerConnection::OnSctpTransportDataReceived_n(
5223 const cricket::ReceiveDataParams& params,
5224 const rtc::CopyOnWriteBuffer& payload) {
5225 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5226 RTC_DCHECK(network_thread()->IsCurrent());
5227 // Note: Cannot use rtc::Bind here because it will grab a reference to
5228 // PeerConnection and potentially cause PeerConnection to live longer than
5229 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5230 // be destroyed before PeerConnection is destroyed, and at that point all
5231 // pending tasks will be cleared.
5232 sctp_invoker_->AsyncInvoke<void>(
5233 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5234 OnSctpTransportDataReceived_s(params, payload);
5235 });
5236}
5237
5238void PeerConnection::OnSctpTransportDataReceived_s(
5239 const cricket::ReceiveDataParams& params,
5240 const rtc::CopyOnWriteBuffer& payload) {
5241 RTC_DCHECK(signaling_thread()->IsCurrent());
5242 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5243 // Received OPEN message; parse and signal that a new data channel should
5244 // be created.
5245 std::string label;
5246 InternalDataChannelInit config;
5247 config.id = params.ssrc;
5248 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005249 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5250 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005251 return;
5252 }
5253 config.open_handshake_role = InternalDataChannelInit::kAcker;
5254 OnDataChannelOpenMessage(label, config);
5255 } else {
5256 // Otherwise just forward the signal.
5257 SignalSctpDataReceived(params, payload);
5258 }
5259}
5260
5261void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5262 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5263 RTC_DCHECK(network_thread()->IsCurrent());
5264 sctp_invoker_->AsyncInvoke<void>(
5265 RTC_FROM_HERE, signaling_thread(),
5266 rtc::Bind(&sigslot::signal1<int>::operator(),
5267 &SignalSctpStreamClosedRemotely, sid));
5268}
5269
5270// Returns false if bundle is enabled and rtcp_mux is disabled.
5271bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5272 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5273 if (!bundle_enabled)
5274 return true;
5275
5276 const cricket::ContentGroup* bundle_group =
5277 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5278 RTC_DCHECK(bundle_group != NULL);
5279
5280 const cricket::ContentInfos& contents = desc->contents();
5281 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5282 citer != contents.end(); ++citer) {
5283 const cricket::ContentInfo* content = (&*citer);
5284 RTC_DCHECK(content != NULL);
5285 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005286 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005287 if (!HasRtcpMuxEnabled(content))
5288 return false;
5289 }
5290 }
5291 // RTCP-MUX is enabled in all the contents.
5292 return true;
5293}
5294
5295bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005296 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005297}
5298
Steve Anton8a006912017-12-04 15:25:56 -08005299RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005300 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005301 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005302 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005303 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005304 }
5305
5306 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005308 }
5309
Steve Anton3828c062017-12-06 10:34:51 -08005310 SdpType type = sdesc->GetType();
5311 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5312 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005313 LOG_AND_RETURN_ERROR(
5314 RTCErrorType::INVALID_PARAMETER,
5315 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005316 }
5317
5318 // Verify crypto settings.
5319 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005320 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5321 dtls_enabled_) {
5322 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
5323 if (!crypto_error.ok()) {
5324 return crypto_error;
5325 }
Steve Anton75737c02017-11-06 10:37:17 -08005326 }
5327
5328 // Verify ice-ufrag and ice-pwd.
5329 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005330 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5331 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005332 }
5333
5334 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5336 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005337 }
5338
5339 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5340 // m-lines that do not rtcp-mux enabled.
5341
5342 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005343 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08005344 const cricket::SessionDescription* offer_desc =
5345 (source == cricket::CS_LOCAL) ? remote_description()->description()
5346 : local_description()->description();
5347 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
5348 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005349 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5350 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005351 }
5352 } else {
5353 const cricket::SessionDescription* current_desc = nullptr;
5354 if (source == cricket::CS_LOCAL && local_description()) {
5355 current_desc = local_description()->description();
5356 } else if (source == cricket::CS_REMOTE && remote_description()) {
5357 current_desc = remote_description()->description();
5358 }
5359 // The re-offers should respect the order of m= sections in current
5360 // description. See RFC3264 Section 8 paragraph 4 for more details.
5361 if (current_desc &&
5362 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5364 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005365 }
5366 }
5367
Steve Anton02ee47c2018-01-10 16:26:06 -08005368 // Unified Plan SDP should have exactly one stream per m= section for audio
5369 // and video.
5370 if (IsUnifiedPlan()) {
5371 for (const ContentInfo& content : sdesc->description()->contents()) {
5372 if (content.rejected) {
5373 continue;
5374 }
5375 if (content.media_description()) {
5376 cricket::MediaType media_type = content.media_description()->type();
5377 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
5378 media_type == cricket::MEDIA_TYPE_VIDEO)) {
5379 continue;
5380 }
5381 const cricket::StreamParamsVec& streams =
5382 content.media_description()->streams();
5383 if (streams.size() != 1u) {
5384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5385 "Unified Plan SDP should have exactly one "
5386 "track per media section for audio and video.");
5387 }
5388 }
5389 }
5390 }
5391
Steve Anton8a006912017-12-04 15:25:56 -08005392 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005393}
5394
Steve Anton3828c062017-12-06 10:34:51 -08005395bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005396 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005397 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005398 return (state == PeerConnectionInterface::kStable) ||
5399 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005400 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005401 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005402 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5403 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5404 }
5405}
5406
Steve Anton3828c062017-12-06 10:34:51 -08005407bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005408 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005409 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005410 return (state == PeerConnectionInterface::kStable) ||
5411 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005412 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005413 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005414 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5415 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5416 }
5417}
5418
Steve Antonf8470812017-12-04 10:46:21 -08005419const char* PeerConnection::SessionErrorToString(SessionError error) const {
5420 switch (error) {
5421 case SessionError::kNone:
5422 return "ERROR_NONE";
5423 case SessionError::kContent:
5424 return "ERROR_CONTENT";
5425 case SessionError::kTransport:
5426 return "ERROR_TRANSPORT";
5427 }
5428 RTC_NOTREACHED();
5429 return "";
5430}
5431
Steve Anton75737c02017-11-06 10:37:17 -08005432std::string PeerConnection::GetSessionErrorMsg() {
5433 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005434 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5435 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005436 return desc.str();
5437}
5438
5439// We need to check the local/remote description for the Transport instead of
5440// the session, because a new Transport added during renegotiation may have
5441// them unset while the session has them set from the previous negotiation.
5442// Not doing so may trigger the auto generation of transport description and
5443// mess up DTLS identity information, ICE credential, etc.
5444bool PeerConnection::ReadyToUseRemoteCandidate(
5445 const IceCandidateInterface* candidate,
5446 const SessionDescriptionInterface* remote_desc,
5447 bool* valid) {
5448 *valid = true;
5449
5450 const SessionDescriptionInterface* current_remote_desc =
5451 remote_desc ? remote_desc : remote_description();
5452
5453 if (!current_remote_desc) {
5454 return false;
5455 }
5456
5457 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5458 size_t remote_content_size =
5459 current_remote_desc->description()->contents().size();
5460 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005461 RTC_LOG(LS_ERROR)
5462 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5463 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005464
5465 *valid = false;
5466 return false;
5467 }
5468
5469 cricket::ContentInfo content =
5470 current_remote_desc->description()->contents()[mediacontent_index];
5471
5472 const std::string transport_name = GetTransportName(content.name);
5473 if (transport_name.empty()) {
5474 return false;
5475 }
5476 return transport_controller_->ReadyForRemoteCandidates(transport_name);
5477}
5478
5479bool PeerConnection::SrtpRequired() const {
5480 return dtls_enabled_ ||
5481 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5482}
5483
5484void PeerConnection::OnTransportControllerGatheringState(
5485 cricket::IceGatheringState state) {
5486 RTC_DCHECK(signaling_thread()->IsCurrent());
5487 if (state == cricket::kIceGatheringGathering) {
5488 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5489 } else if (state == cricket::kIceGatheringComplete) {
5490 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5491 }
5492}
5493
5494void PeerConnection::ReportTransportStats() {
5495 // Use a set so we don't report the same stats twice if two channels share
5496 // a transport.
5497 std::set<std::string> transport_names;
5498 if (voice_channel()) {
5499 transport_names.insert(voice_channel()->transport_name());
5500 }
5501 if (video_channel()) {
5502 transport_names.insert(video_channel()->transport_name());
5503 }
5504 if (rtp_data_channel()) {
5505 transport_names.insert(rtp_data_channel()->transport_name());
5506 }
5507 if (sctp_transport_name_) {
5508 transport_names.insert(*sctp_transport_name_);
5509 }
5510 for (const auto& name : transport_names) {
5511 cricket::TransportStats stats;
5512 if (transport_controller_->GetStats(name, &stats)) {
5513 ReportBestConnectionState(stats);
5514 ReportNegotiatedCiphers(stats);
5515 }
5516 }
5517}
5518// Walk through the ConnectionInfos to gather best connection usage
5519// for IPv4 and IPv6.
5520void PeerConnection::ReportBestConnectionState(
5521 const cricket::TransportStats& stats) {
5522 RTC_DCHECK(metrics_observer());
5523 for (cricket::TransportChannelStatsList::const_iterator it =
5524 stats.channel_stats.begin();
5525 it != stats.channel_stats.end(); ++it) {
5526 for (cricket::ConnectionInfos::const_iterator it_info =
5527 it->connection_infos.begin();
5528 it_info != it->connection_infos.end(); ++it_info) {
5529 if (!it_info->best_connection) {
5530 continue;
5531 }
5532
5533 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
5534 const cricket::Candidate& local = it_info->local_candidate;
5535 const cricket::Candidate& remote = it_info->remote_candidate;
5536
5537 // Increment the counter for IceCandidatePairType.
5538 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5539 (local.type() == RELAY_PORT_TYPE &&
5540 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5541 type = kEnumCounterIceCandidatePairTypeTcp;
5542 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5543 type = kEnumCounterIceCandidatePairTypeUdp;
5544 } else {
5545 RTC_CHECK(0);
5546 }
5547 metrics_observer()->IncrementEnumCounter(
5548 type, GetIceCandidatePairCounter(local, remote),
5549 kIceCandidatePairMax);
5550
5551 // Increment the counter for IP type.
5552 if (local.address().family() == AF_INET) {
5553 metrics_observer()->IncrementEnumCounter(
5554 kEnumCounterAddressFamily, kBestConnections_IPv4,
5555 kPeerConnectionAddressFamilyCounter_Max);
5556
5557 } else if (local.address().family() == AF_INET6) {
5558 metrics_observer()->IncrementEnumCounter(
5559 kEnumCounterAddressFamily, kBestConnections_IPv6,
5560 kPeerConnectionAddressFamilyCounter_Max);
5561 } else {
5562 RTC_CHECK(0);
5563 }
5564
5565 return;
5566 }
5567 }
5568}
5569
5570void PeerConnection::ReportNegotiatedCiphers(
5571 const cricket::TransportStats& stats) {
5572 RTC_DCHECK(metrics_observer());
5573 if (!dtls_enabled_ || stats.channel_stats.empty()) {
5574 return;
5575 }
5576
5577 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
5578 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
5579 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
5580 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
5581 return;
5582 }
5583
5584 PeerConnectionEnumCounterType srtp_counter_type;
5585 PeerConnectionEnumCounterType ssl_counter_type;
5586 if (stats.transport_name == cricket::CN_AUDIO) {
5587 srtp_counter_type = kEnumCounterAudioSrtpCipher;
5588 ssl_counter_type = kEnumCounterAudioSslCipher;
5589 } else if (stats.transport_name == cricket::CN_VIDEO) {
5590 srtp_counter_type = kEnumCounterVideoSrtpCipher;
5591 ssl_counter_type = kEnumCounterVideoSslCipher;
5592 } else if (stats.transport_name == cricket::CN_DATA) {
5593 srtp_counter_type = kEnumCounterDataSrtpCipher;
5594 ssl_counter_type = kEnumCounterDataSslCipher;
5595 } else {
5596 RTC_NOTREACHED();
5597 return;
5598 }
5599
5600 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
5601 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
5602 srtp_crypto_suite);
5603 }
5604 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
5605 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
5606 ssl_cipher_suite);
5607 }
5608}
5609
5610void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
5611 RTC_DCHECK(worker_thread()->IsCurrent());
5612 RTC_DCHECK(call_);
5613 call_->OnSentPacket(sent_packet);
5614}
5615
5616const std::string PeerConnection::GetTransportName(
5617 const std::string& content_name) {
5618 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08005619 if (channel) {
5620 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005621 }
Steve Anton6fec8802017-12-04 10:37:29 -08005622 if (sctp_transport_) {
5623 RTC_DCHECK(sctp_content_name_);
5624 RTC_DCHECK(sctp_transport_name_);
5625 if (content_name == *sctp_content_name_) {
5626 return *sctp_transport_name_;
5627 }
5628 }
5629 // Return an empty string if failed to retrieve the transport name.
5630 return "";
Steve Anton75737c02017-11-06 10:37:17 -08005631}
5632
5633void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
5634 RTC_DCHECK(network_thread()->IsCurrent());
5635 transport_controller_->DestroyDtlsTransport_n(
5636 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5637}
5638
Steve Anton6fec8802017-12-04 10:37:29 -08005639void PeerConnection::DestroyTransceiverChannel(
5640 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
5641 transceiver) {
5642 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08005643
Steve Anton6fec8802017-12-04 10:37:29 -08005644 cricket::BaseChannel* channel = transceiver->internal()->channel();
5645 if (channel) {
5646 transceiver->internal()->SetChannel(nullptr);
5647 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08005648 }
5649}
5650
5651void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08005652 if (rtp_data_channel_) {
5653 OnDataChannelDestroyed();
5654 DestroyBaseChannel(rtp_data_channel_);
5655 rtp_data_channel_ = nullptr;
5656 }
5657
5658 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
5659 // grab a reference to this PeerConnection. If this is called from the
5660 // PeerConnection destructor, the RefCountedObject vtable will have already
5661 // been destroyed (since it is a subclass of PeerConnection) and using
5662 // rtc::Bind will cause "Pure virtual function called" error to appear.
5663
5664 if (sctp_transport_) {
5665 OnDataChannelDestroyed();
5666 network_thread()->Invoke<void>(RTC_FROM_HERE,
5667 [this] { DestroySctpTransport_n(); });
5668 }
5669}
5670
5671void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
5672 RTC_DCHECK(channel);
5673 RTC_DCHECK(channel->rtp_dtls_transport());
5674
5675 // Need to cache these before destroying the base channel so that we do not
5676 // access uninitialized memory.
5677 const std::string transport_name =
5678 channel->rtp_dtls_transport()->transport_name();
5679 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
5680
5681 switch (channel->media_type()) {
5682 case cricket::MEDIA_TYPE_AUDIO:
5683 channel_manager()->DestroyVoiceChannel(
5684 static_cast<cricket::VoiceChannel*>(channel));
5685 break;
5686 case cricket::MEDIA_TYPE_VIDEO:
5687 channel_manager()->DestroyVideoChannel(
5688 static_cast<cricket::VideoChannel*>(channel));
5689 break;
5690 case cricket::MEDIA_TYPE_DATA:
5691 channel_manager()->DestroyRtpDataChannel(
5692 static_cast<cricket::RtpDataChannel*>(channel));
5693 break;
5694 default:
5695 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
5696 break;
5697 }
5698
5699 // |channel| can no longer be used.
5700
Steve Anton75737c02017-11-06 10:37:17 -08005701 transport_controller_->DestroyDtlsTransport(
5702 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
5703 if (need_to_delete_rtcp) {
5704 transport_controller_->DestroyDtlsTransport(
5705 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
5706 }
5707}
5708
Harald Alvestrand89061872018-01-02 14:08:34 +01005709void PeerConnection::ClearStatsCache() {
5710 if (stats_collector_) {
5711 stats_collector_->ClearCachedStatsReport();
5712 }
5713}
5714
henrike@webrtc.org28e20752013-07-10 00:45:36 +00005715} // namespace webrtc