blob: 90242a87a79ef0b8531534920b1b245bc182eeee [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Antondcc3c022017-12-22 16:02:54 -080014#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080015#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080016#include <utility>
17#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000018
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020019#include "api/jsepicecandidate.h"
20#include "api/jsepsessiondescription.h"
21#include "api/mediaconstraintsinterface.h"
22#include "api/mediastreamproxy.h"
23#include "api/mediastreamtrackproxy.h"
24#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080025#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020026#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "logging/rtc_event_log/rtc_event_log.h"
28#include "media/sctp/sctptransport.h"
29#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080030#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "pc/channelmanager.h"
32#include "pc/dtmfsender.h"
33#include "pc/mediastream.h"
34#include "pc/mediastreamobserver.h"
35#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080036#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/rtpreceiver.h"
38#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080039#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080040#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020041#include "pc/streamcollection.h"
42#include "pc/videocapturertracksource.h"
43#include "pc/videotrack.h"
44#include "rtc_base/bind.h"
45#include "rtc_base/checks.h"
46#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010047#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020048#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
50#include "rtc_base/stringutils.h"
51#include "rtc_base/trace_event.h"
52#include "system_wrappers/include/clock.h"
53#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000054
Steve Anton75737c02017-11-06 10:37:17 -080055using cricket::ContentInfo;
56using cricket::ContentInfos;
57using cricket::MediaContentDescription;
58using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080059using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080060using cricket::TransportInfo;
61
62using cricket::LOCAL_PORT_TYPE;
63using cricket::STUN_PORT_TYPE;
64using cricket::RELAY_PORT_TYPE;
65using cricket::PRFLX_PORT_TYPE;
66
Steve Antonba818672017-11-06 10:21:57 -080067namespace webrtc {
68
Steve Anton75737c02017-11-06 10:37:17 -080069// Error messages
70const char kBundleWithoutRtcpMux[] =
71 "rtcp-mux must be enabled when BUNDLE "
72 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080073const char kInvalidCandidates[] = "Description contains invalid candidates.";
74const char kInvalidSdp[] = "Invalid session description.";
75const char kMlineMismatchInAnswer[] =
76 "The order of m-lines in answer doesn't match order in offer. Rejecting "
77 "answer.";
78const char kMlineMismatchInSubsequentOffer[] =
79 "The order of m-lines in subsequent offer doesn't match order from "
80 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080081const char kSdpWithoutDtlsFingerprint[] =
82 "Called with SDP without DTLS fingerprint.";
83const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
84const char kSdpWithoutIceUfragPwd[] =
85 "Called with SDP without ice-ufrag and ice-pwd.";
86const char kSessionError[] = "Session error code: ";
87const char kSessionErrorDesc[] = "Session error description: ";
88const char kDtlsSrtpSetupFailureRtp[] =
89 "Couldn't set up DTLS-SRTP on RTP channel.";
90const char kDtlsSrtpSetupFailureRtcp[] =
91 "Couldn't set up DTLS-SRTP on RTCP channel.";
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
Seth Hampson845e8782018-03-02 11:34:10 -080095static const char kDefaultStreamId[] = "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;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100117 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118};
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;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100126 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700127};
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 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700144 if (current_streams->find(new_stream->id()) != nullptr) {
145 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100146 << " 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
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800320// Logic to decide if an m= section can be recycled. This means that the new
321// m= section is not rejected, but the old local or remote m= section is
322// rejected. |old_content_one| and |old_content_two| refer to the m= section
323// of the old remote and old local descriptions in no particular order.
324// We need to check both the old local and remote because either
325// could be the most current from the latest negotation.
326bool IsMediaSectionBeingRecycled(SdpType type,
327 const ContentInfo& content,
328 const ContentInfo* old_content_one,
329 const ContentInfo* old_content_two) {
330 return type == SdpType::kOffer && !content.rejected &&
331 ((old_content_one && old_content_one->rejected) ||
332 (old_content_two && old_content_two->rejected));
333}
334
Steve Anton75737c02017-11-06 10:37:17 -0800335// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800336// |current_desc|. The number of m= sections in |new_desc| should be no
337// less than |current_desc|. In the case of checking an answer's
338// |new_desc|, the |current_desc| is the last offer that was set as the
339// local or remote. In the case of checking an offer's |new_desc| we
340// check against the local and remote descriptions stored from the last
341// negotiation, because either of these could be the most up to date for
342// possible rejected m sections. These are the |current_desc| and
343// |secondary_current_desc|.
344bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
345 const SessionDescription* secondary_current_desc,
346 const SessionDescription& new_desc,
347 const SdpType type) {
348 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800349 return false;
350 }
351
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800352 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
353 const cricket::ContentInfo* secondary_content_info = nullptr;
354 if (secondary_current_desc &&
355 i < secondary_current_desc->contents().size()) {
356 secondary_content_info = &secondary_current_desc->contents()[i];
357 }
358 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
359 &current_desc.contents()[i],
360 secondary_content_info)) {
361 // For new offer descriptions, if the media section can be recycled, it's
362 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800363 continue;
364 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800365 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800366 return false;
367 }
368 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800369 new_desc.contents()[i].media_description();
370 const MediaContentDescription* current_desc_mdesc =
371 current_desc.contents()[i].media_description();
372 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 }
376 return true;
377}
378
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800379bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
380 const SessionDescription& desc2) {
381 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800382}
383
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100384void NoteKeyProtocolAndMedia(
385 KeyExchangeProtocolType protocol_type,
386 cricket::MediaType media_type,
387 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
388 if (!uma_observer)
389 return;
390 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
391 protocol_type,
392 webrtc::kEnumCounterKeyProtocolMax);
393 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
394 KeyExchangeProtocolMedia>
395 proto_media_counter_map = {
396 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
397 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
398 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
399 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
400 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
401 kEnumCounterKeyProtocolMediaTypeDtlsData},
402 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
403 kEnumCounterKeyProtocolMediaTypeSdesAudio},
404 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
405 kEnumCounterKeyProtocolMediaTypeSdesVideo},
406 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
407 kEnumCounterKeyProtocolMediaTypeSdesData}};
408
409 auto it = proto_media_counter_map.find({protocol_type, media_type});
410 if (it != proto_media_counter_map.end()) {
411 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
412 it->second,
413 kEnumCounterKeyProtocolMediaTypeMax);
414 }
415}
416
Steve Anton75737c02017-11-06 10:37:17 -0800417// Checks that each non-rejected content has SDES crypto keys or a DTLS
418// fingerprint, unless it's in a BUNDLE group, in which case only the
419// BUNDLE-tag section (first media section/description in the BUNDLE group)
420// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
421// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
422// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100423RTCError VerifyCrypto(const SessionDescription* desc,
424 bool dtls_enabled,
425 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800426 const cricket::ContentGroup* bundle =
427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800428 for (const cricket::ContentInfo& content_info : desc->contents()) {
429 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800430 continue;
431 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100432 // Note what media is used with each crypto protocol, for all sections.
433 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
434 : webrtc::kEnumCounterKeyProtocolSdes,
435 content_info.media_description()->type(),
436 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800437 const std::string& mid = content_info.name;
438 if (bundle && bundle->HasContentName(mid) &&
439 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800440 // This isn't the first media section in the BUNDLE group, so it's not
441 // required to have crypto attributes, since only the crypto attributes
442 // from the first section actually get used.
443 continue;
444 }
445
446 // If the content isn't rejected or bundled into another m= section, crypto
447 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800448 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800449 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800450 if (!media || !tinfo) {
451 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800452 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800453 }
454 if (dtls_enabled) {
455 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100456 RTC_LOG(LS_WARNING)
457 << "Session description must have DTLS fingerprint if "
458 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800459 return RTCError(RTCErrorType::INVALID_PARAMETER,
460 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800461 }
462 } else {
463 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100464 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800465 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800466 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800467 }
468 }
469 }
Steve Anton8a006912017-12-04 15:25:56 -0800470 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800471}
472
473// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
474// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
475// media section/description in the BUNDLE group) needs a ufrag and pwd.
476bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
477 const cricket::ContentGroup* bundle =
478 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800479 for (const cricket::ContentInfo& content_info : desc->contents()) {
480 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800481 continue;
482 }
Steve Anton8a006912017-12-04 15:25:56 -0800483 const std::string& mid = content_info.name;
484 if (bundle && bundle->HasContentName(mid) &&
485 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800486 // This isn't the first media section in the BUNDLE group, so it's not
487 // required to have ufrag/password, since only the ufrag/password from
488 // the first section actually get used.
489 continue;
490 }
491
492 // If the content isn't rejected or bundled into another m= section,
493 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800494 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800495 if (!tinfo) {
496 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100497 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800498 return false;
499 }
500 if (tinfo->description.ice_ufrag.empty() ||
501 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100502 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800503 return false;
504 }
505 }
506 return true;
507}
508
509bool GetTrackIdBySsrc(const SessionDescription* session_description,
510 uint32_t ssrc,
511 std::string* track_id) {
512 RTC_DCHECK(track_id != NULL);
513
Steve Antonb1c1de12017-12-21 15:14:30 -0800514 const cricket::AudioContentDescription* audio_desc =
515 cricket::GetFirstAudioContentDescription(session_description);
516 if (audio_desc) {
517 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800518 if (found) {
519 *track_id = found->id;
520 return true;
521 }
522 }
523
Steve Antonb1c1de12017-12-21 15:14:30 -0800524 const cricket::VideoContentDescription* video_desc =
525 cricket::GetFirstVideoContentDescription(session_description);
526 if (video_desc) {
527 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800528 if (found) {
529 *track_id = found->id;
530 return true;
531 }
532 }
533 return false;
534}
535
536// Get the SCTP port out of a SessionDescription.
537// Return -1 if not found.
538int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800539 const cricket::DataContentDescription* data_desc =
540 GetFirstDataContentDescription(session_description);
541 RTC_DCHECK(data_desc);
542 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800543 return -1;
544 }
Steve Anton75737c02017-11-06 10:37:17 -0800545 std::string value;
546 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
547 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800548 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800549 if (!codec.Matches(match_pattern)) {
550 continue;
551 }
552 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
553 return rtc::FromString<int>(value);
554 }
555 }
556 return -1;
557}
558
Steve Anton75737c02017-11-06 10:37:17 -0800559// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
560bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
561 const SessionDescriptionInterface* new_desc,
562 const std::string& content_name) {
563 if (!old_desc) {
564 return false;
565 }
566 const SessionDescription* new_sd = new_desc->description();
567 const SessionDescription* old_sd = old_desc->description();
568 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
569 if (!cinfo || cinfo->rejected) {
570 return false;
571 }
572 // If the content isn't rejected, check if ufrag and password has changed.
573 const cricket::TransportDescription* new_transport_desc =
574 new_sd->GetTransportDescriptionByName(content_name);
575 const cricket::TransportDescription* old_transport_desc =
576 old_sd->GetTransportDescriptionByName(content_name);
577 if (!new_transport_desc || !old_transport_desc) {
578 // No transport description exists. This is not an ICE restart.
579 return false;
580 }
581 if (cricket::IceCredentialsChanged(
582 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
583 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100584 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
585 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800586 return true;
587 }
588 return false;
589}
590
Steve Anton80dd7b52018-02-16 17:08:42 -0800591// Generates a string error message for SetLocalDescription/SetRemoteDescription
592// from an RTCError.
593std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
594 SdpType type,
595 const RTCError& error) {
596 std::ostringstream oss;
597 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
598 << " " << SdpTypeToString(type) << " sdp: " << error.message();
599 return oss.str();
600}
601
Seth Hampson5b4f0752018-04-02 16:31:36 -0700602std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
603 std::string output = "streams=[";
604 const char* separator = "";
605 for (const auto& stream_id : stream_ids) {
606 output.append(separator).append(stream_id);
607 separator = ", ";
608 }
609 output.append("]");
610 return output;
611}
612
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
614 int rtc_configuration_parameter) {
615 if (rtc_configuration_parameter ==
616 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
617 return rtc::nullopt;
618 }
619 return rtc_configuration_parameter;
620}
621
Steve Anton75737c02017-11-06 10:37:17 -0800622} // namespace
623
Henrik Boström31638672017-11-23 17:48:32 +0100624// Upon completion, posts a task to execute the callback of the
625// SetSessionDescriptionObserver asynchronously on the same thread. At this
626// point, the state of the peer connection might no longer reflect the effects
627// of the SetRemoteDescription operation, as the peer connection could have been
628// modified during the post.
629// TODO(hbos): Remove this class once we remove the version of
630// PeerConnectionInterface::SetRemoteDescription() that takes a
631// SetSessionDescriptionObserver as an argument.
632class PeerConnection::SetRemoteDescriptionObserverAdapter
633 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
634 public:
635 SetRemoteDescriptionObserverAdapter(
636 rtc::scoped_refptr<PeerConnection> pc,
637 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
638 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
639
640 // SetRemoteDescriptionObserverInterface implementation.
641 void OnSetRemoteDescriptionComplete(RTCError error) override {
642 if (error.ok())
643 pc_->PostSetSessionDescriptionSuccess(wrapper_);
644 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100645 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100646 }
647
648 private:
649 rtc::scoped_refptr<PeerConnection> pc_;
650 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
651};
652
deadbeef293e9262017-01-11 12:28:30 -0800653bool PeerConnectionInterface::RTCConfiguration::operator==(
654 const PeerConnectionInterface::RTCConfiguration& o) const {
655 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700656 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800657 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000658 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700659 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800660 BundlePolicy bundle_policy;
661 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700662 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
663 int ice_candidate_pool_size;
664 bool disable_ipv6;
665 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700666 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100667 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700668 bool enable_rtp_data_channel;
669 rtc::Optional<int> screencast_min_bitrate;
670 rtc::Optional<bool> combined_audio_video_bwe;
671 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800672 TcpCandidatePolicy tcp_candidate_policy;
673 CandidateNetworkPolicy candidate_network_policy;
674 int audio_jitter_buffer_max_packets;
675 bool audio_jitter_buffer_fast_accelerate;
676 int ice_connection_receiving_timeout;
677 int ice_backup_candidate_pair_ping_interval;
678 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800679 bool prioritize_most_likely_ice_candidate_pairs;
680 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800681 bool prune_turn_ports;
682 bool presume_writable_when_fully_relayed;
683 bool enable_ice_renomination;
684 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800685 rtc::Optional<int> ice_check_interval_strong_connectivity;
686 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800687 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700688 rtc::Optional<int> ice_unwritable_timeout;
689 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800690 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700691 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200692 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800693 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800694 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800695 };
696 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
697 "Did you add something to RTCConfiguration and forget to "
698 "update operator==?");
699 return type == o.type && servers == o.servers &&
700 bundle_policy == o.bundle_policy &&
701 rtcp_mux_policy == o.rtcp_mux_policy &&
702 tcp_candidate_policy == o.tcp_candidate_policy &&
703 candidate_network_policy == o.candidate_network_policy &&
704 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
705 audio_jitter_buffer_fast_accelerate ==
706 o.audio_jitter_buffer_fast_accelerate &&
707 ice_connection_receiving_timeout ==
708 o.ice_connection_receiving_timeout &&
709 ice_backup_candidate_pair_ping_interval ==
710 o.ice_backup_candidate_pair_ping_interval &&
711 continual_gathering_policy == o.continual_gathering_policy &&
712 certificates == o.certificates &&
713 prioritize_most_likely_ice_candidate_pairs ==
714 o.prioritize_most_likely_ice_candidate_pairs &&
715 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800716 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700717 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100718 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800719 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800720 screencast_min_bitrate == o.screencast_min_bitrate &&
721 combined_audio_video_bwe == o.combined_audio_video_bwe &&
722 enable_dtls_srtp == o.enable_dtls_srtp &&
723 ice_candidate_pool_size == o.ice_candidate_pool_size &&
724 prune_turn_ports == o.prune_turn_ports &&
725 presume_writable_when_fully_relayed ==
726 o.presume_writable_when_fully_relayed &&
727 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800728 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800729 ice_check_interval_strong_connectivity ==
730 o.ice_check_interval_strong_connectivity &&
731 ice_check_interval_weak_connectivity ==
732 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700734 ice_unwritable_timeout == o.ice_unwritable_timeout &&
735 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800736 stun_candidate_keepalive_interval ==
737 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200738 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800739 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800740 sdp_semantics == o.sdp_semantics &&
741 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800742}
743
744bool PeerConnectionInterface::RTCConfiguration::operator!=(
745 const PeerConnectionInterface::RTCConfiguration& o) const {
746 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800747}
748
zhihuang8f65cdf2016-05-06 18:40:30 -0700749// Generate a RTCP CNAME when a PeerConnection is created.
750std::string GenerateRtcpCname() {
751 std::string cname;
752 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100753 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800754 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700755 }
756 return cname;
757}
758
zhihuang1c378ed2017-08-17 14:10:50 -0700759bool ValidateOfferAnswerOptions(
760 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
761 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
762 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700763}
764
zhihuang1c378ed2017-08-17 14:10:50 -0700765// From |rtc_options|, fill parts of |session_options| shared by all generated
766// m= sections (in other words, nothing that involves a map/array).
767void ExtractSharedMediaSessionOptions(
768 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
769 cricket::MediaSessionOptions* session_options) {
770 session_options->vad_enabled = rtc_options.voice_activity_detection;
771 session_options->bundle_enabled = rtc_options.use_rtp_mux;
772}
zhihuanga77e6bb2017-08-14 18:17:48 -0700773
zhihuang1c378ed2017-08-17 14:10:50 -0700774bool ConvertConstraintsToOfferAnswerOptions(
775 const MediaConstraintsInterface* constraints,
776 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700777 if (!constraints) {
778 return true;
779 }
zhihuang1c378ed2017-08-17 14:10:50 -0700780
781 bool value = false;
782 size_t mandatory_constraints_satisfied = 0;
783
784 if (FindConstraint(constraints,
785 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
786 &mandatory_constraints_satisfied)) {
787 offer_answer_options->offer_to_receive_audio =
788 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
789 kOfferToReceiveMediaTrue
790 : 0;
791 }
792
793 if (FindConstraint(constraints,
794 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
795 &mandatory_constraints_satisfied)) {
796 offer_answer_options->offer_to_receive_video =
797 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
798 kOfferToReceiveMediaTrue
799 : 0;
800 }
801 if (FindConstraint(constraints,
802 MediaConstraintsInterface::kVoiceActivityDetection, &value,
803 &mandatory_constraints_satisfied)) {
804 offer_answer_options->voice_activity_detection = value;
805 }
806 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
807 &mandatory_constraints_satisfied)) {
808 offer_answer_options->use_rtp_mux = value;
809 }
810 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
811 &value, &mandatory_constraints_satisfied)) {
812 offer_answer_options->ice_restart = value;
813 }
814
deadbeefab9b2d12015-10-14 11:33:11 -0700815 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
816}
817
zhihuang38ede132017-06-15 12:52:32 -0700818PeerConnection::PeerConnection(PeerConnectionFactory* factory,
819 std::unique_ptr<RtcEventLog> event_log,
820 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700822 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700823 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700824 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700825 remote_streams_(StreamCollection::Create()),
826 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827
828PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100829 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800830 RTC_DCHECK_RUN_ON(signaling_thread());
831
Steve Anton8af21862017-12-15 11:20:13 -0800832 // Need to stop transceivers before destroying the stats collector because
833 // AudioRtpSender has a reference to the StatsCollector it will update when
834 // stopping.
835 for (auto transceiver : transceivers_) {
836 transceiver->Stop();
837 }
Steve Anton4171afb2017-11-20 10:20:22 -0800838
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700839 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800840 if (stats_collector_) {
841 stats_collector_->WaitForPendingRequest();
842 stats_collector_ = nullptr;
843 }
Steve Anton75737c02017-11-06 10:37:17 -0800844
Steve Anton8af21862017-12-15 11:20:13 -0800845 // Don't destroy BaseChannels until after stats has been cleaned up so that
846 // the last stats request can still read from the channels.
847 DestroyAllChannels();
848
Mirko Bonadei675513b2017-11-09 11:09:25 +0100849 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800850
851 webrtc_session_desc_factory_.reset();
852 sctp_invoker_.reset();
853 sctp_factory_.reset();
854 transport_controller_.reset();
855
deadbeef91dd5672016-05-18 16:55:30 -0700856 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700857 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700858 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700859 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700860 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700861 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800862 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700863 event_log_.reset();
864 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000865}
866
Steve Anton8af21862017-12-15 11:20:13 -0800867void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800868 // Destroy video channels first since they may have a pointer to a voice
869 // channel.
870 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800871 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800872 DestroyTransceiverChannel(transceiver);
873 }
874 }
875 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800876 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800877 DestroyTransceiverChannel(transceiver);
878 }
879 }
880 DestroyDataChannel();
881}
882
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000884 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700885 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200886 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800887 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100888 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700889
890 RTCError config_error = ValidateConfiguration(configuration);
891 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100892 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700893 return false;
894 }
895
deadbeef293e9262017-01-11 12:28:30 -0800896 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100897 RTC_LOG(LS_ERROR)
898 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100899 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800900 return false;
901 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200902
deadbeef653b8e02015-11-11 12:55:10 -0800903 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800904 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100905 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100906 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800907 return false;
908 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000909 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800910 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800911
deadbeef91dd5672016-05-18 16:55:30 -0700912 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700913 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700914 if (!network_thread()->Invoke<bool>(
915 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
916 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 return false;
918 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919
Zhi Huange830e682018-03-30 10:48:35 -0700920 const PeerConnectionFactoryInterface::Options& options = factory_->options();
921
Steve Anton75737c02017-11-06 10:37:17 -0800922 // RFC 3264: The numeric value of the session id and version in the
923 // o line MUST be representable with a "64 bit signed integer".
924 // Due to this constraint session id |session_id_| is max limited to
925 // LLONG_MAX.
926 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700927 JsepTransportController::Config config;
928 config.redetermine_role_on_ice_restart =
929 configuration.redetermine_role_on_ice_restart;
930 config.ssl_max_version = factory_->options().ssl_max_version;
931 config.disable_encryption = options.disable_encryption;
932 config.bundle_policy = configuration.bundle_policy;
933 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
934 config.crypto_options = options.crypto_options;
935#if defined(ENABLE_EXTERNAL_AUTH)
936 config.enable_external_auth = true;
937#endif
938 transport_controller_.reset(new JsepTransportController(
939 signaling_thread(), network_thread(), port_allocator_.get(), config));
940 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800941 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700942 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800943 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700944 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800945 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700946 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800947 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
948 transport_controller_->SignalDtlsHandshakeError.connect(
949 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
Zhi Huange830e682018-03-30 10:48:35 -0700950 transport_controller_->SignalRtpTransportChanged.connect(
951 this, &PeerConnection::OnRtpTransportChanged);
952 transport_controller_->SignalDtlsTransportChanged.connect(
953 this, &PeerConnection::OnDtlsTransportChanged);
Steve Anton75737c02017-11-06 10:37:17 -0800954
955 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700956
deadbeefab9b2d12015-10-14 11:33:11 -0700957 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700958 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959
Steve Antonba818672017-11-06 10:21:57 -0800960 configuration_ = configuration;
961
Steve Anton75737c02017-11-06 10:37:17 -0800962 // Obtain a certificate from RTCConfiguration if any were provided (optional).
963 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
964 if (!configuration.certificates.empty()) {
965 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
966 // just picking the first one. The decision should be made based on the DTLS
967 // handshake. The DTLS negotiations need to know about all certificates.
968 certificate = configuration.certificates[0];
969 }
970
Steve Antond25da372017-11-06 14:50:29 -0800971 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800972
973 if (options.disable_encryption) {
974 dtls_enabled_ = false;
975 } else {
976 // Enable DTLS by default if we have an identity store or a certificate.
977 dtls_enabled_ = (cert_generator || certificate);
978 // |configuration| can override the default |dtls_enabled_| value.
979 if (configuration.enable_dtls_srtp) {
980 dtls_enabled_ = *(configuration.enable_dtls_srtp);
981 }
982 }
983
984 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
985 // It takes precendence over the disable_sctp_data_channels
986 // PeerConnectionFactoryInterface::Options.
987 if (configuration.enable_rtp_data_channel) {
988 data_channel_type_ = cricket::DCT_RTP;
989 } else {
990 // DTLS has to be enabled to use SCTP.
991 if (!options.disable_sctp_data_channels && dtls_enabled_) {
992 data_channel_type_ = cricket::DCT_SCTP;
993 }
994 }
995
996 video_options_.screencast_min_bitrate_kbps =
997 configuration.screencast_min_bitrate;
998 audio_options_.combined_audio_video_bwe =
999 configuration.combined_audio_video_bwe;
1000
1001 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001002 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001003
1004 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001005 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001006
1007 // Whether the certificate generator/certificate is null or not determines
1008 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1009 // the right instructions by clearing the variables if needed.
1010 if (!dtls_enabled_) {
1011 cert_generator.reset();
1012 certificate = nullptr;
1013 } else if (certificate) {
1014 // Favor generated certificate over the certificate generator.
1015 cert_generator.reset();
1016 }
1017
1018 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1019 signaling_thread(), channel_manager(), this, session_id(),
1020 std::move(cert_generator), certificate));
1021 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1022 this, &PeerConnection::OnCertificateReady);
1023
1024 if (options.disable_encryption) {
1025 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1026 }
1027
1028 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1029 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030
Steve Anton4171afb2017-11-20 10:20:22 -08001031 // Add default audio/video transceivers for Plan B SDP.
1032 if (!IsUnifiedPlan()) {
1033 transceivers_.push_back(
1034 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1035 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1036 transceivers_.push_back(
1037 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1038 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1039 }
1040
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 return true;
1042}
1043
Steve Anton038834f2017-07-14 15:59:59 -07001044RTCError PeerConnection::ValidateConfiguration(
1045 const RTCConfiguration& config) const {
1046 if (config.ice_regather_interval_range &&
1047 config.continual_gathering_policy == GATHER_ONCE) {
1048 return RTCError(RTCErrorType::INVALID_PARAMETER,
1049 "ice_regather_interval_range specified but continual "
1050 "gathering policy is GATHER_ONCE");
1051 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001052 auto result =
1053 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1054 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001055}
1056
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001057rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001059 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1060 "Plan SdpSemantics. Please use GetSenders "
1061 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001062 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063}
1064
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001065rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001067 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1068 "Plan SdpSemantics. Please use GetReceivers "
1069 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001070 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071}
1072
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001073bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001074 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1075 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001076 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077 if (IsClosed()) {
1078 return false;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 return false;
1082 }
deadbeefab9b2d12015-10-14 11:33:11 -07001083
1084 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001085 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1086 observer->SignalAudioTrackAdded.connect(this,
1087 &PeerConnection::OnAudioTrackAdded);
1088 observer->SignalAudioTrackRemoved.connect(
1089 this, &PeerConnection::OnAudioTrackRemoved);
1090 observer->SignalVideoTrackAdded.connect(this,
1091 &PeerConnection::OnVideoTrackAdded);
1092 observer->SignalVideoTrackRemoved.connect(
1093 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001094 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001095
deadbeefab9b2d12015-10-14 11:33:11 -07001096 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001097 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001100 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001101 }
1102
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001103 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 observer_->OnRenegotiationNeeded();
1105 return true;
1106}
1107
1108void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001109 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1110 "Plan SdpSemantics. Please use RemoveTrack "
1111 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001112 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001113 if (!IsClosed()) {
1114 for (const auto& track : local_stream->GetAudioTracks()) {
1115 RemoveAudioTrack(track.get(), local_stream);
1116 }
1117 for (const auto& track : local_stream->GetVideoTracks()) {
1118 RemoveVideoTrack(track.get(), local_stream);
1119 }
deadbeefab9b2d12015-10-14 11:33:11 -07001120 }
deadbeefab9b2d12015-10-14 11:33:11 -07001121 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001122 stream_observers_.erase(
1123 std::remove_if(
1124 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001125 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001126 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001127 }),
1128 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001129
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 if (IsClosed()) {
1131 return;
1132 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133 observer_->OnRenegotiationNeeded();
1134}
1135
deadbeefe1f9d832016-01-14 15:35:42 -08001136rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1137 MediaStreamTrackInterface* track,
1138 std::vector<MediaStreamInterface*> streams) {
1139 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001140 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001141 for (auto* stream : streams) {
1142 if (!stream) {
1143 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1144 return nullptr;
1145 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001146 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001147 }
Seth Hampson845e8782018-03-02 11:34:10 -08001148 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001149 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001150 return nullptr;
1151 }
Steve Antonf9381f02017-12-14 10:23:57 -08001152 return sender_or_error.MoveValue();
1153}
1154
Steve Anton2d6c76a2018-01-05 17:10:52 -08001155RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001156 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001157 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001158 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001159 if (!track) {
1160 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1161 }
1162 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1163 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1165 "Track has invalid kind: " + track->kind());
1166 }
Steve Antonf9381f02017-12-14 10:23:57 -08001167 if (IsClosed()) {
1168 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1169 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001170 }
Steve Anton4171afb2017-11-20 10:20:22 -08001171 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001172 LOG_AND_RETURN_ERROR(
1173 RTCErrorType::INVALID_PARAMETER,
1174 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001175 }
Steve Antonf9381f02017-12-14 10:23:57 -08001176 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001177 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1178 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001179 if (sender_or_error.ok()) {
1180 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001181 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001182 }
1183 return sender_or_error;
1184}
deadbeefe1f9d832016-01-14 15:35:42 -08001185
Steve Antonf9381f02017-12-14 10:23:57 -08001186RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1187PeerConnection::AddTrackPlanB(
1188 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001189 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001190 if (stream_ids.size() > 1u) {
1191 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1192 "AddTrack with more than one stream is not "
1193 "supported with Plan B semantics.");
1194 }
1195 std::vector<std::string> adjusted_stream_ids = stream_ids;
1196 if (adjusted_stream_ids.empty()) {
1197 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1198 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001199 cricket::MediaType media_type =
1200 (track->kind() == MediaStreamTrackInterface::kAudioKind
1201 ? cricket::MEDIA_TYPE_AUDIO
1202 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001203 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001204 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001205 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001206 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001207 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001208 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001209 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001210 if (sender_info) {
1211 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001212 }
Steve Antonf9381f02017-12-14 10:23:57 -08001213 } else {
1214 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001215 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001216 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001217 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001218 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001219 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001220 if (sender_info) {
1221 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001222 }
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001224 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001225}
deadbeefe1f9d832016-01-14 15:35:42 -08001226
Steve Antonf9381f02017-12-14 10:23:57 -08001227RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1228PeerConnection::AddTrackUnifiedPlan(
1229 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001230 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001231 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1232 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001233 RTC_LOG(LS_INFO) << "Reusing an existing "
1234 << cricket::MediaTypeToString(transceiver->media_type())
1235 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001236 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001239 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001240 transceiver->internal()->set_direction(
1241 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001242 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001243 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001244 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001245 } else {
1246 cricket::MediaType media_type =
1247 (track->kind() == MediaStreamTrackInterface::kAudioKind
1248 ? cricket::MEDIA_TYPE_AUDIO
1249 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001250 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1251 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001252 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001253 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1254 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001255 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001256 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001257 }
Steve Antonf9381f02017-12-14 10:23:57 -08001258 return transceiver->sender();
1259}
1260
1261rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1262PeerConnection::FindFirstTransceiverForAddedTrack(
1263 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1264 RTC_DCHECK(track);
1265 for (auto transceiver : transceivers_) {
1266 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001267 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001268 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001269 !transceiver->internal()->has_ever_been_used_to_send() &&
1270 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001271 return transceiver;
1272 }
1273 }
1274 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001275}
1276
1277bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1278 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001279 return RemoveTrackInternal(sender).ok();
1280}
1281
1282RTCError PeerConnection::RemoveTrackInternal(
1283 rtc::scoped_refptr<RtpSenderInterface> sender) {
1284 if (!sender) {
1285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1286 }
deadbeefe1f9d832016-01-14 15:35:42 -08001287 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001288 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1289 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001290 }
Steve Antonf9381f02017-12-14 10:23:57 -08001291 if (IsUnifiedPlan()) {
1292 auto transceiver = FindTransceiverBySender(sender);
1293 if (!transceiver || !sender->track()) {
1294 return RTCError::OK();
1295 }
1296 sender->SetTrack(nullptr);
1297 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001300 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001301 transceiver->internal()->set_direction(
1302 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001303 }
Steve Anton4171afb2017-11-20 10:20:22 -08001304 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001305 bool removed;
1306 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1307 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1308 } else {
1309 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1310 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1311 }
1312 if (!removed) {
1313 LOG_AND_RETURN_ERROR(
1314 RTCErrorType::INVALID_PARAMETER,
1315 "Couldn't find sender " + sender->id() + " to remove.");
1316 }
Steve Anton4171afb2017-11-20 10:20:22 -08001317 }
deadbeefe1f9d832016-01-14 15:35:42 -08001318 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001319 return RTCError::OK();
1320}
1321
1322rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1323PeerConnection::FindTransceiverBySender(
1324 rtc::scoped_refptr<RtpSenderInterface> sender) {
1325 for (auto transceiver : transceivers_) {
1326 if (transceiver->sender() == sender) {
1327 return transceiver;
1328 }
1329 }
1330 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001331}
1332
Steve Anton9158ef62017-11-27 13:01:52 -08001333RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1334PeerConnection::AddTransceiver(
1335 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1336 return AddTransceiver(track, RtpTransceiverInit());
1337}
1338
1339RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1340PeerConnection::AddTransceiver(
1341 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1342 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001343 RTC_CHECK(IsUnifiedPlan())
1344 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001345 if (!track) {
1346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1347 }
1348 cricket::MediaType media_type;
1349 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1350 media_type = cricket::MEDIA_TYPE_AUDIO;
1351 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1352 media_type = cricket::MEDIA_TYPE_VIDEO;
1353 } else {
1354 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1355 "Track kind is not audio or video");
1356 }
1357 return AddTransceiver(media_type, track, init);
1358}
1359
1360RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1361PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1362 return AddTransceiver(media_type, RtpTransceiverInit());
1363}
1364
1365RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1366PeerConnection::AddTransceiver(cricket::MediaType media_type,
1367 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001368 RTC_CHECK(IsUnifiedPlan())
1369 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001370 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1371 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1372 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1373 "media type is not audio or video");
1374 }
1375 return AddTransceiver(media_type, nullptr, init);
1376}
1377
1378RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1379PeerConnection::AddTransceiver(
1380 cricket::MediaType media_type,
1381 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001382 const RtpTransceiverInit& init,
1383 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001384 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1385 media_type == cricket::MEDIA_TYPE_VIDEO));
1386 if (track) {
1387 RTC_DCHECK_EQ(media_type,
1388 (track->kind() == MediaStreamTrackInterface::kAudioKind
1389 ? cricket::MEDIA_TYPE_AUDIO
1390 : cricket::MEDIA_TYPE_VIDEO));
1391 }
1392
1393 // TODO(bugs.webrtc.org/7600): Verify init.
1394
Steve Anton3d954a62018-04-02 11:27:23 -07001395 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1396 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001397 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1399 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1400 transceiver->internal()->set_direction(init.direction);
1401
Steve Anton22da89f2018-01-25 13:58:07 -08001402 if (fire_callback) {
1403 observer_->OnRenegotiationNeeded();
1404 }
Steve Antonf9381f02017-12-14 10:23:57 -08001405
1406 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1407}
1408
Steve Anton02ee47c2018-01-10 16:26:06 -08001409rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1410PeerConnection::CreateSender(
1411 cricket::MediaType media_type,
1412 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001413 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001414 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001415 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1416 RTC_DCHECK(!track ||
1417 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1418 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1419 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001420 new AudioRtpSender(worker_thread(),
1421 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001422 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001423 } else {
1424 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1425 RTC_DCHECK(!track ||
1426 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1427 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1428 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001429 new VideoRtpSender(worker_thread(),
1430 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001431 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001432 }
Seth Hampson845e8782018-03-02 11:34:10 -08001433 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001434 return sender;
1435}
1436
1437rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1438PeerConnection::CreateReceiver(cricket::MediaType media_type,
1439 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001440 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1441 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001442 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001443 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001444 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001445 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001446 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001448 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1449 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001450 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001451 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001452 return receiver;
1453}
1454
1455rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1456PeerConnection::CreateAndAddTransceiver(
1457 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1458 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1459 receiver) {
1460 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1461 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001462 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001463 transceiver->internal()->SignalNegotiationNeeded.connect(
1464 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001465 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001466}
1467
Steve Anton52d86772018-02-20 15:48:12 -08001468void PeerConnection::OnNegotiationNeeded() {
1469 RTC_DCHECK_RUN_ON(signaling_thread());
1470 RTC_DCHECK(!IsClosed());
1471 observer_->OnRenegotiationNeeded();
1472}
1473
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001474rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001476 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001477 if (IsClosed()) {
1478 return nullptr;
1479 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001481 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001482 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 }
Steve Anton4171afb2017-11-20 10:20:22 -08001484 auto track_sender = FindSenderForTrack(track);
1485 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001486 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001487 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488 }
1489
Steve Anton4171afb2017-11-20 10:20:22 -08001490 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491}
1492
deadbeeffac06552015-11-25 11:26:01 -08001493rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001494 const std::string& kind,
1495 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001496 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1497 "Plan SdpSemantics. Please use AddTransceiver "
1498 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001499 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001500 if (IsClosed()) {
1501 return nullptr;
1502 }
Steve Anton4171afb2017-11-20 10:20:22 -08001503
Seth Hampson5b4f0752018-04-02 16:31:36 -07001504 // Internally we need to have one stream with Plan B semantics, so we
1505 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001506 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001507 if (stream_id.empty()) {
1508 stream_ids.push_back(rtc::CreateRandomUuid());
1509 RTC_LOG(LS_INFO)
1510 << "No stream_id specified for sender. Generated stream ID: "
1511 << stream_ids[0];
1512 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001513 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001514 }
1515
Steve Anton4171afb2017-11-20 10:20:22 -08001516 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001517 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001518 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001519 auto* audio_sender =
1520 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001521 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001522 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001523 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001524 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001525 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001526 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001527 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001528 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001529 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001530 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001531 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001532 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001533 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001534 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001535 }
Steve Anton4171afb2017-11-20 10:20:22 -08001536
deadbeefe1f9d832016-01-14 15:35:42 -08001537 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001538}
1539
deadbeef70ab1a12015-09-28 16:53:55 -07001540std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1541 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001542 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001543 for (auto sender : GetSendersInternal()) {
1544 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001545 }
1546 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001547}
1548
Steve Anton4171afb2017-11-20 10:20:22 -08001549std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1550PeerConnection::GetSendersInternal() const {
1551 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1552 all_senders;
1553 for (auto transceiver : transceivers_) {
1554 auto senders = transceiver->internal()->senders();
1555 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1556 }
1557 return all_senders;
1558}
1559
deadbeef70ab1a12015-09-28 16:53:55 -07001560std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1561PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001562 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001563 for (const auto& receiver : GetReceiversInternal()) {
1564 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001565 }
1566 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001567}
1568
Steve Anton4171afb2017-11-20 10:20:22 -08001569std::vector<
1570 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1571PeerConnection::GetReceiversInternal() const {
1572 std::vector<
1573 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1574 all_receivers;
1575 for (auto transceiver : transceivers_) {
1576 auto receivers = transceiver->internal()->receivers();
1577 all_receivers.insert(all_receivers.end(), receivers.begin(),
1578 receivers.end());
1579 }
1580 return all_receivers;
1581}
1582
Steve Anton9158ef62017-11-27 13:01:52 -08001583std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1584PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001585 RTC_CHECK(IsUnifiedPlan())
1586 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001587 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1588 for (auto transceiver : transceivers_) {
1589 all_transceivers.push_back(transceiver);
1590 }
1591 return all_transceivers;
1592}
1593
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001594bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001595 MediaStreamTrackInterface* track,
1596 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001597 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001598 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001599 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001600 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001601 return false;
1602 }
1603
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001604 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001605 // The StatsCollector is used to tell if a track is valid because it may
1606 // remember tracks that the PeerConnection previously removed.
1607 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001608 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1609 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001610 return false;
1611 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001612 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001613 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001614 return true;
1615}
1616
hbos74e1a4f2016-09-15 23:33:01 -07001617void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001618 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001619 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001620 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001621 stats_collector_->GetStatsReport(callback);
1622}
1623
Henrik Boström1df1bf82018-03-20 13:24:20 +01001624void PeerConnection::GetStats(
1625 rtc::scoped_refptr<RtpSenderInterface> selector,
1626 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1627 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1628 RTC_DCHECK(callback);
1629 RTC_DCHECK(stats_collector_);
1630 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1631 if (selector) {
1632 for (const auto& proxy_transceiver : transceivers_) {
1633 for (const auto& proxy_sender :
1634 proxy_transceiver->internal()->senders()) {
1635 if (proxy_sender == selector) {
1636 internal_sender = proxy_sender->internal();
1637 break;
1638 }
1639 }
1640 if (internal_sender)
1641 break;
1642 }
1643 }
1644 // If there is no |internal_sender| then |selector| is either null or does not
1645 // belong to the PeerConnection (in Plan B, senders can be removed from the
1646 // PeerConnection). This means that "all the stats objects representing the
1647 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1648 // produces an empty stats report.
1649 stats_collector_->GetStatsReport(internal_sender, callback);
1650}
1651
1652void PeerConnection::GetStats(
1653 rtc::scoped_refptr<RtpReceiverInterface> selector,
1654 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1655 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1656 RTC_DCHECK(callback);
1657 RTC_DCHECK(stats_collector_);
1658 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1659 if (selector) {
1660 for (const auto& proxy_transceiver : transceivers_) {
1661 for (const auto& proxy_receiver :
1662 proxy_transceiver->internal()->receivers()) {
1663 if (proxy_receiver == selector) {
1664 internal_receiver = proxy_receiver->internal();
1665 break;
1666 }
1667 }
1668 if (internal_receiver)
1669 break;
1670 }
1671 }
1672 // If there is no |internal_receiver| then |selector| is either null or does
1673 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1674 // the PeerConnection). This means that "all the stats objects representing
1675 // the selector" is an empty set. Invoking GetStatsReport() with a null
1676 // selector produces an empty stats report.
1677 stats_collector_->GetStatsReport(internal_receiver, callback);
1678}
1679
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1681 return signaling_state_;
1682}
1683
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684PeerConnectionInterface::IceConnectionState
1685PeerConnection::ice_connection_state() {
1686 return ice_connection_state_;
1687}
1688
1689PeerConnectionInterface::IceGatheringState
1690PeerConnection::ice_gathering_state() {
1691 return ice_gathering_state_;
1692}
1693
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001694rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695PeerConnection::CreateDataChannel(
1696 const std::string& label,
1697 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001698 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001699
deadbeefab9b2d12015-10-14 11:33:11 -07001700 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001701
kwibergd1fe2812016-04-27 06:47:29 -07001702 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001703 if (config) {
1704 internal_config.reset(new InternalDataChannelInit(*config));
1705 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001706 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001707 InternalCreateDataChannel(label, internal_config.get()));
1708 if (!channel.get()) {
1709 return nullptr;
1710 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001712 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1713 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001714 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001715 observer_->OnRenegotiationNeeded();
1716 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001717
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 return DataChannelProxy::Create(signaling_thread(), channel.get());
1719}
1720
1721void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1722 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001723 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001724
zhihuang1c378ed2017-08-17 14:10:50 -07001725 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1726 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1727 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1728 // compares the mandatory fields parsed with the mandatory fields added in the
1729 // |constraints| and some downstream applications might create offers with
1730 // mandatory fields which would not be parsed in the helper method. For
1731 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1732 // |constraints| as a mandatory field but it is not parsed.
1733 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001734
zhihuang1c378ed2017-08-17 14:10:50 -07001735 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001736}
1737
1738void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1739 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001740 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001741
nisse7ce109a2017-01-31 00:57:56 -08001742 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001743 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001744 return;
1745 }
deadbeefab9b2d12015-10-14 11:33:11 -07001746
Steve Anton8d3444d2017-10-20 15:30:51 -07001747 if (IsClosed()) {
1748 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001749 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001750 PostCreateSessionDescriptionFailure(
1751 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001752 return;
1753 }
1754
zhihuang1c378ed2017-08-17 14:10:50 -07001755 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001756 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001757 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001758 PostCreateSessionDescriptionFailure(
1759 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001760 return;
1761 }
1762
Steve Anton22da89f2018-01-25 13:58:07 -08001763 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1764 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1765 if (IsUnifiedPlan()) {
1766 RTCError error = HandleLegacyOfferOptions(options);
1767 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001768 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001769 return;
1770 }
1771 }
1772
zhihuang1c378ed2017-08-17 14:10:50 -07001773 cricket::MediaSessionOptions session_options;
1774 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001775 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776}
1777
Steve Anton22da89f2018-01-25 13:58:07 -08001778RTCError PeerConnection::HandleLegacyOfferOptions(
1779 const RTCOfferAnswerOptions& options) {
1780 RTC_DCHECK(IsUnifiedPlan());
1781
1782 if (options.offer_to_receive_audio == 0) {
1783 RemoveRecvDirectionFromReceivingTransceiversOfType(
1784 cricket::MEDIA_TYPE_AUDIO);
1785 } else if (options.offer_to_receive_audio == 1) {
1786 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1787 } else if (options.offer_to_receive_audio > 1) {
1788 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1789 "offer_to_receive_audio > 1 is not supported.");
1790 }
1791
1792 if (options.offer_to_receive_video == 0) {
1793 RemoveRecvDirectionFromReceivingTransceiversOfType(
1794 cricket::MEDIA_TYPE_VIDEO);
1795 } else if (options.offer_to_receive_video == 1) {
1796 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1797 } else if (options.offer_to_receive_video > 1) {
1798 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1799 "offer_to_receive_video > 1 is not supported.");
1800 }
1801
1802 return RTCError::OK();
1803}
1804
1805void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1806 cricket::MediaType media_type) {
1807 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001808 RtpTransceiverDirection new_direction =
1809 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1810 if (new_direction != transceiver->direction()) {
1811 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1812 << " transceiver (MID="
1813 << transceiver->mid().value_or("<not set>") << ") from "
1814 << RtpTransceiverDirectionToString(
1815 transceiver->direction())
1816 << " to "
1817 << RtpTransceiverDirectionToString(new_direction)
1818 << " since CreateOffer specified offer_to_receive=0";
1819 transceiver->internal()->set_direction(new_direction);
1820 }
Steve Anton22da89f2018-01-25 13:58:07 -08001821 }
1822}
1823
1824void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1825 cricket::MediaType media_type) {
1826 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001827 RTC_LOG(LS_INFO)
1828 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1829 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001830 RtpTransceiverInit init;
1831 init.direction = RtpTransceiverDirection::kRecvOnly;
1832 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1833 }
1834}
1835
1836std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1837PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1838 std::vector<
1839 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1840 receiving_transceivers;
1841 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001842 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001843 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1844 receiving_transceivers.push_back(transceiver);
1845 }
1846 }
1847 return receiving_transceivers;
1848}
1849
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850void PeerConnection::CreateAnswer(
1851 CreateSessionDescriptionObserver* observer,
1852 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001853 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001854
nisse7ce109a2017-01-31 00:57:56 -08001855 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001856 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857 return;
1858 }
deadbeefab9b2d12015-10-14 11:33:11 -07001859
zhihuang1c378ed2017-08-17 14:10:50 -07001860 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1861 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1862 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001863 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001864 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001865 PostCreateSessionDescriptionFailure(
1866 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001867 return;
1868 }
1869
Steve Anton8d3444d2017-10-20 15:30:51 -07001870 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001871}
1872
1873void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1874 const RTCOfferAnswerOptions& options) {
1875 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001876 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001877 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001878 return;
1879 }
1880
Steve Antondffead82018-02-06 10:31:29 -08001881 if (!(signaling_state_ == kHaveRemoteOffer ||
1882 signaling_state_ == kHaveLocalPrAnswer)) {
1883 std::string error =
1884 "PeerConnection cannot create an answer in a state other than "
1885 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001886 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001887 PostCreateSessionDescriptionFailure(
1888 observer, RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001889 return;
1890 }
1891
Steve Antondffead82018-02-06 10:31:29 -08001892 // The remote description should be set if we're in the right state.
1893 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001894
Steve Anton22da89f2018-01-25 13:58:07 -08001895 if (IsUnifiedPlan()) {
1896 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1897 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1898 "supported with Unified Plan semantics. Use the "
1899 "RtpTransceiver API instead.";
1900 }
1901 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1902 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1903 "supported with Unified Plan semantics. Use the "
1904 "RtpTransceiver API instead.";
1905 }
1906 }
1907
htaa2a49d92016-03-04 02:51:39 -08001908 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001909 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001910
Steve Antond25da372017-11-06 14:50:29 -08001911 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912}
1913
1914void PeerConnection::SetLocalDescription(
1915 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001916 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001917 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001918
Steve Anton80dd7b52018-02-16 17:08:42 -08001919 // The SetLocalDescription contract is that we take ownership of the session
1920 // description regardless of the outcome, so wrap it in a unique_ptr right
1921 // away. Ideally, SetLocalDescription's signature will be changed to take the
1922 // description as a unique_ptr argument to formalize this agreement.
1923 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1924
nisse7ce109a2017-01-31 00:57:56 -08001925 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001926 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 return;
1928 }
Steve Anton8a006912017-12-04 15:25:56 -08001929
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001931 PostSetSessionDescriptionFailure(
1932 observer,
1933 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 return;
1935 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001936
Steve Anton80dd7b52018-02-16 17:08:42 -08001937 // If a session error has occurred the PeerConnection is in a possibly
1938 // inconsistent state so fail right away.
1939 if (session_error() != SessionError::kNone) {
1940 std::string error_message = GetSessionErrorMsg();
1941 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001942 PostSetSessionDescriptionFailure(
1943 observer,
1944 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001945 return;
1946 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001947
Steve Anton80dd7b52018-02-16 17:08:42 -08001948 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1949 if (!error.ok()) {
1950 std::string error_message = GetSetDescriptionErrorMessage(
1951 cricket::CS_LOCAL, desc->GetType(), error);
1952 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001953 PostSetSessionDescriptionFailure(
1954 observer,
1955 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001956 return;
1957 }
1958
1959 // Grab the description type before moving ownership to ApplyLocalDescription,
1960 // which may destroy it before returning.
1961 const SdpType type = desc->GetType();
1962
1963 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001964 // |desc| may be destroyed at this point.
1965
1966 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001967 // If ApplyLocalDescription fails, the PeerConnection could be in an
1968 // inconsistent state, so act conservatively here and set the session error
1969 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1970 SetSessionError(SessionError::kContent, error.message());
1971 std::string error_message =
1972 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1973 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001974 PostSetSessionDescriptionFailure(
1975 observer,
1976 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001977 return;
1978 }
Steve Anton8a006912017-12-04 15:25:56 -08001979 RTC_DCHECK(local_description());
1980
1981 PostSetSessionDescriptionSuccess(observer);
1982
Steve Anton8a006912017-12-04 15:25:56 -08001983 // MaybeStartGathering needs to be called after posting
1984 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1985 // before signaling that SetLocalDescription completed.
1986 transport_controller_->MaybeStartGathering();
1987
Steve Antona3a92c22017-12-07 10:27:41 -08001988 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001989 // TODO(deadbeef): We already had to hop to the network thread for
1990 // MaybeStartGathering...
1991 network_thread()->Invoke<void>(
1992 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1993 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001994 // Make UMA notes about what was agreed to.
1995 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001996 }
1997}
1998
1999RTCError PeerConnection::ApplyLocalDescription(
2000 std::unique_ptr<SessionDescriptionInterface> desc) {
2001 RTC_DCHECK_RUN_ON(signaling_thread());
2002 RTC_DCHECK(desc);
2003
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 // Update stats here so that we have the most recent stats for tracks and
2005 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002006 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002007
Steve Antondcc3c022017-12-22 16:02:54 -08002008 // Take a reference to the old local description since it's used below to
2009 // compare against the new local description. When setting the new local
2010 // description, grab ownership of the replaced session description in case it
2011 // is the same as |old_local_description|, to keep it alive for the duration
2012 // of the method.
2013 const SessionDescriptionInterface* old_local_description =
2014 local_description();
2015 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002016 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002017 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002018 replaced_local_description = pending_local_description_
2019 ? std::move(pending_local_description_)
2020 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002021 current_local_description_ = std::move(desc);
2022 pending_local_description_ = nullptr;
2023 current_remote_description_ = std::move(pending_remote_description_);
2024 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002025 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002026 pending_local_description_ = std::move(desc);
2027 }
2028 // The session description to apply now must be accessed by
2029 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002030 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002031
Zhi Huange830e682018-03-30 10:48:35 -07002032 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2033 if (!error.ok()) {
2034 return error;
2035 }
2036
Steve Antondcc3c022017-12-22 16:02:54 -08002037 if (IsUnifiedPlan()) {
2038 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002039 cricket::CS_LOCAL, *local_description(), old_local_description,
2040 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002041 if (!error.ok()) {
2042 return error;
2043 }
Steve Antondcc3c022017-12-22 16:02:54 -08002044 for (auto transceiver : transceivers_) {
2045 const ContentInfo* content =
2046 FindMediaSectionForTransceiver(transceiver, local_description());
2047 if (!content) {
2048 continue;
2049 }
2050 const MediaContentDescription* media_desc = content->media_description();
2051 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2052 transceiver->internal()->set_current_direction(media_desc->direction());
2053 }
2054 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002055 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2056 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002057 transceiver->Stop();
2058 }
2059 }
2060 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002061 // Media channels will be created only when offer is set. These may use new
2062 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002063 if (type == SdpType::kOffer) {
2064 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2065 // description is applied. Restore back to old description.
2066 RTCError error = CreateChannels(*local_description()->description());
2067 if (!error.ok()) {
2068 return error;
2069 }
2070 }
Steve Antondcc3c022017-12-22 16:02:54 -08002071 // Remove unused channels if MediaContentDescription is rejected.
2072 RemoveUnusedChannels(local_description()->description());
2073 }
Steve Anton8a006912017-12-04 15:25:56 -08002074
Zhi Huange830e682018-03-30 10:48:35 -07002075 error = UpdateSessionState(type, cricket::CS_LOCAL,
2076 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002077 if (!error.ok()) {
2078 return error;
2079 }
Steve Antondcc3c022017-12-22 16:02:54 -08002080
Steve Anton8a006912017-12-04 15:25:56 -08002081 if (remote_description()) {
2082 // Now that we have a local description, we can push down remote candidates.
2083 UseCandidatesInSessionDescription(remote_description());
2084 }
2085
2086 pending_ice_restarts_.clear();
2087 if (session_error() != SessionError::kNone) {
2088 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2089 }
2090
deadbeefab9b2d12015-10-14 11:33:11 -07002091 // If setting the description decided our SSL role, allocate any necessary
2092 // SCTP sids.
2093 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002094 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002095 AllocateSctpSids(role);
2096 }
2097
Steve Antond3679212018-01-17 17:41:02 -08002098 if (IsUnifiedPlan()) {
2099 for (auto transceiver : transceivers_) {
2100 const ContentInfo* content =
2101 FindMediaSectionForTransceiver(transceiver, local_description());
2102 if (!content) {
2103 continue;
2104 }
Steve Anton74255ff2018-01-24 18:32:57 -08002105 const auto& streams = content->media_description()->streams();
2106 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002107 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002108 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002109 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002110 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002111 }
2112 }
2113 } else {
2114 // Plan B semantics.
2115
Steve Antondcc3c022017-12-22 16:02:54 -08002116 // Update state and SSRC of local MediaStreams and DataChannels based on the
2117 // local session description.
2118 const cricket::ContentInfo* audio_content =
2119 GetFirstAudioContent(local_description()->description());
2120 if (audio_content) {
2121 if (audio_content->rejected) {
2122 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2123 } else {
2124 const cricket::AudioContentDescription* audio_desc =
2125 audio_content->media_description()->as_audio();
2126 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2127 }
deadbeeffaac4972015-11-12 15:33:07 -08002128 }
deadbeefab9b2d12015-10-14 11:33:11 -07002129
Steve Antondcc3c022017-12-22 16:02:54 -08002130 const cricket::ContentInfo* video_content =
2131 GetFirstVideoContent(local_description()->description());
2132 if (video_content) {
2133 if (video_content->rejected) {
2134 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2135 } else {
2136 const cricket::VideoContentDescription* video_desc =
2137 video_content->media_description()->as_video();
2138 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2139 }
deadbeeffaac4972015-11-12 15:33:07 -08002140 }
deadbeefab9b2d12015-10-14 11:33:11 -07002141 }
2142
2143 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002144 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002145 if (data_content) {
2146 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002147 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002148 if (rtc::starts_with(data_desc->protocol().data(),
2149 cricket::kMediaProtocolRtpPrefix)) {
2150 UpdateLocalRtpDataChannels(data_desc->streams());
2151 }
2152 }
2153
Steve Anton8a006912017-12-04 15:25:56 -08002154 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002155}
2156
2157void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002158 SetSessionDescriptionObserver* observer,
2159 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002160 SetRemoteDescription(
2161 std::unique_ptr<SessionDescriptionInterface>(desc),
2162 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2163 new SetRemoteDescriptionObserverAdapter(this, observer)));
2164}
2165
2166void PeerConnection::SetRemoteDescription(
2167 std::unique_ptr<SessionDescriptionInterface> desc,
2168 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002169 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002170
nisse7ce109a2017-01-31 00:57:56 -08002171 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002172 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002173 return;
2174 }
Steve Anton8a006912017-12-04 15:25:56 -08002175
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002177 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002178 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179 return;
2180 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002181
Steve Anton80dd7b52018-02-16 17:08:42 -08002182 // If a session error has occurred the PeerConnection is in a possibly
2183 // inconsistent state so fail right away.
2184 if (session_error() != SessionError::kNone) {
2185 std::string error_message = GetSessionErrorMsg();
2186 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2187 observer->OnSetRemoteDescriptionComplete(
2188 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2189 return;
2190 }
Steve Anton71439a62018-02-15 11:53:06 -08002191
Steve Anton80dd7b52018-02-16 17:08:42 -08002192 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002193 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002194 std::string error_message = GetSetDescriptionErrorMessage(
2195 cricket::CS_REMOTE, desc->GetType(), error);
2196 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002197 observer->OnSetRemoteDescriptionComplete(
2198 RTCError(error.type(), std::move(error_message)));
2199 return;
2200 }
Steve Anton71439a62018-02-15 11:53:06 -08002201
Steve Anton80dd7b52018-02-16 17:08:42 -08002202 // Grab the description type before moving ownership to
2203 // ApplyRemoteDescription, which may destroy it before returning.
2204 const SdpType type = desc->GetType();
2205
2206 error = ApplyRemoteDescription(std::move(desc));
2207 // |desc| may be destroyed at this point.
2208
2209 if (!error.ok()) {
2210 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2211 // inconsistent state, so act conservatively here and set the session error
2212 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2213 SetSessionError(SessionError::kContent, error.message());
2214 std::string error_message =
2215 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2216 RTC_LOG(LS_ERROR) << error_message;
2217 observer->OnSetRemoteDescriptionComplete(
2218 RTCError(error.type(), std::move(error_message)));
2219 return;
2220 }
2221 RTC_DCHECK(remote_description());
2222
Steve Anton8e20f172018-03-06 10:55:04 -08002223 if (type == SdpType::kOffer) {
2224 // Report to UMA the format of the received offer.
2225 ReportSdpFormatReceived(*remote_description());
2226 }
2227
Steve Anton80dd7b52018-02-16 17:08:42 -08002228 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002229 // TODO(deadbeef): We already had to hop to the network thread for
2230 // MaybeStartGathering...
2231 network_thread()->Invoke<void>(
2232 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2233 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002234 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002235 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002236 }
2237
2238 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2239}
2240
2241RTCError PeerConnection::ApplyRemoteDescription(
2242 std::unique_ptr<SessionDescriptionInterface> desc) {
2243 RTC_DCHECK_RUN_ON(signaling_thread());
2244 RTC_DCHECK(desc);
2245
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246 // Update stats here so that we have the most recent stats for tracks and
2247 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002248 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002249
Steve Antondcc3c022017-12-22 16:02:54 -08002250 // Take a reference to the old remote description since it's used below to
2251 // compare against the new remote description. When setting the new remote
2252 // description, grab ownership of the replaced session description in case it
2253 // is the same as |old_remote_description|, to keep it alive for the duration
2254 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002255 const SessionDescriptionInterface* old_remote_description =
2256 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002257 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002258 SdpType type = desc->GetType();
2259 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002260 replaced_remote_description = pending_remote_description_
2261 ? std::move(pending_remote_description_)
2262 : std::move(current_remote_description_);
2263 current_remote_description_ = std::move(desc);
2264 pending_remote_description_ = nullptr;
2265 current_local_description_ = std::move(pending_local_description_);
2266 } else {
2267 replaced_remote_description = std::move(pending_remote_description_);
2268 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002269 }
Steve Anton8a006912017-12-04 15:25:56 -08002270 // The session description to apply now must be accessed by
2271 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002272 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273
Zhi Huange830e682018-03-30 10:48:35 -07002274 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2275 if (!error.ok()) {
2276 return error;
2277 }
Steve Anton8a006912017-12-04 15:25:56 -08002278 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002279 if (IsUnifiedPlan()) {
2280 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002281 cricket::CS_REMOTE, *remote_description(), local_description(),
2282 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002283 if (!error.ok()) {
2284 return error;
2285 }
Steve Antondcc3c022017-12-22 16:02:54 -08002286 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002287 // Media channels will be created only when offer is set. These may use new
2288 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002289 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002290 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002291 // description is applied. Restore back to old description.
2292 RTCError error = CreateChannels(*remote_description()->description());
2293 if (!error.ok()) {
2294 return error;
2295 }
2296 }
Steve Antondcc3c022017-12-22 16:02:54 -08002297 // Remove unused channels if MediaContentDescription is rejected.
2298 RemoveUnusedChannels(remote_description()->description());
2299 }
Steve Anton8a006912017-12-04 15:25:56 -08002300
Zhi Huange830e682018-03-30 10:48:35 -07002301 // NOTE: Candidates allocation will be initiated only when
2302 // SetLocalDescription is called.
2303 error = UpdateSessionState(type, cricket::CS_REMOTE,
2304 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002305 if (!error.ok()) {
2306 return error;
2307 }
2308
2309 if (local_description() &&
2310 !UseCandidatesInSessionDescription(remote_description())) {
2311 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2312 }
2313
2314 if (old_remote_description) {
2315 for (const cricket::ContentInfo& content :
2316 old_remote_description->description()->contents()) {
2317 // Check if this new SessionDescription contains new ICE ufrag and
2318 // password that indicates the remote peer requests an ICE restart.
2319 // TODO(deadbeef): When we start storing both the current and pending
2320 // remote description, this should reset pending_ice_restarts and compare
2321 // against the current description.
2322 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2323 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002324 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002325 pending_ice_restarts_.insert(content.name);
2326 }
2327 } else {
2328 // We retain all received candidates only if ICE is not restarted.
2329 // When ICE is restarted, all previous candidates belong to an old
2330 // generation and should not be kept.
2331 // TODO(deadbeef): This goes against the W3C spec which says the remote
2332 // description should only contain candidates from the last set remote
2333 // description plus any candidates added since then. We should remove
2334 // this once we're sure it won't break anything.
2335 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2336 old_remote_description, content.name, mutable_remote_description());
2337 }
2338 }
2339 }
2340
2341 if (session_error() != SessionError::kNone) {
2342 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2343 }
2344
2345 // Set the the ICE connection state to connecting since the connection may
2346 // become writable with peer reflexive candidates before any remote candidate
2347 // is signaled.
2348 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2349 // is to have a new signal the indicates a change in checking state from the
2350 // transport and expose a new checking() member from transport that can be
2351 // read to determine the current checking state. The existing SignalConnecting
2352 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002353 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Anton8a006912017-12-04 15:25:56 -08002354 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2355 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2356 }
2357
deadbeefab9b2d12015-10-14 11:33:11 -07002358 // If setting the description decided our SSL role, allocate any necessary
2359 // SCTP sids.
2360 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002361 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002362 AllocateSctpSids(role);
2363 }
2364
Steve Antondcc3c022017-12-22 16:02:54 -08002365 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002366 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2367 receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002368 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002369 for (auto transceiver : transceivers_) {
2370 const ContentInfo* content =
2371 FindMediaSectionForTransceiver(transceiver, remote_description());
2372 if (!content) {
2373 continue;
2374 }
2375 const MediaContentDescription* media_desc = content->media_description();
2376 RtpTransceiverDirection local_direction =
2377 RtpTransceiverDirectionReversed(media_desc->direction());
2378 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2379 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2380 // transceiver's current direction is neither sendrecv nor recvonly,
2381 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002382 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002383 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002384 // The remote description has signaled the stream IDs.
2385 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002386 }
Steve Antondcc3c022017-12-22 16:02:54 -08002387 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2388 (!transceiver->current_direction() ||
2389 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002390 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002391 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002392 << content->name << " (added to "
2393 << GetStreamIdsString(stream_ids) << ").";
2394
2395 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2396 for (const std::string& stream_id : stream_ids) {
2397 rtc::scoped_refptr<MediaStreamInterface> stream =
2398 remote_streams_->find(stream_id);
2399 if (!stream) {
2400 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2401 MediaStream::Create(stream_id));
2402 remote_streams_->AddStream(stream);
2403 added_streams.push_back(stream);
2404 }
2405 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002406 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07002407 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton8b815cd2018-02-16 16:14:42 -08002408 receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002409 }
2410 // If direction is sendonly or inactive, and transceiver's current
2411 // direction is neither sendonly nor inactive, process the removal of a
2412 // remote track for the media description.
2413 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002414 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002415 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002416 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2417 << content->name;
Steve Antonef65ef12018-01-10 17:15:20 -08002418 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Antondcc3c022017-12-22 16:02:54 -08002419 }
2420 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2421 transceiver->internal()->set_current_direction(local_direction);
2422 }
2423 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002424 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2425 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002426 transceiver->Stop();
2427 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002428 if (!content->rejected &&
2429 RtpTransceiverDirectionHasRecv(local_direction)) {
2430 // Set ssrc to 0 in the case of an unsignalled ssrc.
2431 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002432 if (!media_desc->streams().empty() &&
2433 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002434 ssrc = media_desc->streams()[0].first_ssrc();
2435 }
2436 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002437 }
Steve Antondcc3c022017-12-22 16:02:54 -08002438 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002439 // Once all processing has finished, fire off callbacks.
Steve Anton8b815cd2018-02-16 16:14:42 -08002440 for (auto transceiver : receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002441 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002442 observer_->OnTrack(transceiver);
2443 observer_->OnAddTrack(transceiver->receiver(),
2444 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002445 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002446 for (auto stream : added_streams) {
2447 observer_->OnAddStream(stream);
2448 }
Steve Antondcc3c022017-12-22 16:02:54 -08002449 }
2450
Henrik Boströmfdb92012017-11-09 19:55:44 +01002451 const cricket::ContentInfo* audio_content =
2452 GetFirstAudioContent(remote_description()->description());
2453 const cricket::ContentInfo* video_content =
2454 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002455 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002456 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002457 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002458 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002459 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002460 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002461
2462 // Check if the descriptions include streams, just in case the peer supports
2463 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002464 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002465 (audio_desc && !audio_desc->streams().empty()) ||
2466 (video_desc && !video_desc->streams().empty())) {
2467 remote_peer_supports_msid_ = true;
2468 }
deadbeefab9b2d12015-10-14 11:33:11 -07002469
2470 // We wait to signal new streams until we finish processing the description,
2471 // since only at that point will new streams have all their tracks.
2472 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2473
Steve Antondcc3c022017-12-22 16:02:54 -08002474 if (!IsUnifiedPlan()) {
2475 // TODO(steveanton): When removing RTP senders/receivers in response to a
2476 // rejected media section, there is some cleanup logic that expects the
2477 // voice/ video channel to still be set. But in this method the voice/video
2478 // channel would have been destroyed by the SetRemoteDescription caller
2479 // above so the cleanup that relies on them fails to run. The RemoveSenders
2480 // calls should be moved to right before the DestroyChannel calls to fix
2481 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002482
Steve Antondcc3c022017-12-22 16:02:54 -08002483 // Find all audio rtp streams and create corresponding remote AudioTracks
2484 // and MediaStreams.
2485 if (audio_content) {
2486 if (audio_content->rejected) {
2487 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2488 } else {
2489 bool default_audio_track_needed =
2490 !remote_peer_supports_msid_ &&
2491 RtpTransceiverDirectionHasSend(audio_desc->direction());
2492 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2493 default_audio_track_needed, audio_desc->type(),
2494 new_streams);
2495 }
deadbeeffaac4972015-11-12 15:33:07 -08002496 }
deadbeefab9b2d12015-10-14 11:33:11 -07002497
Steve Antondcc3c022017-12-22 16:02:54 -08002498 // Find all video rtp streams and create corresponding remote VideoTracks
2499 // and MediaStreams.
2500 if (video_content) {
2501 if (video_content->rejected) {
2502 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2503 } else {
2504 bool default_video_track_needed =
2505 !remote_peer_supports_msid_ &&
2506 RtpTransceiverDirectionHasSend(video_desc->direction());
2507 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2508 default_video_track_needed, video_desc->type(),
2509 new_streams);
2510 }
deadbeeffaac4972015-11-12 15:33:07 -08002511 }
deadbeefab9b2d12015-10-14 11:33:11 -07002512
Steve Antondcc3c022017-12-22 16:02:54 -08002513 // Update the DataChannels with the information from the remote peer.
2514 if (data_desc) {
2515 if (rtc::starts_with(data_desc->protocol().data(),
2516 cricket::kMediaProtocolRtpPrefix)) {
2517 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2518 }
deadbeefab9b2d12015-10-14 11:33:11 -07002519 }
deadbeefab9b2d12015-10-14 11:33:11 -07002520
Steve Antondcc3c022017-12-22 16:02:54 -08002521 // Iterate new_streams and notify the observer about new MediaStreams.
2522 for (size_t i = 0; i < new_streams->count(); ++i) {
2523 MediaStreamInterface* new_stream = new_streams->at(i);
2524 stats_->AddStream(new_stream);
2525 observer_->OnAddStream(
2526 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2527 }
deadbeefab9b2d12015-10-14 11:33:11 -07002528
Steve Antondcc3c022017-12-22 16:02:54 -08002529 UpdateEndedRemoteMediaStreams();
2530 }
deadbeefab9b2d12015-10-14 11:33:11 -07002531
Steve Anton8a006912017-12-04 15:25:56 -08002532 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002533}
2534
Steve Antondcc3c022017-12-22 16:02:54 -08002535RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2536 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002537 const SessionDescriptionInterface& new_session,
2538 const SessionDescriptionInterface* old_local_description,
2539 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002540 RTC_DCHECK(IsUnifiedPlan());
2541
Steve Anton7464fca2018-01-19 11:10:37 -08002542 const cricket::ContentGroup* bundle_group = nullptr;
2543 if (new_session.GetType() == SdpType::kOffer) {
2544 auto bundle_group_or_error =
2545 GetEarlyBundleGroup(*new_session.description());
2546 if (!bundle_group_or_error.ok()) {
2547 return bundle_group_or_error.MoveError();
2548 }
2549 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002550 }
Steve Antondcc3c022017-12-22 16:02:54 -08002551
Steve Antondcc3c022017-12-22 16:02:54 -08002552 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002553 for (size_t i = 0; i < new_contents.size(); ++i) {
2554 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002555 cricket::MediaType media_type = new_content.media_description()->type();
2556 seen_mids_.insert(new_content.name);
2557 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2558 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002559 const cricket::ContentInfo* old_local_content = nullptr;
2560 if (old_local_description &&
2561 i < old_local_description->description()->contents().size()) {
2562 old_local_content =
2563 &old_local_description->description()->contents()[i];
2564 }
2565 const cricket::ContentInfo* old_remote_content = nullptr;
2566 if (old_remote_description &&
2567 i < old_remote_description->description()->contents().size()) {
2568 old_remote_content =
2569 &old_remote_description->description()->contents()[i];
2570 }
Steve Antondcc3c022017-12-22 16:02:54 -08002571 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002572 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2573 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002574 if (!transceiver_or_error.ok()) {
2575 return transceiver_or_error.MoveError();
2576 }
2577 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002578 RTCError error =
2579 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2580 if (!error.ok()) {
2581 return error;
2582 }
2583 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002584 if (GetDataMid() && new_content.name != *GetDataMid()) {
2585 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002586 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2587 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002588 continue;
2589 }
2590 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2591 if (!error.ok()) {
2592 return error;
2593 }
Steve Antondcc3c022017-12-22 16:02:54 -08002594 } else {
2595 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2596 "Unknown section type.");
2597 }
2598 }
2599
2600 return RTCError::OK();
2601}
2602
2603RTCError PeerConnection::UpdateTransceiverChannel(
2604 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2605 transceiver,
2606 const cricket::ContentInfo& content,
2607 const cricket::ContentGroup* bundle_group) {
2608 RTC_DCHECK(IsUnifiedPlan());
2609 RTC_DCHECK(transceiver);
2610 cricket::BaseChannel* channel = transceiver->internal()->channel();
2611 if (content.rejected) {
2612 if (channel) {
2613 transceiver->internal()->SetChannel(nullptr);
2614 DestroyBaseChannel(channel);
2615 }
2616 } else {
2617 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002618 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002619 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002620 } else {
Steve Anton69470252018-02-09 11:43:08 -08002621 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002622 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002623 }
2624 if (!channel) {
2625 LOG_AND_RETURN_ERROR(
2626 RTCErrorType::INTERNAL_ERROR,
2627 "Failed to create channel for mid=" + content.name);
2628 }
2629 transceiver->internal()->SetChannel(channel);
2630 }
2631 }
2632 return RTCError::OK();
2633}
2634
Steve Antonfa2260d2017-12-28 16:38:23 -08002635RTCError PeerConnection::UpdateDataChannel(
2636 cricket::ContentSource source,
2637 const cricket::ContentInfo& content,
2638 const cricket::ContentGroup* bundle_group) {
2639 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002640 // If data channels are disabled, ignore this media section. CreateAnswer
2641 // will take care of rejecting it.
2642 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002643 }
2644 if (content.rejected) {
2645 DestroyDataChannel();
2646 } else {
2647 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002648 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002649 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2650 "Failed to create data channel.");
2651 }
2652 }
2653 if (source == cricket::CS_REMOTE) {
2654 const MediaContentDescription* data_desc = content.media_description();
2655 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2656 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2657 }
2658 }
2659 }
2660 return RTCError::OK();
2661}
2662
Steve Antondcc3c022017-12-22 16:02:54 -08002663RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2664PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002665 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002666 size_t mline_index,
2667 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002668 const ContentInfo* old_local_content,
2669 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002670 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002671 // If this is an offer then the m= section might be recycled. If the m=
2672 // section is being recycled (defined as: rejected in the current local or
2673 // remote description and not rejected in new description), dissociate the
2674 // currently associated RtpTransceiver by setting its mid property to null,
2675 // and discard the mapping between the transceiver and its m= section index.
2676 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2677 old_remote_content)) {
2678 // We want to dissociate the transceiver that has the rejected mid.
2679 const std::string& old_mid =
2680 (old_local_content && old_local_content->rejected)
2681 ? old_local_content->name
2682 : old_remote_content->name;
2683 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002684 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002685 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2686 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-22 16:02:54 -08002687 old_transceiver->internal()->set_mid(rtc::nullopt);
2688 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2689 }
2690 }
2691 const MediaContentDescription* media_desc = content.media_description();
2692 auto transceiver = GetAssociatedTransceiver(content.name);
2693 if (source == cricket::CS_LOCAL) {
2694 // Find the RtpTransceiver that corresponds to this m= section, using the
2695 // mapping between transceivers and m= section indices established when
2696 // creating the offer.
2697 if (!transceiver) {
2698 transceiver = GetTransceiverByMLineIndex(mline_index);
2699 }
2700 if (!transceiver) {
2701 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2702 "Unknown transceiver");
2703 }
2704 } else {
2705 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2706 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2707 // of the same type...
2708 if (!transceiver &&
2709 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2710 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2711 }
2712 // If no RtpTransceiver was found in the previous step, create one with a
2713 // recvonly direction.
2714 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002715 RTC_LOG(LS_INFO) << "Adding "
2716 << cricket::MediaTypeToString(media_desc->type())
2717 << " transceiver for MID=" << content.name
2718 << " at i=" << mline_index
2719 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002720 auto sender =
2721 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002722 std::string receiver_id;
2723 if (!media_desc->streams().empty()) {
2724 receiver_id = media_desc->streams()[0].id;
2725 } else {
2726 receiver_id = rtc::CreateRandomUuid();
2727 }
2728 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002729 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002730 transceiver->internal()->set_direction(
2731 RtpTransceiverDirection::kRecvOnly);
2732 }
2733 }
2734 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002735 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002736 LOG_AND_RETURN_ERROR(
2737 RTCErrorType::INVALID_PARAMETER,
2738 "Transceiver type does not match media description type.");
2739 }
2740 // Associate the found or created RtpTransceiver with the m= section by
2741 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2742 // section, and establish a mapping between the transceiver and the index of
2743 // the m= section.
2744 transceiver->internal()->set_mid(content.name);
2745 transceiver->internal()->set_mline_index(mline_index);
2746 return std::move(transceiver);
2747}
2748
2749rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2750PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2751 RTC_DCHECK(IsUnifiedPlan());
2752 for (auto transceiver : transceivers_) {
2753 if (transceiver->mid() == mid) {
2754 return transceiver;
2755 }
2756 }
2757 return nullptr;
2758}
2759
2760rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2761PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2762 RTC_DCHECK(IsUnifiedPlan());
2763 for (auto transceiver : transceivers_) {
2764 if (transceiver->internal()->mline_index() == mline_index) {
2765 return transceiver;
2766 }
2767 }
2768 return nullptr;
2769}
2770
2771rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2772PeerConnection::FindAvailableTransceiverToReceive(
2773 cricket::MediaType media_type) const {
2774 RTC_DCHECK(IsUnifiedPlan());
2775 // From JSEP section 5.10 (Applying a Remote Description):
2776 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2777 // the same type that were added to the PeerConnection by addTrack and are not
2778 // associated with any m= section and are not stopped, find the first such
2779 // RtpTransceiver.
2780 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002781 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002782 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2783 !transceiver->stopped()) {
2784 return transceiver;
2785 }
2786 }
2787 return nullptr;
2788}
2789
Steve Antoned10bd92017-12-05 10:52:59 -08002790const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2791 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2792 transceiver,
2793 const SessionDescriptionInterface* sdesc) const {
2794 RTC_DCHECK(transceiver);
2795 RTC_DCHECK(sdesc);
2796 if (IsUnifiedPlan()) {
2797 if (!transceiver->internal()->mid()) {
2798 // This transceiver is not associated with a media section yet.
2799 return nullptr;
2800 }
2801 return sdesc->description()->GetContentByName(
2802 *transceiver->internal()->mid());
2803 } else {
2804 // Plan B only allows at most one audio and one video section, so use the
2805 // first media section of that type.
2806 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002807 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002808 }
2809}
2810
deadbeef46c73892016-11-16 19:42:04 -08002811PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2812 return configuration_;
2813}
2814
deadbeef293e9262017-01-11 12:28:30 -08002815bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2816 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002817 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002818
Qingsi Wangfc43d112018-04-10 15:50:46 -07002819 // According to JSEP, after setLocalDescription, changing the candidate pool
2820 // size is not allowed, and changing the set of ICE servers will not result
2821 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002822 if (local_description() && configuration.ice_candidate_pool_size !=
2823 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002824 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2825 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002826 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002827 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002828
deadbeef293e9262017-01-11 12:28:30 -08002829 // The simplest (and most future-compatible) way to tell if the config was
2830 // modified in an invalid way is to copy each property we do support
2831 // modifying, then use operator==. There are far more properties we don't
2832 // support modifying than those we do, and more could be added.
2833 RTCConfiguration modified_config = configuration_;
2834 modified_config.servers = configuration.servers;
2835 modified_config.type = configuration.type;
2836 modified_config.ice_candidate_pool_size =
2837 configuration.ice_candidate_pool_size;
2838 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002839 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002840 modified_config.ice_check_interval_strong_connectivity =
2841 configuration.ice_check_interval_strong_connectivity;
2842 modified_config.ice_check_interval_weak_connectivity =
2843 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002844 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2845 modified_config.ice_unwritable_min_checks =
2846 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002847 modified_config.stun_candidate_keepalive_interval =
2848 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002849 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002850 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002851 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002852 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002853 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2854 }
2855
Steve Anton038834f2017-07-14 15:59:59 -07002856 // Validate the modified configuration.
2857 RTCError validate_error = ValidateConfiguration(modified_config);
2858 if (!validate_error.ok()) {
2859 return SafeSetError(std::move(validate_error), error);
2860 }
2861
deadbeef293e9262017-01-11 12:28:30 -08002862 // Note that this isn't possible through chromium, since it's an unsigned
2863 // short in WebIDL.
2864 if (configuration.ice_candidate_pool_size < 0 ||
2865 configuration.ice_candidate_pool_size > UINT16_MAX) {
2866 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2867 }
2868
2869 // Parse ICE servers before hopping to network thread.
2870 cricket::ServerAddresses stun_servers;
2871 std::vector<cricket::RelayServerConfig> turn_servers;
2872 RTCErrorType parse_error =
2873 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2874 if (parse_error != RTCErrorType::NONE) {
2875 return SafeSetError(parse_error, error);
2876 }
2877
2878 // In theory this shouldn't fail.
2879 if (!network_thread()->Invoke<bool>(
2880 RTC_FROM_HERE,
2881 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2882 stun_servers, turn_servers, modified_config.type,
2883 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002884 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002885 modified_config.turn_customizer,
2886 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002887 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002888 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2889 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002890
deadbeefd1a38b52016-12-10 13:15:33 -08002891 // As described in JSEP, calling setConfiguration with new ICE servers or
2892 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2893 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002894 if (modified_config.servers != configuration_.servers ||
2895 modified_config.type != configuration_.type ||
2896 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002897 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002898 }
skvladd1f5fda2017-02-03 16:54:05 -08002899
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002900 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002901
deadbeef293e9262017-01-11 12:28:30 -08002902 configuration_ = modified_config;
2903 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002904}
2905
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002906bool PeerConnection::AddIceCandidate(
2907 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002908 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002909 if (IsClosed()) {
2910 return false;
2911 }
Steve Antond25da372017-11-06 14:50:29 -08002912
2913 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002914 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002915 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002916 return false;
2917 }
2918
2919 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002920 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08002921 return false;
2922 }
2923
2924 bool valid = false;
2925 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2926 if (!valid) {
2927 return false;
2928 }
2929
2930 // Add this candidate to the remote session description.
2931 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002932 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002933 return false;
2934 }
2935
2936 if (ready) {
2937 return UseCandidate(ice_candidate);
2938 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002939 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002940 return true;
2941 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002942}
2943
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002944bool PeerConnection::RemoveIceCandidates(
2945 const std::vector<cricket::Candidate>& candidates) {
2946 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002947 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002948 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002949 "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002950 return false;
2951 }
2952
2953 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002954 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002955 return false;
2956 }
2957
2958 size_t number_removed =
2959 mutable_remote_description()->RemoveCandidates(candidates);
2960 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002961 RTC_LOG(LS_ERROR)
2962 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002963 "Requested "
2964 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002965 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002966 }
2967
2968 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07002969 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
2970 if (!error.ok()) {
2971 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: "
2972 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08002973 }
2974 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002975}
2976
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002977void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002978 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wangfc43d112018-04-10 15:50:46 -07002979 network_thread()->Invoke<void>(
2980 RTC_FROM_HERE,
2981 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002982 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002983 if (uma_observer_) {
Qingsi Wangfc43d112018-04-10 15:50:46 -07002984 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002985 uma_observer_->IncrementEnumCounter(
2986 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2987 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002988 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002989 uma_observer_->IncrementEnumCounter(
2990 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2991 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002992 }
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002993 // Send information about the requested SDP semantics.
2994 switch (configuration_.sdp_semantics) {
2995 case SdpSemantics::kDefault:
2996 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
2997 kSdpSemanticRequestDefault,
2998 kSdpSemanticRequestMax);
2999
3000 break;
3001 case SdpSemantics::kPlanB:
3002 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
3003 kSdpSemanticRequestPlanB,
3004 kSdpSemanticRequestMax);
3005 break;
3006 case SdpSemantics::kUnifiedPlan:
3007 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticRequested,
3008 kSdpSemanticRequestUnifiedPlan,
3009 kSdpSemanticRequestMax);
3010 break;
3011 default:
3012 RTC_NOTREACHED();
3013 }
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003014 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003015}
3016
Qingsi Wangfc43d112018-04-10 15:50:46 -07003017void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3018 RTC_DCHECK(network_thread()->IsCurrent());
3019 uma_observer_ = observer;
3020 if (transport_controller()) {
3021 transport_controller()->SetMetricsObserver(uma_observer_);
3022 }
3023
3024 for (auto transceiver : transceivers_) {
3025 auto* channel = transceiver->internal()->channel();
3026 if (channel) {
3027 channel->SetMetricsObserver(uma_observer_);
3028 }
3029 }
3030
3031 if (uma_observer_) {
3032 port_allocator_->SetMetricsObserver(uma_observer_);
3033 }
3034}
3035
zstein4b979802017-06-02 14:37:37 -07003036RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003037 if (!worker_thread()->IsCurrent()) {
3038 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07003039 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
3040 }
3041
3042 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
3043 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
3044 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
3045 if (has_min && *bitrate.min_bitrate_bps < 0) {
3046 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3047 "min_bitrate_bps <= 0");
3048 }
3049 if (has_current) {
3050 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
3051 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3052 "current_bitrate_bps < min_bitrate_bps");
3053 } else if (*bitrate.current_bitrate_bps < 0) {
3054 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3055 "curent_bitrate_bps < 0");
3056 }
3057 }
3058 if (has_max) {
3059 if (has_current &&
3060 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
3061 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3062 "max_bitrate_bps < current_bitrate_bps");
3063 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3064 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3065 "max_bitrate_bps < min_bitrate_bps");
3066 } else if (*bitrate.max_bitrate_bps < 0) {
3067 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3068 "max_bitrate_bps < 0");
3069 }
3070 }
3071
Sebastian Janssonfc8d26b2018-02-21 09:52:06 +01003072 BitrateConstraintsMask mask;
zstein4b979802017-06-02 14:37:37 -07003073 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
3074 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
3075 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
3076
3077 RTC_DCHECK(call_.get());
Sebastian Jansson8f83b422018-02-21 13:07:13 +01003078 call_->GetTransportControllerSend()->SetClientBitratePreferences(mask);
zstein4b979802017-06-02 14:37:37 -07003079
3080 return RTCError::OK();
3081}
3082
Alex Narest78609d52017-10-20 10:37:47 +02003083void PeerConnection::SetBitrateAllocationStrategy(
3084 std::unique_ptr<rtc::BitrateAllocationStrategy>
3085 bitrate_allocation_strategy) {
3086 rtc::Thread* worker_thread = factory_->worker_thread();
3087 if (!worker_thread->IsCurrent()) {
3088 rtc::BitrateAllocationStrategy* strategy_raw =
3089 bitrate_allocation_strategy.release();
3090 auto functor = [this, strategy_raw]() {
3091 call_->SetBitrateAllocationStrategy(
3092 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3093 };
3094 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3095 return;
3096 }
3097 RTC_DCHECK(call_.get());
3098 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3099}
3100
henrika5f6bf242017-11-01 11:06:56 +01003101void PeerConnection::SetAudioPlayout(bool playout) {
3102 if (!worker_thread()->IsCurrent()) {
3103 worker_thread()->Invoke<void>(
3104 RTC_FROM_HERE,
3105 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3106 return;
3107 }
3108 auto audio_state =
3109 factory_->channel_manager()->media_engine()->GetAudioState();
3110 audio_state->SetPlayout(playout);
3111}
3112
3113void PeerConnection::SetAudioRecording(bool recording) {
3114 if (!worker_thread()->IsCurrent()) {
3115 worker_thread()->Invoke<void>(
3116 RTC_FROM_HERE,
3117 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3118 return;
3119 }
3120 auto audio_state =
3121 factory_->channel_manager()->media_engine()->GetAudioState();
3122 audio_state->SetRecording(recording);
3123}
3124
Steve Anton8c0f7a72017-10-03 10:03:10 -07003125std::unique_ptr<rtc::SSLCertificate>
3126PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003127 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3128 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003129 return nullptr;
3130 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003131 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003132}
3133
Zhi Huang70b820f2018-01-27 14:16:15 -08003134std::unique_ptr<rtc::SSLCertChain>
3135PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003136 auto audio_transceiver = GetFirstAudioTransceiver();
3137 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003138 return nullptr;
3139 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003140 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003141 audio_transceiver->internal()->channel()->transport_name());
3142}
3143
3144rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3145PeerConnection::GetFirstAudioTransceiver() const {
3146 for (auto transceiver : transceivers_) {
3147 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3148 return transceiver;
3149 }
3150 }
3151 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003152}
3153
ivoc14d5dbe2016-07-04 07:06:55 -07003154bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3155 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003156 // TODO(eladalon): It would be better to not allow negative values into PC.
3157 const size_t max_size = (max_size_bytes < 0)
3158 ? RtcEventLog::kUnlimitedOutput
3159 : rtc::saturated_cast<size_t>(max_size_bytes);
3160 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003161 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3162 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003163}
3164
Bjorn Tereliusde939432017-11-20 17:38:14 +01003165bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3166 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003167 // TODO(eladalon): In C++14, this can be done with a lambda.
3168 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003169 bool operator()() {
3170 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3171 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003172 PeerConnection* const pc;
3173 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003174 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003175 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003176 return worker_thread()->Invoke<bool>(
3177 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003178}
3179
3180void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003181 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003182 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3183}
3184
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003185const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003186 return pending_local_description_ ? pending_local_description_.get()
3187 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003188}
3189
3190const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003191 return pending_remote_description_ ? pending_remote_description_.get()
3192 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193}
3194
deadbeeffe4a8a42016-12-20 17:56:17 -08003195const SessionDescriptionInterface* PeerConnection::current_local_description()
3196 const {
Steve Anton75737c02017-11-06 10:37:17 -08003197 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003198}
3199
3200const SessionDescriptionInterface* PeerConnection::current_remote_description()
3201 const {
Steve Anton75737c02017-11-06 10:37:17 -08003202 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003203}
3204
3205const SessionDescriptionInterface* PeerConnection::pending_local_description()
3206 const {
Steve Anton75737c02017-11-06 10:37:17 -08003207 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003208}
3209
3210const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3211 const {
Steve Anton75737c02017-11-06 10:37:17 -08003212 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003213}
3214
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003215void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003216 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217 // Update stats here so that we have the most recent stats for tracks and
3218 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003219 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003220
Steve Anton75737c02017-11-06 10:37:17 -08003221 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003222
Steve Anton8af21862017-12-15 11:20:13 -08003223 for (auto transceiver : transceivers_) {
3224 transceiver->Stop();
3225 }
3226 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003227
Qingsi Wang93a84392018-01-30 17:13:09 -08003228 // The event log is used in the transport controller, which must be outlived
3229 // by the former. CreateOffer by the peer connection is implemented
3230 // asynchronously and if the peer connection is closed without resetting the
3231 // WebRTC session description factory, the session description factory would
3232 // call the transport controller.
3233 webrtc_session_desc_factory_.reset();
3234 transport_controller_.reset();
3235
deadbeef42a42632017-03-10 15:18:00 -08003236 network_thread()->Invoke<void>(
3237 RTC_FROM_HERE,
3238 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3239 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003240
Steve Anton978b8762017-09-29 12:15:02 -07003241 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003242 call_.reset();
3243 // The event log must outlive call (and any other object that uses it).
3244 event_log_.reset();
3245 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246}
3247
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003248void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003249 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003250 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3251 SetSessionDescriptionMsg* param =
3252 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3253 param->observer->OnSuccess();
3254 delete param;
3255 break;
3256 }
3257 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3258 SetSessionDescriptionMsg* param =
3259 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003260 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261 delete param;
3262 break;
3263 }
deadbeefab9b2d12015-10-14 11:33:11 -07003264 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3265 CreateSessionDescriptionMsg* param =
3266 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003267 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003268 delete param;
3269 break;
3270 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003271 case MSG_GETSTATS: {
3272 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003273 StatsReports reports;
3274 stats_->GetStats(param->track, &reports);
3275 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276 delete param;
3277 break;
3278 }
deadbeefbd292462015-12-14 18:15:29 -08003279 case MSG_FREE_DATACHANNELS: {
3280 sctp_data_channels_to_free_.clear();
3281 break;
3282 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003283 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003284 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003285 break;
3286 }
3287}
3288
Steve Antonafb0bb72018-02-20 11:35:37 -08003289cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3290 RTC_DCHECK(!IsUnifiedPlan());
3291 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3292 GetAudioTransceiver()->internal()->channel());
3293 if (voice_channel) {
3294 return voice_channel->media_channel();
3295 } else {
3296 return nullptr;
3297 }
3298}
3299
3300cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3301 RTC_DCHECK(!IsUnifiedPlan());
3302 auto* video_channel = static_cast<cricket::VideoChannel*>(
3303 GetVideoTransceiver()->internal()->channel());
3304 if (video_channel) {
3305 return video_channel->media_channel();
3306 } else {
3307 return nullptr;
3308 }
3309}
3310
Steve Anton4171afb2017-11-20 10:20:22 -08003311void PeerConnection::CreateAudioReceiver(
3312 MediaStreamInterface* stream,
3313 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003314 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3315 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003316 auto* audio_receiver = new AudioRtpReceiver(
3317 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003318 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003319 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3320 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3321 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003322 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003323 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324}
3325
Steve Anton4171afb2017-11-20 10:20:22 -08003326void PeerConnection::CreateVideoReceiver(
3327 MediaStreamInterface* stream,
3328 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003329 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3330 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003331 auto* video_receiver = new VideoRtpReceiver(
3332 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003333 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003334 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3335 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3336 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003337 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003338 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339}
3340
deadbeef70ab1a12015-09-28 16:53:55 -07003341// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3342// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003343rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003344 const RtpSenderInfo& remote_sender_info) {
3345 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3346 if (!receiver) {
3347 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3348 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003349 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003350 }
Steve Anton4171afb2017-11-20 10:20:22 -08003351 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3352 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3353 } else {
3354 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3355 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003356 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003359void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3360 MediaStreamInterface* stream) {
3361 RTC_DCHECK(!IsClosed());
3362 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003363 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003364 // We already have a sender for this track, so just change the stream_id
3365 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003366 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003367 return;
3368 }
3369
3370 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003371 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003372 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003373 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003374 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003375 // If the sender has already been configured in SDP, we call SetSsrc,
3376 // which will connect the sender to the underlying transport. This can
3377 // occur if a local session description that contains the ID of the sender
3378 // is set before AddStream is called. It can also occur if the local
3379 // session description is not changed and RemoveStream is called, and
3380 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003381 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003382 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003383 if (sender_info) {
3384 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003385 }
3386}
3387
3388// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3389// indefinitely, when we have unified plan SDP.
3390void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3391 MediaStreamInterface* stream) {
3392 RTC_DCHECK(!IsClosed());
3393 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003394 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003395 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3396 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003397 return;
3398 }
Steve Anton4171afb2017-11-20 10:20:22 -08003399 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003400}
3401
3402void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3403 MediaStreamInterface* stream) {
3404 RTC_DCHECK(!IsClosed());
3405 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003406 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003407 // We already have a sender for this track, so just change the stream_id
3408 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003409 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003410 return;
3411 }
3412
3413 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003414 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003415 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003416 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003417 GetVideoTransceiver()->internal()->AddSender(new_sender);
3418 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003419 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003420 if (sender_info) {
3421 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003422 }
3423}
3424
3425void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3426 MediaStreamInterface* stream) {
3427 RTC_DCHECK(!IsClosed());
3428 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003429 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003430 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3431 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003432 return;
3433 }
Steve Anton4171afb2017-11-20 10:20:22 -08003434 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003435}
3436
Steve Antonba818672017-11-06 10:21:57 -08003437void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003438 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003439 if (ice_connection_state_ == new_state) {
3440 return;
3441 }
3442
deadbeefcbecd352015-09-23 11:50:27 -07003443 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003444 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003445 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003446 return;
3447 }
Steve Antonba818672017-11-06 10:21:57 -08003448
Mirko Bonadei675513b2017-11-09 11:09:25 +01003449 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3450 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003451 RTC_DCHECK(ice_connection_state_ !=
3452 PeerConnectionInterface::kIceConnectionClosed);
3453
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003454 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003455 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003456}
3457
3458void PeerConnection::OnIceGatheringChange(
3459 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003460 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003461 if (IsClosed()) {
3462 return;
3463 }
3464 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003465 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003466}
3467
jbauch81bf7b02017-03-25 08:31:12 -07003468void PeerConnection::OnIceCandidate(
3469 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003470 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003471 if (IsClosed()) {
3472 return;
3473 }
jbauch81bf7b02017-03-25 08:31:12 -07003474 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475}
3476
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003477void PeerConnection::OnIceCandidatesRemoved(
3478 const std::vector<cricket::Candidate>& candidates) {
3479 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003480 if (IsClosed()) {
3481 return;
3482 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003483 observer_->OnIceCandidatesRemoved(candidates);
3484}
3485
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003486void PeerConnection::ChangeSignalingState(
3487 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003488 RTC_DCHECK(signaling_thread()->IsCurrent());
3489 if (signaling_state_ == signaling_state) {
3490 return;
3491 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003492 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3493 << GetSignalingStateString(signaling_state_)
3494 << " New state: "
3495 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496 signaling_state_ = signaling_state;
3497 if (signaling_state == kClosed) {
3498 ice_connection_state_ = kIceConnectionClosed;
3499 observer_->OnIceConnectionChange(ice_connection_state_);
3500 if (ice_gathering_state_ != kIceGatheringComplete) {
3501 ice_gathering_state_ = kIceGatheringComplete;
3502 observer_->OnIceGatheringChange(ice_gathering_state_);
3503 }
3504 }
3505 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506}
3507
deadbeefeb459812015-12-15 19:24:43 -08003508void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3509 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003510 if (IsClosed()) {
3511 return;
3512 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003513 AddAudioTrack(track, stream);
3514 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003515}
3516
deadbeefeb459812015-12-15 19:24:43 -08003517void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3518 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003519 if (IsClosed()) {
3520 return;
3521 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003522 RemoveAudioTrack(track, stream);
3523 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003524}
3525
3526void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3527 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003528 if (IsClosed()) {
3529 return;
3530 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003531 AddVideoTrack(track, stream);
3532 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003533}
3534
3535void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3536 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003537 if (IsClosed()) {
3538 return;
3539 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003540 RemoveVideoTrack(track, stream);
3541 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003542}
3543
Henrik Boström31638672017-11-23 17:48:32 +01003544void PeerConnection::PostSetSessionDescriptionSuccess(
3545 SetSessionDescriptionObserver* observer) {
3546 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3547 signaling_thread()->Post(RTC_FROM_HERE, this,
3548 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3549}
3550
deadbeefab9b2d12015-10-14 11:33:11 -07003551void PeerConnection::PostSetSessionDescriptionFailure(
3552 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003553 RTCError&& error) {
3554 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003555 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003556 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003557 signaling_thread()->Post(RTC_FROM_HERE, this,
3558 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003559}
3560
3561void PeerConnection::PostCreateSessionDescriptionFailure(
3562 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003563 RTCError error) {
3564 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003565 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003566 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003567 signaling_thread()->Post(RTC_FROM_HERE, this,
3568 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003569}
3570
zhihuang1c378ed2017-08-17 14:10:50 -07003571void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003572 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003573 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003574 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003575
Steve Antondcc3c022017-12-22 16:02:54 -08003576 if (IsUnifiedPlan()) {
3577 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3578 } else {
3579 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3580 }
3581
Steve Antonfa2260d2017-12-28 16:38:23 -08003582 // Intentionally unset the data channel type for RTP data channel with the
3583 // second condition. Otherwise the RTP data channels would be successfully
3584 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3585 // when building with chromium. We want to leave RTP data channels broken, so
3586 // people won't try to use them.
3587 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3588 session_options->data_channel_type = data_channel_type();
3589 }
3590
Steve Antondcc3c022017-12-22 16:02:54 -08003591 // Apply ICE restart flag and renomination flag.
3592 for (auto& options : session_options->media_description_options) {
3593 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3594 options.transport_options.enable_ice_renomination =
3595 configuration_.enable_ice_renomination;
3596 }
3597
3598 session_options->rtcp_cname = rtcp_cname_;
3599 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003600 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003601}
3602
3603void PeerConnection::GetOptionsForPlanBOffer(
3604 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3605 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003606 // Figure out transceiver directional preferences.
3607 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3608 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3609
3610 // By default, generate sendrecv/recvonly m= sections.
3611 bool recv_audio = true;
3612 bool recv_video = true;
3613
3614 // By default, only offer a new m= section if we have media to send with it.
3615 bool offer_new_audio_description = send_audio;
3616 bool offer_new_video_description = send_video;
3617 bool offer_new_data_description = HasDataChannels();
3618
3619 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003620 if (offer_answer_options.offer_to_receive_audio !=
3621 RTCOfferAnswerOptions::kUndefined) {
3622 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003623 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003624 offer_new_audio_description ||
3625 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003626 }
Steve Antondcc3c022017-12-22 16:02:54 -08003627 if (offer_answer_options.offer_to_receive_video !=
3628 RTCOfferAnswerOptions::kUndefined) {
3629 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003630 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003631 offer_new_video_description ||
3632 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003633 }
3634
3635 rtc::Optional<size_t> audio_index;
3636 rtc::Optional<size_t> video_index;
3637 rtc::Optional<size_t> data_index;
3638 // If a current description exists, generate m= sections in the same order,
3639 // using the first audio/video/data section that appears and rejecting
3640 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003641 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003642 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003643 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003644 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3645 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3646 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003647 }
3648
zhihuang1c378ed2017-08-17 14:10:50 -07003649 // Add audio/video/data m= sections to the end if needed.
3650 if (!audio_index && offer_new_audio_description) {
3651 session_options->media_description_options.push_back(
3652 cricket::MediaDescriptionOptions(
3653 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003654 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3655 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003656 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003657 }
zhihuang1c378ed2017-08-17 14:10:50 -07003658 if (!video_index && offer_new_video_description) {
3659 session_options->media_description_options.push_back(
3660 cricket::MediaDescriptionOptions(
3661 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003662 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3663 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003664 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003665 }
zhihuang1c378ed2017-08-17 14:10:50 -07003666 if (!data_index && offer_new_data_description) {
3667 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003668 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003669 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003670 }
3671
3672 cricket::MediaDescriptionOptions* audio_media_description_options =
3673 !audio_index ? nullptr
3674 : &session_options->media_description_options[*audio_index];
3675 cricket::MediaDescriptionOptions* video_media_description_options =
3676 !video_index ? nullptr
3677 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003678
Steve Anton4171afb2017-11-20 10:20:22 -08003679 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003680 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003681}
3682
3683// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3684// and return a reference to it.
3685// Generated MIDs should be no more than 3 bytes long to take up less space in
3686// the RTP packet.
3687static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3688 RTC_DCHECK(used_mids);
3689 // We're boring: just generate MIDs 0, 1, 2, ...
3690 size_t i = 0;
3691 std::set<std::string>::iterator it;
3692 bool inserted;
3693 do {
3694 std::string mid = rtc::ToString(i++);
3695 auto insert_result = used_mids->insert(mid);
3696 it = insert_result.first;
3697 inserted = insert_result.second;
3698 } while (!inserted);
3699 return *it;
3700}
3701
3702static cricket::MediaDescriptionOptions
3703GetMediaDescriptionOptionsForTransceiver(
3704 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3705 transceiver,
3706 const std::string& mid) {
3707 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003708 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003709 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003710 // This behavior is specified in JSEP. The gist is that:
3711 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3712 // sendrecv.
3713 // 2. If the MSID is included, then it must be included in any subsequent
3714 // offer/answer exactly the same until the RtpTransceiver is stopped.
3715 if (!transceiver->stopped() &&
3716 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3717 transceiver->internal()->has_ever_been_used_to_send())) {
3718 cricket::SenderOptions sender_options;
3719 sender_options.track_id = transceiver->sender()->id();
3720 sender_options.stream_ids = transceiver->sender()->stream_ids();
3721 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3722 // set in the RTP parameters when the transceiver was added.
3723 sender_options.num_sim_layers = 1;
3724 media_description_options.sender_options.push_back(sender_options);
3725 }
Steve Antondcc3c022017-12-22 16:02:54 -08003726 return media_description_options;
3727}
3728
3729void PeerConnection::GetOptionsForUnifiedPlanOffer(
3730 const RTCOfferAnswerOptions& offer_answer_options,
3731 cricket::MediaSessionOptions* session_options) {
3732 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3733 // Offers) and 5.2.2 (Subsequent Offers).
3734 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3735 const ContentInfos& local_contents =
3736 (local_description() ? local_description()->description()->contents()
3737 : ContentInfos());
3738 const ContentInfos& remote_contents =
3739 (remote_description() ? remote_description()->description()->contents()
3740 : ContentInfos());
3741 // The mline indices that can be recycled. New transceivers should reuse these
3742 // slots first.
3743 std::queue<size_t> recycleable_mline_indices;
3744 // Track the MIDs used in previous offer/answer exchanges and the current
3745 // offer so that new, unique MIDs are generated.
3746 std::set<std::string> used_mids = seen_mids_;
3747 // First, go through each media section that exists in either the local or
3748 // remote description and generate a media section in this offer for the
3749 // associated transceiver. If a media section can be recycled, generate a
3750 // default, rejected media section here that can be later overwritten.
3751 for (size_t i = 0;
3752 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3753 // Either |local_content| or |remote_content| is non-null.
3754 const ContentInfo* local_content =
3755 (i < local_contents.size() ? &local_contents[i] : nullptr);
3756 const ContentInfo* remote_content =
3757 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3758 bool had_been_rejected = (local_content && local_content->rejected) ||
3759 (remote_content && remote_content->rejected);
3760 const std::string& mid =
3761 (local_content ? local_content->name : remote_content->name);
3762 cricket::MediaType media_type =
3763 (local_content ? local_content->media_description()->type()
3764 : remote_content->media_description()->type());
3765 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3766 media_type == cricket::MEDIA_TYPE_VIDEO) {
3767 auto transceiver = GetAssociatedTransceiver(mid);
3768 RTC_CHECK(transceiver);
3769 // A media section is considered eligible for recycling if it is marked as
3770 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003771 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003772 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003773 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3774 RtpTransceiverDirection::kInactive,
3775 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003776 recycleable_mline_indices.push(i);
3777 } else {
3778 session_options->media_description_options.push_back(
3779 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3780 // CreateOffer shouldn't really cause any state changes in
3781 // PeerConnection, but we need a way to match new transceivers to new
3782 // media sections in SetLocalDescription and JSEP specifies this is done
3783 // by recording the index of the media section generated for the
3784 // transceiver in the offer.
3785 transceiver->internal()->set_mline_index(i);
3786 }
3787 } else {
3788 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003789 RTC_CHECK(GetDataMid());
3790 if (had_been_rejected || mid != *GetDataMid()) {
3791 session_options->media_description_options.push_back(
3792 GetMediaDescriptionOptionsForRejectedData(mid));
3793 } else {
3794 session_options->media_description_options.push_back(
3795 GetMediaDescriptionOptionsForActiveData(mid));
3796 }
Steve Antondcc3c022017-12-22 16:02:54 -08003797 }
3798 }
3799 // Next, look for transceivers that are newly added (that is, are not stopped
3800 // and not associated). Reuse media sections marked as recyclable first,
3801 // otherwise append to the end of the offer. New media sections should be
3802 // added in the order they were added to the PeerConnection.
3803 for (auto transceiver : transceivers_) {
3804 if (transceiver->mid() || transceiver->stopped()) {
3805 continue;
3806 }
3807 size_t mline_index;
3808 if (!recycleable_mline_indices.empty()) {
3809 mline_index = recycleable_mline_indices.front();
3810 recycleable_mline_indices.pop();
3811 session_options->media_description_options[mline_index] =
3812 GetMediaDescriptionOptionsForTransceiver(transceiver,
3813 AllocateMid(&used_mids));
3814 } else {
3815 mline_index = session_options->media_description_options.size();
3816 session_options->media_description_options.push_back(
3817 GetMediaDescriptionOptionsForTransceiver(transceiver,
3818 AllocateMid(&used_mids)));
3819 }
3820 // See comment above for why CreateOffer changes the transceiver's state.
3821 transceiver->internal()->set_mline_index(mline_index);
3822 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003823 // Lastly, add a m-section if we have local data channels and an m section
3824 // does not already exist.
3825 if (!GetDataMid() && HasDataChannels()) {
3826 session_options->media_description_options.push_back(
3827 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3828 }
Steve Antondcc3c022017-12-22 16:02:54 -08003829}
3830
3831void PeerConnection::GetOptionsForAnswer(
3832 const RTCOfferAnswerOptions& offer_answer_options,
3833 cricket::MediaSessionOptions* session_options) {
3834 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3835
3836 if (IsUnifiedPlan()) {
3837 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3838 } else {
3839 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3840 }
3841
Steve Antonfa2260d2017-12-28 16:38:23 -08003842 // Intentionally unset the data channel type for RTP data channel. Otherwise
3843 // the RTP data channels would be successfully negotiated by default and the
3844 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3845 // We want to leave RTP data channels broken, so people won't try to use them.
3846 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3847 session_options->data_channel_type = data_channel_type();
3848 }
3849
Steve Antondcc3c022017-12-22 16:02:54 -08003850 // Apply ICE renomination flag.
3851 for (auto& options : session_options->media_description_options) {
3852 options.transport_options.enable_ice_renomination =
3853 configuration_.enable_ice_renomination;
3854 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003855
3856 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003857 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003858 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003859}
3860
Steve Antondcc3c022017-12-22 16:02:54 -08003861void PeerConnection::GetOptionsForPlanBAnswer(
3862 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003863 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003864 // Figure out transceiver directional preferences.
3865 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3866 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3867
3868 // By default, generate sendrecv/recvonly m= sections. The direction is also
3869 // restricted by the direction in the offer.
3870 bool recv_audio = true;
3871 bool recv_video = true;
3872
3873 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003874 if (offer_answer_options.offer_to_receive_audio !=
3875 RTCOfferAnswerOptions::kUndefined) {
3876 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003877 }
Steve Antondcc3c022017-12-22 16:02:54 -08003878 if (offer_answer_options.offer_to_receive_video !=
3879 RTCOfferAnswerOptions::kUndefined) {
3880 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003881 }
3882
3883 rtc::Optional<size_t> audio_index;
3884 rtc::Optional<size_t> video_index;
3885 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003886
3887 // Generate m= sections that match those in the offer.
3888 // Note that mediasession.cc will handle intersection our preferred
3889 // direction with the offered direction.
3890 GenerateMediaDescriptionOptions(
3891 remote_description(),
3892 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3893 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3894 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003895
3896 cricket::MediaDescriptionOptions* audio_media_description_options =
3897 !audio_index ? nullptr
3898 : &session_options->media_description_options[*audio_index];
3899 cricket::MediaDescriptionOptions* video_media_description_options =
3900 !video_index ? nullptr
3901 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003902
Steve Anton4171afb2017-11-20 10:20:22 -08003903 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003904 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003905}
zhihuangaf388472016-11-02 16:49:48 -07003906
Steve Antondcc3c022017-12-22 16:02:54 -08003907void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3908 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3909 cricket::MediaSessionOptions* session_options) {
3910 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3911 // Answers) and 5.3.2 (Subsequent Answers).
3912 RTC_DCHECK(remote_description());
3913 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3914 for (const ContentInfo& content :
3915 remote_description()->description()->contents()) {
3916 cricket::MediaType media_type = content.media_description()->type();
3917 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3918 media_type == cricket::MEDIA_TYPE_VIDEO) {
3919 auto transceiver = GetAssociatedTransceiver(content.name);
3920 RTC_CHECK(transceiver);
3921 session_options->media_description_options.push_back(
3922 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3923 } else {
3924 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003925 // Reject all data sections if data channels are disabled.
3926 // Reject a data section if it has already been rejected.
3927 // Reject all data sections except for the first one.
3928 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3929 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003930 session_options->media_description_options.push_back(
3931 GetMediaDescriptionOptionsForRejectedData(content.name));
3932 } else {
3933 session_options->media_description_options.push_back(
3934 GetMediaDescriptionOptionsForActiveData(content.name));
3935 }
Steve Antondcc3c022017-12-22 16:02:54 -08003936 }
3937 }
htaa2a49d92016-03-04 02:51:39 -08003938}
3939
zhihuang1c378ed2017-08-17 14:10:50 -07003940void PeerConnection::GenerateMediaDescriptionOptions(
3941 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003942 RtpTransceiverDirection audio_direction,
3943 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003944 rtc::Optional<size_t>* audio_index,
3945 rtc::Optional<size_t>* video_index,
3946 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003947 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003948 for (const cricket::ContentInfo& content :
3949 session_desc->description()->contents()) {
3950 if (IsAudioContent(&content)) {
3951 // If we already have an audio m= section, reject this extra one.
3952 if (*audio_index) {
3953 session_options->media_description_options.push_back(
3954 cricket::MediaDescriptionOptions(
3955 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003956 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003957 } else {
3958 session_options->media_description_options.push_back(
3959 cricket::MediaDescriptionOptions(
3960 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003961 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003962 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003963 }
3964 } else if (IsVideoContent(&content)) {
3965 // If we already have an video m= section, reject this extra one.
3966 if (*video_index) {
3967 session_options->media_description_options.push_back(
3968 cricket::MediaDescriptionOptions(
3969 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003970 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003971 } else {
3972 session_options->media_description_options.push_back(
3973 cricket::MediaDescriptionOptions(
3974 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003975 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003976 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003977 }
3978 } else {
3979 RTC_DCHECK(IsDataContent(&content));
3980 // If we already have an data m= section, reject this extra one.
3981 if (*data_index) {
3982 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003983 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003984 } else {
3985 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003986 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003987 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003988 }
3989 }
htaa2a49d92016-03-04 02:51:39 -08003990 }
deadbeefab9b2d12015-10-14 11:33:11 -07003991}
3992
Steve Antonfa2260d2017-12-28 16:38:23 -08003993cricket::MediaDescriptionOptions
3994PeerConnection::GetMediaDescriptionOptionsForActiveData(
3995 const std::string& mid) const {
3996 // Direction for data sections is meaningless, but legacy endpoints might
3997 // expect sendrecv.
3998 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
3999 RtpTransceiverDirection::kSendRecv,
4000 /*stopped=*/false);
4001 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4002 return options;
4003}
4004
4005cricket::MediaDescriptionOptions
4006PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4007 const std::string& mid) const {
4008 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4009 RtpTransceiverDirection::kInactive,
4010 /*stopped=*/true);
4011 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4012 return options;
4013}
4014
4015rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4016 switch (data_channel_type_) {
4017 case cricket::DCT_RTP:
4018 if (!rtp_data_channel_) {
4019 return rtc::nullopt;
4020 }
4021 return rtp_data_channel_->content_name();
4022 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004023 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004024 default:
4025 return rtc::nullopt;
4026 }
4027}
4028
Steve Anton4171afb2017-11-20 10:20:22 -08004029void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4030 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4031 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004032 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004033}
4034
Steve Anton4171afb2017-11-20 10:20:22 -08004035void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004036 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004037 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004038 cricket::MediaType media_type,
4039 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004040 RTC_DCHECK(!IsUnifiedPlan());
4041
Steve Anton4171afb2017-11-20 10:20:22 -08004042 std::vector<RtpSenderInfo>* current_senders =
4043 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004044
Steve Anton4171afb2017-11-20 10:20:22 -08004045 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004046 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004047 for (auto sender_it = current_senders->begin();
4048 sender_it != current_senders->end();
4049 /* incremented manually */) {
4050 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004051 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004052 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004053 std::string params_stream_id;
4054 if (params) {
4055 params_stream_id =
4056 (!params->first_stream_id().empty() ? params->first_stream_id()
4057 : kDefaultStreamId);
4058 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004059 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004060 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004061 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004062 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004063 sender_exists) {
4064 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004065 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004066 OnRemoteSenderRemoved(info, media_type);
4067 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004068 }
4069 }
4070
Steve Anton4171afb2017-11-20 10:20:22 -08004071 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004072 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004073 if (!params.has_ssrcs()) {
4074 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4075 // sender, this means it is coming from a Unified Plan endpoint,so we just
4076 // create a default.
4077 default_sender_needed = true;
4078 break;
4079 }
4080
Seth Hampson845e8782018-03-02 11:34:10 -08004081 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004082 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004083 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4084 // not supported in Plan B, we just take the first here and create the
4085 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004086 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004087 (!params.first_stream_id().empty() ? params.first_stream_id()
4088 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004089 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004090 uint32_t ssrc = params.first_ssrc();
4091
4092 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004093 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004094 if (!stream) {
4095 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004096 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004097 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004098 remote_streams_->AddStream(stream);
4099 new_streams->AddStream(stream);
4100 }
4101
Steve Anton4171afb2017-11-20 10:20:22 -08004102 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004103 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004104 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004105 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004106 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004107 }
4108 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004109
Steve Anton4171afb2017-11-20 10:20:22 -08004110 // Add default sender if necessary.
4111 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004112 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004113 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004114 if (!default_stream) {
4115 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004116 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004117 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004118 remote_streams_->AddStream(default_stream);
4119 new_streams->AddStream(default_stream);
4120 }
Steve Anton4171afb2017-11-20 10:20:22 -08004121 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4122 ? kDefaultAudioSenderId
4123 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004124 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004125 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004126 if (!default_sender_info) {
4127 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004128 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004129 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004130 }
4131 }
deadbeefab9b2d12015-10-14 11:33:11 -07004132}
4133
Steve Anton4171afb2017-11-20 10:20:22 -08004134void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4135 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004136 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4137 << " receiver for track_id=" << sender_info.sender_id
4138 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004139
Steve Anton3d954a62018-04-02 11:27:23 -07004140 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004141 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004142 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004143 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004144 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004145 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004146 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004147 }
4148}
4149
Steve Anton4171afb2017-11-20 10:20:22 -08004150void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4151 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004152 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4153 << " receiver for track_id=" << sender_info.sender_id
4154 << " and stream_id=" << sender_info.stream_id;
4155
Seth Hampson845e8782018-03-02 11:34:10 -08004156 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004157
Henrik Boström933d8b02017-10-10 10:05:16 -07004158 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004159 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004160 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4161 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004162 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004163 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004164 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004165 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004166 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004167 }
4168 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004169 // Stopping or destroying a VideoRtpReceiver will end the
4170 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004171 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004172 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004173 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004174 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004175 // There's no guarantee the track is still available, e.g. the track may
4176 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004177 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004178 }
4179 } else {
nisseede5da42017-01-12 05:15:36 -08004180 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004181 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004182 if (receiver) {
4183 observer_->OnRemoveTrack(receiver);
4184 }
deadbeefab9b2d12015-10-14 11:33:11 -07004185}
4186
4187void PeerConnection::UpdateEndedRemoteMediaStreams() {
4188 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4189 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4190 MediaStreamInterface* stream = remote_streams_->at(i);
4191 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4192 streams_to_remove.push_back(stream);
4193 }
4194 }
4195
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004196 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004197 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004198 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004199 }
4200}
4201
Steve Anton4171afb2017-11-20 10:20:22 -08004202void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004203 const std::vector<cricket::StreamParams>& streams,
4204 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004205 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004206
Seth Hampson845e8782018-03-02 11:34:10 -08004207 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004208 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004209 for (auto sender_it = current_senders->begin();
4210 sender_it != current_senders->end();
4211 /* incremented manually */) {
4212 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004213 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004214 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4215 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004216 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004217 OnLocalSenderRemoved(info, media_type);
4218 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004219 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004220 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004221 }
4222 }
4223
Steve Anton4171afb2017-11-20 10:20:22 -08004224 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004225 for (const cricket::StreamParams& params : streams) {
4226 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004227 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004228 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004229 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004230 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004231 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004232 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004233 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004234 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004235 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004236 }
4237 }
4238}
4239
Steve Anton4171afb2017-11-20 10:20:22 -08004240void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4241 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004242 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004243 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004244 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004245 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4246 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004247 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004248 return;
4249 }
4250
deadbeeffac06552015-11-25 11:26:01 -08004251 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004252 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004253 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004254 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004255 }
deadbeeffac06552015-11-25 11:26:01 -08004256
Seth Hampson5b4f0752018-04-02 16:31:36 -07004257 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004258 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004259}
4260
Steve Anton4171afb2017-11-20 10:20:22 -08004261void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4262 cricket::MediaType media_type) {
4263 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004264 if (!sender) {
4265 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004266 // SessionDescriptions has been renegotiated.
4267 return;
4268 }
deadbeeffac06552015-11-25 11:26:01 -08004269
4270 // A sender has been removed from the SessionDescription but it's still
4271 // associated with the PeerConnection. This only occurs if the SDP doesn't
4272 // match with the calls to CreateSender, AddStream and RemoveStream.
4273 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004274 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004275 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004276 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004277 }
deadbeeffac06552015-11-25 11:26:01 -08004278
Steve Anton4171afb2017-11-20 10:20:22 -08004279 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004280}
4281
4282void PeerConnection::UpdateLocalRtpDataChannels(
4283 const cricket::StreamParamsVec& streams) {
4284 std::vector<std::string> existing_channels;
4285
4286 // Find new and active data channels.
4287 for (const cricket::StreamParams& params : streams) {
4288 // |it->sync_label| is actually the data channel label. The reason is that
4289 // we use the same naming of data channels as we do for
4290 // MediaStreams and Tracks.
4291 // For MediaStreams, the sync_label is the MediaStream label and the
4292 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004293 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004294 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004295 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004296 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004297 continue;
4298 }
4299 // Set the SSRC the data channel should use for sending.
4300 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4301 existing_channels.push_back(data_channel_it->first);
4302 }
4303
4304 UpdateClosingRtpDataChannels(existing_channels, true);
4305}
4306
4307void PeerConnection::UpdateRemoteRtpDataChannels(
4308 const cricket::StreamParamsVec& streams) {
4309 std::vector<std::string> existing_channels;
4310
4311 // Find new and active data channels.
4312 for (const cricket::StreamParams& params : streams) {
4313 // The data channel label is either the mslabel or the SSRC if the mslabel
4314 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004315 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004316 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004317 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004318 auto data_channel_it = rtp_data_channels_.find(label);
4319 if (data_channel_it == rtp_data_channels_.end()) {
4320 // This is a new data channel.
4321 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4322 } else {
4323 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4324 }
4325 existing_channels.push_back(label);
4326 }
4327
4328 UpdateClosingRtpDataChannels(existing_channels, false);
4329}
4330
4331void PeerConnection::UpdateClosingRtpDataChannels(
4332 const std::vector<std::string>& active_channels,
4333 bool is_local_update) {
4334 auto it = rtp_data_channels_.begin();
4335 while (it != rtp_data_channels_.end()) {
4336 DataChannel* data_channel = it->second;
4337 if (std::find(active_channels.begin(), active_channels.end(),
4338 data_channel->label()) != active_channels.end()) {
4339 ++it;
4340 continue;
4341 }
4342
4343 if (is_local_update) {
4344 data_channel->SetSendSsrc(0);
4345 } else {
4346 data_channel->RemotePeerRequestClose();
4347 }
4348
4349 if (data_channel->state() == DataChannel::kClosed) {
4350 rtp_data_channels_.erase(it);
4351 it = rtp_data_channels_.begin();
4352 } else {
4353 ++it;
4354 }
4355 }
4356}
4357
4358void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4359 uint32_t remote_ssrc) {
4360 rtc::scoped_refptr<DataChannel> channel(
4361 InternalCreateDataChannel(label, nullptr));
4362 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004363 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004364 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004365 return;
4366 }
4367 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004368 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4369 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004370 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004371}
4372
4373rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4374 const std::string& label,
4375 const InternalDataChannelInit* config) {
4376 if (IsClosed()) {
4377 return nullptr;
4378 }
Steve Anton75737c02017-11-06 10:37:17 -08004379 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004380 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004381 << "InternalCreateDataChannel: Data is not supported in this call.";
4382 return nullptr;
4383 }
4384 InternalDataChannelInit new_config =
4385 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004386 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004387 if (new_config.id < 0) {
4388 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004389 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004390 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004391 RTC_LOG(LS_ERROR)
4392 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004393 return nullptr;
4394 }
4395 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004396 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004397 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004398 return nullptr;
4399 }
4400 }
4401
Steve Anton75737c02017-11-06 10:37:17 -08004402 rtc::scoped_refptr<DataChannel> channel(
4403 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004404 if (!channel) {
4405 sid_allocator_.ReleaseSid(new_config.id);
4406 return nullptr;
4407 }
4408
4409 if (channel->data_channel_type() == cricket::DCT_RTP) {
4410 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004411 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4412 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004413 return nullptr;
4414 }
4415 rtp_data_channels_[channel->label()] = channel;
4416 } else {
4417 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4418 sctp_data_channels_.push_back(channel);
4419 channel->SignalClosed.connect(this,
4420 &PeerConnection::OnSctpDataChannelClosed);
4421 }
4422
Steve Anton2d8609c2018-01-23 16:38:46 -08004423 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004424 return channel;
4425}
4426
4427bool PeerConnection::HasDataChannels() const {
4428 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4429}
4430
4431void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4432 for (const auto& channel : sctp_data_channels_) {
4433 if (channel->id() < 0) {
4434 int sid;
4435 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004436 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004437 continue;
4438 }
4439 channel->SetSctpSid(sid);
4440 }
4441 }
4442}
4443
4444void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004445 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004446 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4447 ++it) {
4448 if (it->get() == channel) {
4449 if (channel->id() >= 0) {
4450 sid_allocator_.ReleaseSid(channel->id());
4451 }
deadbeefbd292462015-12-14 18:15:29 -08004452 // Since this method is triggered by a signal from the DataChannel,
4453 // we can't free it directly here; we need to free it asynchronously.
4454 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004455 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004456 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4457 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004458 return;
4459 }
4460 }
4461}
4462
deadbeefab9b2d12015-10-14 11:33:11 -07004463void PeerConnection::OnDataChannelDestroyed() {
4464 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4465 // DataChannel may callback to us and try to modify the list.
4466 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4467 temp_rtp_dcs.swap(rtp_data_channels_);
4468 for (const auto& kv : temp_rtp_dcs) {
4469 kv.second->OnTransportChannelDestroyed();
4470 }
4471
4472 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4473 temp_sctp_dcs.swap(sctp_data_channels_);
4474 for (const auto& channel : temp_sctp_dcs) {
4475 channel->OnTransportChannelDestroyed();
4476 }
4477}
4478
4479void PeerConnection::OnDataChannelOpenMessage(
4480 const std::string& label,
4481 const InternalDataChannelInit& config) {
4482 rtc::scoped_refptr<DataChannel> channel(
4483 InternalCreateDataChannel(label, &config));
4484 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004485 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004486 return;
4487 }
4488
deadbeefa601f5c2016-06-06 14:27:39 -07004489 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4490 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004491 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004492}
4493
Steve Anton4171afb2017-11-20 10:20:22 -08004494rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4495PeerConnection::GetAudioTransceiver() const {
4496 // This method only works with Plan B SDP, where there is a single
4497 // audio/video transceiver.
4498 RTC_DCHECK(!IsUnifiedPlan());
4499 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004500 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004501 return transceiver;
4502 }
4503 }
4504 RTC_NOTREACHED();
4505 return nullptr;
4506}
4507
4508rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4509PeerConnection::GetVideoTransceiver() const {
4510 // This method only works with Plan B SDP, where there is a single
4511 // audio/video transceiver.
4512 RTC_DCHECK(!IsUnifiedPlan());
4513 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004514 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004515 return transceiver;
4516 }
4517 }
4518 RTC_NOTREACHED();
4519 return nullptr;
4520}
4521
4522// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4523// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004524bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004525 switch (type) {
4526 case cricket::MEDIA_TYPE_AUDIO:
4527 return !GetAudioTransceiver()->internal()->senders().empty();
4528 case cricket::MEDIA_TYPE_VIDEO:
4529 return !GetVideoTransceiver()->internal()->senders().empty();
4530 case cricket::MEDIA_TYPE_DATA:
4531 return false;
4532 }
4533 RTC_NOTREACHED();
4534 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004535}
4536
Steve Anton4171afb2017-11-20 10:20:22 -08004537rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4538PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4539 for (auto transceiver : transceivers_) {
4540 for (auto sender : transceiver->internal()->senders()) {
4541 if (sender->track() == track) {
4542 return sender;
4543 }
4544 }
4545 }
4546 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004547}
4548
Steve Anton4171afb2017-11-20 10:20:22 -08004549rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4550PeerConnection::FindSenderById(const std::string& sender_id) const {
4551 for (auto transceiver : transceivers_) {
4552 for (auto sender : transceiver->internal()->senders()) {
4553 if (sender->id() == sender_id) {
4554 return sender;
4555 }
4556 }
4557 }
4558 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004559}
4560
Steve Anton4171afb2017-11-20 10:20:22 -08004561rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4562PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4563 for (auto transceiver : transceivers_) {
4564 for (auto receiver : transceiver->internal()->receivers()) {
4565 if (receiver->id() == receiver_id) {
4566 return receiver;
4567 }
4568 }
4569 }
4570 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004571}
4572
Steve Anton4171afb2017-11-20 10:20:22 -08004573std::vector<PeerConnection::RtpSenderInfo>*
4574PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4575 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4576 media_type == cricket::MEDIA_TYPE_VIDEO);
4577 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4578 ? &remote_audio_sender_infos_
4579 : &remote_video_sender_infos_;
4580}
4581
4582std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004583 cricket::MediaType media_type) {
4584 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4585 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004586 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4587 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004588}
4589
Steve Anton4171afb2017-11-20 10:20:22 -08004590const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4591 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004592 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004593 const std::string sender_id) const {
4594 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004595 if (sender_info.stream_id == stream_id &&
4596 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004597 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004598 }
4599 }
4600 return nullptr;
4601}
4602
4603DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4604 for (const auto& channel : sctp_data_channels_) {
4605 if (channel->id() == sid) {
4606 return channel;
4607 }
4608 }
4609 return nullptr;
4610}
4611
deadbeef91dd5672016-05-18 16:55:30 -07004612bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004613 const RTCConfiguration& configuration) {
4614 cricket::ServerAddresses stun_servers;
4615 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004616 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4617 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004618 return false;
4619 }
4620
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004621 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004622 // To handle both internal and externally created port allocator, we will
4623 // enable BUNDLE here.
Qingsi Wangfc43d112018-04-10 15:50:46 -07004624 port_allocator_flags_ = port_allocator_->flags();
4625 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4626 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4627 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004628 // If the disable-IPv6 flag was specified, we'll not override it
4629 // by experiment.
4630 if (configuration.disable_ipv6) {
Qingsi Wangfc43d112018-04-10 15:50:46 -07004631 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004632 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4633 .find("Disabled") == 0) {
Qingsi Wangfc43d112018-04-10 15:50:46 -07004634 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004635 }
4636
zhihuangb09b3f92017-03-07 14:40:51 -08004637 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wangfc43d112018-04-10 15:50:46 -07004638 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004639 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004640 }
4641
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004642 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wangfc43d112018-04-10 15:50:46 -07004643 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004644 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004645 }
4646
honghaiz60347052016-05-31 18:29:12 -07004647 if (configuration.candidate_network_policy ==
4648 kCandidateNetworkPolicyLowCost) {
Qingsi Wangfc43d112018-04-10 15:50:46 -07004649 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004650 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004651 }
4652
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004653 if (configuration.disable_link_local_networks) {
Qingsi Wangfc43d112018-04-10 15:50:46 -07004654 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004655 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4656 }
4657
Qingsi Wangfc43d112018-04-10 15:50:46 -07004658 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004659 // No step delay is used while allocating ports.
4660 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4661 port_allocator_->set_candidate_filter(
4662 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004663 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004664
4665 // Call this last since it may create pooled allocator sessions using the
4666 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004667 port_allocator_->SetConfiguration(
4668 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4669 configuration.prune_turn_ports, configuration.turn_customizer,
4670 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004671 return true;
4672}
4673
deadbeef91dd5672016-05-18 16:55:30 -07004674bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004675 const cricket::ServerAddresses& stun_servers,
4676 const std::vector<cricket::RelayServerConfig>& turn_servers,
4677 IceTransportsType type,
4678 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004679 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004680 webrtc::TurnCustomizer* turn_customizer,
4681 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004682 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004683 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wangfc43d112018-04-10 15:50:46 -07004684 // According to JSEP, after setLocalDescription, changing the candidate pool
4685 // size is not allowed, and changing the set of ICE servers will not result
4686 // in new candidates being gathered.
4687 if (local_description()) {
4688 port_allocator_->FreezeCandidatePool();
4689 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004690 // Call this last since it may create pooled allocator sessions using the
4691 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004692 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004693 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004694 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004695}
4696
Steve Antonba818672017-11-06 10:21:57 -08004697cricket::ChannelManager* PeerConnection::channel_manager() const {
4698 return factory_->channel_manager();
4699}
4700
4701MetricsObserverInterface* PeerConnection::metrics_observer() const {
4702 return uma_observer_;
4703}
4704
Elad Alon99c3fe52017-10-13 16:29:40 +02004705bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004706 std::unique_ptr<RtcEventLogOutput> output,
4707 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004708 if (!event_log_) {
4709 return false;
4710 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004711 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004712}
4713
4714void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004715 if (event_log_) {
4716 event_log_->StopLogging();
4717 }
ivoc14d5dbe2016-07-04 07:06:55 -07004718}
nisseeaabdf62017-05-05 02:23:02 -07004719
Steve Anton75737c02017-11-06 10:37:17 -08004720cricket::BaseChannel* PeerConnection::GetChannel(
4721 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004722 for (auto transceiver : transceivers_) {
4723 cricket::BaseChannel* channel = transceiver->internal()->channel();
4724 if (channel && channel->content_name() == content_name) {
4725 return channel;
4726 }
Steve Anton75737c02017-11-06 10:37:17 -08004727 }
4728 if (rtp_data_channel() &&
4729 rtp_data_channel()->content_name() == content_name) {
4730 return rtp_data_channel();
4731 }
4732 return nullptr;
4733}
4734
4735bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4736 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004737 RTC_LOG(LS_INFO)
4738 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004739 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004740 return false;
4741 }
4742 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004743 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004744 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004745 return false;
4746 }
4747
Zhi Huange830e682018-03-30 10:48:35 -07004748 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4749 if (dtls_role) {
4750 *role = *dtls_role;
4751 return true;
4752 }
4753 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004754}
4755
4756bool PeerConnection::GetSslRole(const std::string& content_name,
4757 rtc::SSLRole* role) {
4758 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004759 RTC_LOG(LS_INFO)
4760 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004761 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004762 return false;
4763 }
4764
Zhi Huange830e682018-03-30 10:48:35 -07004765 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4766 if (dtls_role) {
4767 *role = *dtls_role;
4768 return true;
4769 }
4770 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004771}
4772
Steve Antonf8470812017-12-04 10:46:21 -08004773void PeerConnection::SetSessionError(SessionError error,
4774 const std::string& error_desc) {
4775 RTC_DCHECK_RUN_ON(signaling_thread());
4776 if (error != session_error_) {
4777 session_error_ = error;
4778 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004779 }
4780}
4781
Zhi Huange830e682018-03-30 10:48:35 -07004782RTCError PeerConnection::UpdateSessionState(
4783 SdpType type,
4784 cricket::ContentSource source,
4785 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004786 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004787
4788 // If there's already a pending error then no state transition should happen.
4789 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004790 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004791
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004792 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004793 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004794 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004795 }
4796
4797 // Update the signaling state according to the specified state machine (see
4798 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004799 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004800 ChangeSignalingState(source == cricket::CS_LOCAL
4801 ? PeerConnectionInterface::kHaveLocalOffer
4802 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004803 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004804 ChangeSignalingState(source == cricket::CS_LOCAL
4805 ? PeerConnectionInterface::kHaveLocalPrAnswer
4806 : PeerConnectionInterface::kHaveRemotePrAnswer);
4807 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004808 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004809 ChangeSignalingState(PeerConnectionInterface::kStable);
4810 }
4811
4812 // Update internal objects according to the session description's media
4813 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004814 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004815 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004816 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004817 }
4818
Steve Anton8a006912017-12-04 15:25:56 -08004819 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004820}
4821
Steve Anton8a006912017-12-04 15:25:56 -08004822RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004823 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004824 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004825 const SessionDescriptionInterface* sdesc =
4826 (source == cricket::CS_LOCAL ? local_description()
4827 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004828 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004829
4830 // Push down the new SDP media section for each audio/video transceiver.
4831 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004832 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004833 FindMediaSectionForTransceiver(transceiver, sdesc);
4834 cricket::BaseChannel* channel = transceiver->internal()->channel();
4835 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004836 continue;
4837 }
4838 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004839 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004840 if (!content_desc) {
4841 continue;
4842 }
4843 std::string error;
4844 bool success =
4845 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004846 ? channel->SetLocalContent(content_desc, type, &error)
4847 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004848 if (!success) {
4849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4850 }
4851 }
4852
4853 // If using the RtpDataChannel, push down the new SDP section for it too.
4854 if (rtp_data_channel_) {
4855 const ContentInfo* data_content =
4856 cricket::GetFirstDataContent(sdesc->description());
4857 if (data_content && !data_content->rejected) {
4858 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004859 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004860 if (data_desc) {
4861 std::string error;
4862 bool success =
4863 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004864 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4865 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004866 &error);
4867 if (!success) {
4868 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4869 std::move(error));
4870 }
Steve Anton75737c02017-11-06 10:37:17 -08004871 }
4872 }
4873 }
Steve Antoned10bd92017-12-05 10:52:59 -08004874
Steve Anton75737c02017-11-06 10:37:17 -08004875 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4876 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4877 if (sctp_transport_ && local_description() && remote_description() &&
4878 cricket::GetFirstDataContent(local_description()->description()) &&
4879 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004880 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004881 RTC_FROM_HERE,
4882 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004883 if (!success) {
4884 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4885 "Failed to push down SCTP parameters.");
4886 }
Steve Anton75737c02017-11-06 10:37:17 -08004887 }
Steve Antoned10bd92017-12-05 10:52:59 -08004888
Steve Anton8a006912017-12-04 15:25:56 -08004889 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004890}
4891
4892bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4893 RTC_DCHECK(network_thread()->IsCurrent());
4894 RTC_DCHECK(local_description());
4895 RTC_DCHECK(remote_description());
4896 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4897 // When we support "max-message-size", that would also be pushed down here.
4898 return sctp_transport_->Start(
4899 GetSctpPort(local_description()->description()),
4900 GetSctpPort(remote_description()->description()));
4901}
4902
Steve Anton8a006912017-12-04 15:25:56 -08004903RTCError PeerConnection::PushdownTransportDescription(
4904 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004905 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004906 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004907
Zhi Huange830e682018-03-30 10:48:35 -07004908 if (source == cricket::CS_LOCAL) {
4909 const SessionDescriptionInterface* sdesc = local_description();
4910 RTC_DCHECK(sdesc);
4911 return transport_controller_->SetLocalDescription(type,
4912 sdesc->description());
4913 } else {
4914 const SessionDescriptionInterface* sdesc = remote_description();
4915 RTC_DCHECK(sdesc);
4916 return transport_controller_->SetRemoteDescription(type,
4917 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004918 }
Steve Anton75737c02017-11-06 10:37:17 -08004919}
4920
4921bool PeerConnection::GetTransportDescription(
4922 const SessionDescription* description,
4923 const std::string& content_name,
4924 cricket::TransportDescription* tdesc) {
4925 if (!description || !tdesc) {
4926 return false;
4927 }
4928 const TransportInfo* transport_info =
4929 description->GetTransportInfoByName(content_name);
4930 if (!transport_info) {
4931 return false;
4932 }
4933 *tdesc = transport_info->description;
4934 return true;
4935}
4936
Steve Anton75737c02017-11-06 10:37:17 -08004937cricket::IceConfig PeerConnection::ParseIceConfig(
4938 const PeerConnectionInterface::RTCConfiguration& config) const {
4939 cricket::ContinualGatheringPolicy gathering_policy;
4940 // TODO(honghaiz): Add the third continual gathering policy in
4941 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4942 switch (config.continual_gathering_policy) {
4943 case PeerConnectionInterface::GATHER_ONCE:
4944 gathering_policy = cricket::GATHER_ONCE;
4945 break;
4946 case PeerConnectionInterface::GATHER_CONTINUALLY:
4947 gathering_policy = cricket::GATHER_CONTINUALLY;
4948 break;
4949 default:
4950 RTC_NOTREACHED();
4951 gathering_policy = cricket::GATHER_ONCE;
4952 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004953
Steve Anton75737c02017-11-06 10:37:17 -08004954 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004955 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4956 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004957 ice_config.prioritize_most_likely_candidate_pairs =
4958 config.prioritize_most_likely_ice_candidate_pairs;
4959 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004960 RTCConfigurationToIceConfigOptionalInt(
4961 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004962 ice_config.continual_gathering_policy = gathering_policy;
4963 ice_config.presume_writable_when_fully_relayed =
4964 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004965 ice_config.ice_check_interval_strong_connectivity =
4966 config.ice_check_interval_strong_connectivity;
4967 ice_config.ice_check_interval_weak_connectivity =
4968 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004969 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004970 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004971 ice_config.regather_all_networks_interval_range =
4972 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004973 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004974 return ice_config;
4975}
4976
Steve Anton75737c02017-11-06 10:37:17 -08004977bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4978 std::string* track_id) {
4979 if (!local_description()) {
4980 return false;
4981 }
4982 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
4983 track_id);
4984}
4985
4986bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
4987 std::string* track_id) {
4988 if (!remote_description()) {
4989 return false;
4990 }
4991 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
4992 track_id);
4993}
4994
4995bool PeerConnection::SendData(const cricket::SendDataParams& params,
4996 const rtc::CopyOnWriteBuffer& payload,
4997 cricket::SendDataResult* result) {
4998 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004999 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005000 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005001 return false;
5002 }
5003 return rtp_data_channel_
5004 ? rtp_data_channel_->SendData(params, payload, result)
5005 : network_thread()->Invoke<bool>(
5006 RTC_FROM_HERE,
5007 Bind(&cricket::SctpTransportInternal::SendData,
5008 sctp_transport_.get(), params, payload, result));
5009}
5010
5011bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5012 if (!rtp_data_channel_ && !sctp_transport_) {
5013 // Don't log an error here, because DataChannels are expected to call
5014 // ConnectDataChannel in this state. It's the only way to initially tell
5015 // whether or not the underlying transport is ready.
5016 return false;
5017 }
5018 if (rtp_data_channel_) {
5019 rtp_data_channel_->SignalReadyToSendData.connect(
5020 webrtc_data_channel, &DataChannel::OnChannelReady);
5021 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5022 &DataChannel::OnDataReceived);
5023 } else {
5024 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5025 &DataChannel::OnChannelReady);
5026 SignalSctpDataReceived.connect(webrtc_data_channel,
5027 &DataChannel::OnDataReceived);
5028 SignalSctpStreamClosedRemotely.connect(
5029 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5030 }
5031 return true;
5032}
5033
5034void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5035 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005036 RTC_LOG(LS_ERROR)
5037 << "DisconnectDataChannel called when rtp_data_channel_ and "
5038 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005039 return;
5040 }
5041 if (rtp_data_channel_) {
5042 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5043 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5044 } else {
5045 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5046 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5047 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5048 }
5049}
5050
5051void PeerConnection::AddSctpDataStream(int sid) {
5052 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005053 RTC_LOG(LS_ERROR)
5054 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005055 return;
5056 }
5057 network_thread()->Invoke<void>(
5058 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5059 sctp_transport_.get(), sid));
5060}
5061
5062void PeerConnection::RemoveSctpDataStream(int sid) {
5063 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005064 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005065 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005066 return;
5067 }
5068 network_thread()->Invoke<void>(
5069 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5070 sctp_transport_.get(), sid));
5071}
5072
5073bool PeerConnection::ReadyToSendData() const {
5074 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5075 sctp_ready_to_send_data_;
5076}
5077
Zhi Huange830e682018-03-30 10:48:35 -07005078rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5079 if (sctp_mid_ && transport_controller_) {
5080 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5081 if (dtls_transport) {
5082 return dtls_transport->transport_name();
5083 }
5084 return rtc::Optional<std::string>();
5085 }
5086 return rtc::Optional<std::string>();
5087}
5088
Qingsi Wang72a43a12018-02-20 16:03:18 -08005089cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5090 cricket::CandidateStatsList candidate_states_list;
Qingsi Wangfc43d112018-04-10 15:50:46 -07005091 network_thread()->Invoke<void>(
5092 RTC_FROM_HERE,
5093 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5094 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005095 return candidate_states_list;
5096}
5097
Steve Anton5dfde182018-02-06 10:34:40 -08005098std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5099 const {
5100 std::map<std::string, std::string> transport_names_by_mid;
5101 for (auto transceiver : transceivers_) {
5102 cricket::BaseChannel* channel = transceiver->internal()->channel();
5103 if (channel) {
5104 transport_names_by_mid[channel->content_name()] =
5105 channel->transport_name();
5106 }
Steve Anton75737c02017-11-06 10:37:17 -08005107 }
Steve Anton5dfde182018-02-06 10:34:40 -08005108 if (rtp_data_channel_) {
5109 transport_names_by_mid[rtp_data_channel_->content_name()] =
5110 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005111 }
5112 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005113 rtc::Optional<std::string> transport_name = sctp_transport_name();
5114 RTC_DCHECK(transport_name);
5115 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005116 }
Steve Anton5dfde182018-02-06 10:34:40 -08005117 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005118}
5119
Steve Anton5dfde182018-02-06 10:34:40 -08005120std::map<std::string, cricket::TransportStats>
5121PeerConnection::GetTransportStatsByNames(
5122 const std::set<std::string>& transport_names) {
5123 if (!network_thread()->IsCurrent()) {
5124 return network_thread()
5125 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5126 RTC_FROM_HERE,
5127 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005128 }
Steve Anton5dfde182018-02-06 10:34:40 -08005129 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5130 for (const std::string& transport_name : transport_names) {
5131 cricket::TransportStats transport_stats;
5132 bool success =
5133 transport_controller_->GetStats(transport_name, &transport_stats);
5134 if (success) {
5135 transport_stats_by_name[transport_name] = std::move(transport_stats);
5136 } else {
5137 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5138 << transport_name;
5139 }
5140 }
5141 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005142}
5143
5144bool PeerConnection::GetLocalCertificate(
5145 const std::string& transport_name,
5146 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005147 if (!certificate) {
5148 return false;
5149 }
5150 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5151 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005152}
5153
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005154std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005155 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005156 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005157}
5158
5159cricket::DataChannelType PeerConnection::data_channel_type() const {
5160 return data_channel_type_;
5161}
5162
5163bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5164 return pending_ice_restarts_.find(content_name) !=
5165 pending_ice_restarts_.end();
5166}
5167
Steve Anton75737c02017-11-06 10:37:17 -08005168bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5169 return transport_controller_->NeedsIceRestart(content_name);
5170}
5171
5172void PeerConnection::OnCertificateReady(
5173 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5174 transport_controller_->SetLocalCertificate(certificate);
5175}
5176
5177void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005178 SetSessionError(SessionError::kTransport,
5179 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005180}
5181
5182void PeerConnection::OnTransportControllerConnectionState(
5183 cricket::IceConnectionState state) {
5184 switch (state) {
5185 case cricket::kIceConnectionConnecting:
5186 // If the current state is Connected or Completed, then there were
5187 // writable channels but now there are not, so the next state must
5188 // be Disconnected.
5189 // kIceConnectionConnecting is currently used as the default,
5190 // un-connected state by the TransportController, so its only use is
5191 // detecting disconnections.
5192 if (ice_connection_state_ ==
5193 PeerConnectionInterface::kIceConnectionConnected ||
5194 ice_connection_state_ ==
5195 PeerConnectionInterface::kIceConnectionCompleted) {
5196 SetIceConnectionState(
5197 PeerConnectionInterface::kIceConnectionDisconnected);
5198 }
5199 break;
5200 case cricket::kIceConnectionFailed:
5201 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5202 break;
5203 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005204 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005205 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005206 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5207 break;
5208 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005209 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005210 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005211 if (ice_connection_state_ !=
5212 PeerConnectionInterface::kIceConnectionConnected) {
5213 // If jumping directly from "checking" to "connected",
5214 // signal "connected" first.
5215 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5216 }
5217 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5218 if (metrics_observer()) {
5219 ReportTransportStats();
5220 }
5221 break;
5222 default:
5223 RTC_NOTREACHED();
5224 }
5225}
5226
5227void PeerConnection::OnTransportControllerCandidatesGathered(
5228 const std::string& transport_name,
5229 const cricket::Candidates& candidates) {
5230 RTC_DCHECK(signaling_thread()->IsCurrent());
5231 int sdp_mline_index;
5232 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005233 RTC_LOG(LS_ERROR)
5234 << "OnTransportControllerCandidatesGathered: content name "
5235 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005236 return;
5237 }
5238
5239 for (cricket::Candidates::const_iterator citer = candidates.begin();
5240 citer != candidates.end(); ++citer) {
5241 // Use transport_name as the candidate media id.
5242 std::unique_ptr<JsepIceCandidate> candidate(
5243 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5244 if (local_description()) {
5245 mutable_local_description()->AddCandidate(candidate.get());
5246 }
5247 OnIceCandidate(std::move(candidate));
5248 }
5249}
5250
5251void PeerConnection::OnTransportControllerCandidatesRemoved(
5252 const std::vector<cricket::Candidate>& candidates) {
5253 RTC_DCHECK(signaling_thread()->IsCurrent());
5254 // Sanity check.
5255 for (const cricket::Candidate& candidate : candidates) {
5256 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005257 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005258 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005259 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005260 return;
5261 }
5262 }
5263
5264 if (local_description()) {
5265 mutable_local_description()->RemoveCandidates(candidates);
5266 }
5267 OnIceCandidatesRemoved(candidates);
5268}
5269
5270void PeerConnection::OnTransportControllerDtlsHandshakeError(
5271 rtc::SSLHandshakeError error) {
5272 if (metrics_observer()) {
5273 metrics_observer()->IncrementEnumCounter(
5274 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5275 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5276 }
5277}
5278
Steve Antoned10bd92017-12-05 10:52:59 -08005279void PeerConnection::EnableSending() {
5280 for (auto transceiver : transceivers_) {
5281 cricket::BaseChannel* channel = transceiver->internal()->channel();
5282 if (channel && !channel->enabled()) {
5283 channel->Enable(true);
5284 }
Steve Anton75737c02017-11-06 10:37:17 -08005285 }
5286
Steve Anton4171afb2017-11-20 10:20:22 -08005287 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005288 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005289 }
Steve Anton75737c02017-11-06 10:37:17 -08005290}
5291
5292// Returns the media index for a local ice candidate given the content name.
5293bool PeerConnection::GetLocalCandidateMediaIndex(
5294 const std::string& content_name,
5295 int* sdp_mline_index) {
5296 if (!local_description() || !sdp_mline_index) {
5297 return false;
5298 }
5299
5300 bool content_found = false;
5301 const ContentInfos& contents = local_description()->description()->contents();
5302 for (size_t index = 0; index < contents.size(); ++index) {
5303 if (contents[index].name == content_name) {
5304 *sdp_mline_index = static_cast<int>(index);
5305 content_found = true;
5306 break;
5307 }
5308 }
5309 return content_found;
5310}
5311
5312bool PeerConnection::UseCandidatesInSessionDescription(
5313 const SessionDescriptionInterface* remote_desc) {
5314 if (!remote_desc) {
5315 return true;
5316 }
5317 bool ret = true;
5318
5319 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5320 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5321 for (size_t n = 0; n < candidates->count(); ++n) {
5322 const IceCandidateInterface* candidate = candidates->at(n);
5323 bool valid = false;
5324 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5325 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005326 RTC_LOG(LS_INFO)
5327 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005328 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005329 }
5330 continue;
5331 }
5332 ret = UseCandidate(candidate);
5333 if (!ret) {
5334 break;
5335 }
5336 }
5337 }
5338 return ret;
5339}
5340
5341bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5342 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5343 size_t remote_content_size =
5344 remote_description()->description()->contents().size();
5345 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005346 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005347 return false;
5348 }
5349
5350 cricket::ContentInfo content =
5351 remote_description()->description()->contents()[mediacontent_index];
5352 std::vector<cricket::Candidate> candidates;
5353 candidates.push_back(candidate->candidate());
5354 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005355 RTCError error =
5356 transport_controller_->AddRemoteCandidates(content.name, candidates);
5357 if (error.ok()) {
Steve Anton75737c02017-11-06 10:37:17 -08005358 // Candidates successfully submitted for checking.
5359 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5360 ice_connection_state_ ==
5361 PeerConnectionInterface::kIceConnectionDisconnected) {
5362 // If state is New, then the session has just gotten its first remote ICE
5363 // candidates, so go to Checking.
5364 // If state is Disconnected, the session is re-using old candidates or
5365 // receiving additional ones, so go to Checking.
5366 // If state is Connected, stay Connected.
5367 // TODO(bemasc): If state is Connected, and the new candidates are for a
5368 // newly added transport, then the state actually _should_ move to
5369 // checking. Add a way to distinguish that case.
5370 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5371 }
5372 // TODO(bemasc): If state is Completed, go back to Connected.
Zhi Huange830e682018-03-30 10:48:35 -07005373 } else if (error.message()) {
5374 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005375 }
5376 return true;
5377}
5378
5379void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005380 // Destroy video channel first since it may have a pointer to the
5381 // voice channel.
5382 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005383 if (!video_info || video_info->rejected) {
5384 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005385 }
5386
Steve Anton6fec8802017-12-04 10:37:29 -08005387 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5388 if (!audio_info || audio_info->rejected) {
5389 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005390 }
5391
5392 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5393 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005394 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005395 }
5396}
5397
Steve Antondcc3c022017-12-22 16:02:54 -08005398RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5399 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005400 const cricket::ContentGroup* bundle_group = nullptr;
5401 if (configuration_.bundle_policy ==
5402 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005403 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005404 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005405 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5406 "max-bundle configured but session description "
5407 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005408 }
5409 }
Steve Antondcc3c022017-12-22 16:02:54 -08005410 return std::move(bundle_group);
5411}
5412
5413RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005414 // Creating the media channels. Transports should already have been created
5415 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005416 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005417 if (voice && !voice->rejected &&
5418 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005419 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005420 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005421 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5422 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005423 }
5424 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5425 }
5426
Steve Antondcc3c022017-12-22 16:02:54 -08005427 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005428 if (video && !video->rejected &&
5429 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005430 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005431 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005432 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5433 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005434 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005435 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005436 }
5437
Steve Antondcc3c022017-12-22 16:02:54 -08005438 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005439 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5440 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005441 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005442 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5443 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005444 }
5445 }
5446
Steve Anton8a006912017-12-04 15:25:56 -08005447 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005448}
5449
Steve Anton4171afb2017-11-20 10:20:22 -08005450// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005451cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005452 const std::string& mid) {
5453 RtpTransportInternal* rtp_transport =
5454 transport_controller_->GetRtpTransport(mid);
5455 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005456 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005457 call_.get(), configuration_.media_config, rtp_transport,
5458 signaling_thread(), mid, SrtpRequired(),
5459 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005460 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005461 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005462 }
Steve Anton75737c02017-11-06 10:37:17 -08005463 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5464 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005465 voice_channel->SignalSentPacket.connect(this,
5466 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005467 voice_channel->SetRtpTransport(rtp_transport);
5468 if (factory_->options().disable_encryption) {
5469 voice_channel->DisableEncryption(true);
5470 }
Steve Antondb67ba12018-03-19 17:41:42 -07005471 if (uma_observer_) {
5472 voice_channel->SetMetricsObserver(uma_observer_);
5473 }
Steve Anton4171afb2017-11-20 10:20:22 -08005474
Steve Antoneda6ccd2017-12-04 10:21:55 -08005475 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005476}
5477
Steve Anton4171afb2017-11-20 10:20:22 -08005478// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005479cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005480 const std::string& mid) {
5481 RtpTransportInternal* rtp_transport =
5482 transport_controller_->GetRtpTransport(mid);
5483 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005484 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005485 call_.get(), configuration_.media_config, rtp_transport,
5486 signaling_thread(), mid, SrtpRequired(),
5487 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005488 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005489 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005490 }
Steve Anton75737c02017-11-06 10:37:17 -08005491 video_channel->SignalDtlsSrtpSetupFailure.connect(
5492 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005493 video_channel->SignalSentPacket.connect(this,
5494 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005495 video_channel->SetRtpTransport(rtp_transport);
5496 if (factory_->options().disable_encryption) {
5497 video_channel->DisableEncryption(true);
5498 }
Steve Antondb67ba12018-03-19 17:41:42 -07005499 if (uma_observer_) {
5500 video_channel->SetMetricsObserver(uma_observer_);
5501 }
Steve Anton4171afb2017-11-20 10:20:22 -08005502
Steve Antoneda6ccd2017-12-04 10:21:55 -08005503 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005504}
5505
Zhi Huange830e682018-03-30 10:48:35 -07005506bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005507 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5508 if (sctp) {
5509 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005510 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005511 << "Trying to create SCTP transport, but didn't compile with "
5512 "SCTP support (HAVE_SCTP)";
5513 return false;
5514 }
5515 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005516 RTC_FROM_HERE,
5517 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005518 return false;
5519 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005520 for (const auto& channel : sctp_data_channels_) {
5521 channel->OnTransportChannelCreated();
5522 }
Steve Anton75737c02017-11-06 10:37:17 -08005523 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005524 RtpTransportInternal* rtp_transport =
5525 transport_controller_->GetRtpTransport(mid);
5526 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005527 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005528 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5529 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005530 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005531 return false;
5532 }
Steve Anton75737c02017-11-06 10:37:17 -08005533 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5534 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5535 rtp_data_channel_->SignalSentPacket.connect(
5536 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005537 rtp_data_channel_->SetRtpTransport(rtp_transport);
5538 if (factory_->options().disable_encryption) {
5539 rtp_data_channel_->DisableEncryption(true);
5540 }
Steve Antondb67ba12018-03-19 17:41:42 -07005541 if (uma_observer_) {
5542 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5543 }
Steve Anton75737c02017-11-06 10:37:17 -08005544 }
5545
Steve Anton75737c02017-11-06 10:37:17 -08005546 return true;
5547}
5548
5549Call::Stats PeerConnection::GetCallStats() {
5550 if (!worker_thread()->IsCurrent()) {
5551 return worker_thread()->Invoke<Call::Stats>(
5552 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5553 }
5554 if (call_) {
5555 return call_->GetStats();
5556 } else {
5557 return Call::Stats();
5558 }
5559}
5560
Zhi Huange830e682018-03-30 10:48:35 -07005561bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005562 RTC_DCHECK(network_thread()->IsCurrent());
5563 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005564 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005565 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005566 RTC_DCHECK(dtls_transport);
5567 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005568 RTC_DCHECK(sctp_transport_);
5569 sctp_invoker_.reset(new rtc::AsyncInvoker());
5570 sctp_transport_->SignalReadyToSendData.connect(
5571 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5572 sctp_transport_->SignalDataReceived.connect(
5573 this, &PeerConnection::OnSctpTransportDataReceived_n);
5574 sctp_transport_->SignalStreamClosedRemotely.connect(
5575 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Zhi Huange830e682018-03-30 10:48:35 -07005576 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005577 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005578 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005579}
5580
5581void PeerConnection::DestroySctpTransport_n() {
5582 RTC_DCHECK(network_thread()->IsCurrent());
5583 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005584 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005585 sctp_invoker_.reset(nullptr);
5586 sctp_ready_to_send_data_ = false;
5587}
5588
5589void PeerConnection::OnSctpTransportReadyToSendData_n() {
5590 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5591 RTC_DCHECK(network_thread()->IsCurrent());
5592 // Note: Cannot use rtc::Bind here because it will grab a reference to
5593 // PeerConnection and potentially cause PeerConnection to live longer than
5594 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5595 // be destroyed before PeerConnection is destroyed, and at that point all
5596 // pending tasks will be cleared.
5597 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5598 OnSctpTransportReadyToSendData_s(true);
5599 });
5600}
5601
5602void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5603 RTC_DCHECK(signaling_thread()->IsCurrent());
5604 sctp_ready_to_send_data_ = ready;
5605 SignalSctpReadyToSendData(ready);
5606}
5607
5608void PeerConnection::OnSctpTransportDataReceived_n(
5609 const cricket::ReceiveDataParams& params,
5610 const rtc::CopyOnWriteBuffer& payload) {
5611 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5612 RTC_DCHECK(network_thread()->IsCurrent());
5613 // Note: Cannot use rtc::Bind here because it will grab a reference to
5614 // PeerConnection and potentially cause PeerConnection to live longer than
5615 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5616 // be destroyed before PeerConnection is destroyed, and at that point all
5617 // pending tasks will be cleared.
5618 sctp_invoker_->AsyncInvoke<void>(
5619 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5620 OnSctpTransportDataReceived_s(params, payload);
5621 });
5622}
5623
5624void PeerConnection::OnSctpTransportDataReceived_s(
5625 const cricket::ReceiveDataParams& params,
5626 const rtc::CopyOnWriteBuffer& payload) {
5627 RTC_DCHECK(signaling_thread()->IsCurrent());
5628 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5629 // Received OPEN message; parse and signal that a new data channel should
5630 // be created.
5631 std::string label;
5632 InternalDataChannelInit config;
5633 config.id = params.ssrc;
5634 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005635 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5636 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005637 return;
5638 }
5639 config.open_handshake_role = InternalDataChannelInit::kAcker;
5640 OnDataChannelOpenMessage(label, config);
5641 } else {
5642 // Otherwise just forward the signal.
5643 SignalSctpDataReceived(params, payload);
5644 }
5645}
5646
5647void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5648 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5649 RTC_DCHECK(network_thread()->IsCurrent());
5650 sctp_invoker_->AsyncInvoke<void>(
5651 RTC_FROM_HERE, signaling_thread(),
5652 rtc::Bind(&sigslot::signal1<int>::operator(),
5653 &SignalSctpStreamClosedRemotely, sid));
5654}
5655
5656// Returns false if bundle is enabled and rtcp_mux is disabled.
5657bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5658 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5659 if (!bundle_enabled)
5660 return true;
5661
5662 const cricket::ContentGroup* bundle_group =
5663 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5664 RTC_DCHECK(bundle_group != NULL);
5665
5666 const cricket::ContentInfos& contents = desc->contents();
5667 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5668 citer != contents.end(); ++citer) {
5669 const cricket::ContentInfo* content = (&*citer);
5670 RTC_DCHECK(content != NULL);
5671 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005672 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005673 if (!HasRtcpMuxEnabled(content))
5674 return false;
5675 }
5676 }
5677 // RTCP-MUX is enabled in all the contents.
5678 return true;
5679}
5680
5681bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005682 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005683}
5684
Steve Anton8a006912017-12-04 15:25:56 -08005685RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005686 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005687 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005688 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005689 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005690 }
5691
5692 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005693 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005694 }
5695
Steve Anton3828c062017-12-06 10:34:51 -08005696 SdpType type = sdesc->GetType();
5697 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5698 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005699 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005700 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005701 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005702 }
5703
5704 // Verify crypto settings.
5705 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005706 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5707 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005708 RTCError crypto_error =
5709 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005710 if (!crypto_error.ok()) {
5711 return crypto_error;
5712 }
Steve Anton75737c02017-11-06 10:37:17 -08005713 }
5714
5715 // Verify ice-ufrag and ice-pwd.
5716 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005717 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5718 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005719 }
5720
5721 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005722 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5723 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005724 }
5725
5726 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5727 // m-lines that do not rtcp-mux enabled.
5728
5729 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005730 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005731 // With an answer we want to compare the new answer session description with
5732 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005733 const cricket::SessionDescription* offer_desc =
5734 (source == cricket::CS_LOCAL) ? remote_description()->description()
5735 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005736 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5737 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5738 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005739 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5740 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005741 }
5742 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005743 // The re-offers should respect the order of m= sections in current
5744 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005745 // With a re-offer, either the current local or current remote descriptions
5746 // could be the most up to date, so we would like to check against both of
5747 // them if they exist. It could be the case that one of them has a 0 port
5748 // for a media section, but the other does not. This is important to check
5749 // against in the case that we are recycling an m= section.
5750 const cricket::SessionDescription* current_desc = nullptr;
5751 const cricket::SessionDescription* secondary_current_desc = nullptr;
5752 if (local_description()) {
5753 current_desc = local_description()->description();
5754 if (remote_description()) {
5755 secondary_current_desc = remote_description()->description();
5756 }
5757 } else if (remote_description()) {
5758 current_desc = remote_description()->description();
5759 }
Steve Anton75737c02017-11-06 10:37:17 -08005760 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005761 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5762 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005763 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5764 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
5766 }
5767
Steve Anton8a006912017-12-04 15:25:56 -08005768 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005769}
5770
Steve Anton3828c062017-12-06 10:34:51 -08005771bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005772 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005773 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005774 return (state == PeerConnectionInterface::kStable) ||
5775 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005776 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005777 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005778 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5779 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5780 }
5781}
5782
Steve Anton3828c062017-12-06 10:34:51 -08005783bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005784 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005785 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005786 return (state == PeerConnectionInterface::kStable) ||
5787 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005788 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005789 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005790 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5791 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5792 }
5793}
5794
Steve Antonf8470812017-12-04 10:46:21 -08005795const char* PeerConnection::SessionErrorToString(SessionError error) const {
5796 switch (error) {
5797 case SessionError::kNone:
5798 return "ERROR_NONE";
5799 case SessionError::kContent:
5800 return "ERROR_CONTENT";
5801 case SessionError::kTransport:
5802 return "ERROR_TRANSPORT";
5803 }
5804 RTC_NOTREACHED();
5805 return "";
5806}
5807
Steve Anton75737c02017-11-06 10:37:17 -08005808std::string PeerConnection::GetSessionErrorMsg() {
5809 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005810 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5811 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005812 return desc.str();
5813}
5814
Steve Anton8e20f172018-03-06 10:55:04 -08005815void PeerConnection::ReportSdpFormatReceived(
5816 const SessionDescriptionInterface& remote_offer) {
5817 if (!uma_observer_) {
5818 return;
5819 }
5820 int num_audio_mlines = 0;
5821 int num_video_mlines = 0;
5822 int num_audio_tracks = 0;
5823 int num_video_tracks = 0;
5824 for (const ContentInfo& content : remote_offer.description()->contents()) {
5825 cricket::MediaType media_type = content.media_description()->type();
5826 int num_tracks = std::max(
5827 1, static_cast<int>(content.media_description()->streams().size()));
5828 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5829 num_audio_mlines += 1;
5830 num_audio_tracks += num_tracks;
5831 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5832 num_video_mlines += 1;
5833 num_video_tracks += num_tracks;
5834 }
5835 }
5836 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5837 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5838 format = kSdpFormatReceivedComplexUnifiedPlan;
5839 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5840 format = kSdpFormatReceivedComplexPlanB;
5841 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5842 format = kSdpFormatReceivedSimple;
5843 }
5844 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5845 kSdpFormatReceivedMax);
5846}
5847
Steve Anton0ffaaa22018-02-23 10:31:30 -08005848void PeerConnection::ReportNegotiatedSdpSemantics(
5849 const SessionDescriptionInterface& answer) {
5850 if (!uma_observer_) {
5851 return;
5852 }
5853 switch (answer.description()->msid_signaling()) {
5854 case 0:
5855 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5856 kSdpSemanticNegotiatedNone,
5857 kSdpSemanticNegotiatedMax);
5858 break;
5859 case cricket::kMsidSignalingMediaSection:
5860 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5861 kSdpSemanticNegotiatedUnifiedPlan,
5862 kSdpSemanticNegotiatedMax);
5863 break;
5864 case cricket::kMsidSignalingSsrcAttribute:
5865 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5866 kSdpSemanticNegotiatedPlanB,
5867 kSdpSemanticNegotiatedMax);
5868 break;
5869 case cricket::kMsidSignalingMediaSection |
5870 cricket::kMsidSignalingSsrcAttribute:
5871 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5872 kSdpSemanticNegotiatedMixed,
5873 kSdpSemanticNegotiatedMax);
5874 break;
5875 default:
5876 RTC_NOTREACHED();
5877 }
5878}
5879
Steve Anton75737c02017-11-06 10:37:17 -08005880// We need to check the local/remote description for the Transport instead of
5881// the session, because a new Transport added during renegotiation may have
5882// them unset while the session has them set from the previous negotiation.
5883// Not doing so may trigger the auto generation of transport description and
5884// mess up DTLS identity information, ICE credential, etc.
5885bool PeerConnection::ReadyToUseRemoteCandidate(
5886 const IceCandidateInterface* candidate,
5887 const SessionDescriptionInterface* remote_desc,
5888 bool* valid) {
5889 *valid = true;
5890
5891 const SessionDescriptionInterface* current_remote_desc =
5892 remote_desc ? remote_desc : remote_description();
5893
5894 if (!current_remote_desc) {
5895 return false;
5896 }
5897
5898 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5899 size_t remote_content_size =
5900 current_remote_desc->description()->contents().size();
5901 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005902 RTC_LOG(LS_ERROR)
5903 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5904 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005905
5906 *valid = false;
5907 return false;
5908 }
5909
5910 cricket::ContentInfo content =
5911 current_remote_desc->description()->contents()[mediacontent_index];
5912
5913 const std::string transport_name = GetTransportName(content.name);
5914 if (transport_name.empty()) {
5915 return false;
5916 }
Zhi Huange830e682018-03-30 10:48:35 -07005917 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005918}
5919
5920bool PeerConnection::SrtpRequired() const {
5921 return dtls_enabled_ ||
5922 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5923}
5924
5925void PeerConnection::OnTransportControllerGatheringState(
5926 cricket::IceGatheringState state) {
5927 RTC_DCHECK(signaling_thread()->IsCurrent());
5928 if (state == cricket::kIceGatheringGathering) {
5929 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5930 } else if (state == cricket::kIceGatheringComplete) {
5931 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5932 }
5933}
5934
5935void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005936 std::map<std::string, std::set<cricket::MediaType>>
5937 media_types_by_transport_name;
5938 for (auto transceiver : transceivers_) {
5939 if (transceiver->internal()->channel()) {
5940 const std::string& transport_name =
5941 transceiver->internal()->channel()->transport_name();
5942 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005943 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005944 }
Steve Anton75737c02017-11-06 10:37:17 -08005945 }
5946 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005947 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5948 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005949 }
Zhi Huange830e682018-03-30 10:48:35 -07005950
5951 rtc::Optional<std::string> transport_name = sctp_transport_name();
5952 if (transport_name) {
5953 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08005954 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005955 }
Zhi Huange830e682018-03-30 10:48:35 -07005956
Steve Antonc7b964c2018-02-01 14:39:45 -08005957 for (const auto& entry : media_types_by_transport_name) {
5958 const std::string& transport_name = entry.first;
5959 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005960 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005961 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005962 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005963 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005964 }
5965 }
5966}
5967// Walk through the ConnectionInfos to gather best connection usage
5968// for IPv4 and IPv6.
5969void PeerConnection::ReportBestConnectionState(
5970 const cricket::TransportStats& stats) {
5971 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08005972 for (const cricket::TransportChannelStats& channel_stats :
5973 stats.channel_stats) {
5974 for (const cricket::ConnectionInfo& connection_info :
5975 channel_stats.connection_infos) {
5976 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08005977 continue;
5978 }
5979
5980 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08005981 const cricket::Candidate& local = connection_info.local_candidate;
5982 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08005983
5984 // Increment the counter for IceCandidatePairType.
5985 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
5986 (local.type() == RELAY_PORT_TYPE &&
5987 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
5988 type = kEnumCounterIceCandidatePairTypeTcp;
5989 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
5990 type = kEnumCounterIceCandidatePairTypeUdp;
5991 } else {
5992 RTC_CHECK(0);
5993 }
5994 metrics_observer()->IncrementEnumCounter(
5995 type, GetIceCandidatePairCounter(local, remote),
5996 kIceCandidatePairMax);
5997
5998 // Increment the counter for IP type.
5999 if (local.address().family() == AF_INET) {
6000 metrics_observer()->IncrementEnumCounter(
6001 kEnumCounterAddressFamily, kBestConnections_IPv4,
6002 kPeerConnectionAddressFamilyCounter_Max);
6003
6004 } else if (local.address().family() == AF_INET6) {
6005 metrics_observer()->IncrementEnumCounter(
6006 kEnumCounterAddressFamily, kBestConnections_IPv6,
6007 kPeerConnectionAddressFamilyCounter_Max);
6008 } else {
6009 RTC_CHECK(0);
6010 }
6011
6012 return;
6013 }
6014 }
6015}
6016
6017void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006018 const cricket::TransportStats& stats,
6019 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006020 RTC_DCHECK(metrics_observer());
6021 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6022 return;
6023 }
6024
6025 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6026 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6027 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6028 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6029 return;
6030 }
6031
Steve Antonc7b964c2018-02-01 14:39:45 -08006032 for (cricket::MediaType media_type : media_types) {
6033 PeerConnectionEnumCounterType srtp_counter_type;
6034 PeerConnectionEnumCounterType ssl_counter_type;
6035 switch (media_type) {
6036 case cricket::MEDIA_TYPE_AUDIO:
6037 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6038 ssl_counter_type = kEnumCounterAudioSslCipher;
6039 break;
6040 case cricket::MEDIA_TYPE_VIDEO:
6041 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6042 ssl_counter_type = kEnumCounterVideoSslCipher;
6043 break;
6044 case cricket::MEDIA_TYPE_DATA:
6045 srtp_counter_type = kEnumCounterDataSrtpCipher;
6046 ssl_counter_type = kEnumCounterDataSslCipher;
6047 break;
6048 default:
6049 RTC_NOTREACHED();
6050 continue;
6051 }
6052 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6053 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6054 srtp_crypto_suite);
6055 }
6056 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6057 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6058 ssl_cipher_suite);
6059 }
Steve Anton75737c02017-11-06 10:37:17 -08006060 }
6061}
6062
6063void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6064 RTC_DCHECK(worker_thread()->IsCurrent());
6065 RTC_DCHECK(call_);
6066 call_->OnSentPacket(sent_packet);
6067}
6068
6069const std::string PeerConnection::GetTransportName(
6070 const std::string& content_name) {
6071 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006072 if (channel) {
6073 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006074 }
Steve Anton6fec8802017-12-04 10:37:29 -08006075 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006076 RTC_DCHECK(sctp_mid_);
6077 if (content_name == *sctp_mid_) {
6078 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006079 }
6080 }
6081 // Return an empty string if failed to retrieve the transport name.
6082 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006083}
6084
Steve Anton6fec8802017-12-04 10:37:29 -08006085void PeerConnection::DestroyTransceiverChannel(
6086 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6087 transceiver) {
6088 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006089
Steve Anton6fec8802017-12-04 10:37:29 -08006090 cricket::BaseChannel* channel = transceiver->internal()->channel();
6091 if (channel) {
6092 transceiver->internal()->SetChannel(nullptr);
6093 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006094 }
6095}
6096
6097void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006098 if (rtp_data_channel_) {
6099 OnDataChannelDestroyed();
6100 DestroyBaseChannel(rtp_data_channel_);
6101 rtp_data_channel_ = nullptr;
6102 }
6103
6104 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6105 // grab a reference to this PeerConnection. If this is called from the
6106 // PeerConnection destructor, the RefCountedObject vtable will have already
6107 // been destroyed (since it is a subclass of PeerConnection) and using
6108 // rtc::Bind will cause "Pure virtual function called" error to appear.
6109
6110 if (sctp_transport_) {
6111 OnDataChannelDestroyed();
6112 network_thread()->Invoke<void>(RTC_FROM_HERE,
6113 [this] { DestroySctpTransport_n(); });
6114 }
6115}
6116
6117void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6118 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006119
6120 switch (channel->media_type()) {
6121 case cricket::MEDIA_TYPE_AUDIO:
6122 channel_manager()->DestroyVoiceChannel(
6123 static_cast<cricket::VoiceChannel*>(channel));
6124 break;
6125 case cricket::MEDIA_TYPE_VIDEO:
6126 channel_manager()->DestroyVideoChannel(
6127 static_cast<cricket::VideoChannel*>(channel));
6128 break;
6129 case cricket::MEDIA_TYPE_DATA:
6130 channel_manager()->DestroyRtpDataChannel(
6131 static_cast<cricket::RtpDataChannel*>(channel));
6132 break;
6133 default:
6134 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6135 break;
6136 }
Zhi Huange830e682018-03-30 10:48:35 -07006137}
Steve Anton6fec8802017-12-04 10:37:29 -08006138
Zhi Huange830e682018-03-30 10:48:35 -07006139void PeerConnection::OnRtpTransportChanged(
6140 const std::string& mid,
6141 RtpTransportInternal* rtp_transport) {
6142 auto base_channel = GetChannel(mid);
6143 if (base_channel) {
6144 base_channel->SetRtpTransport(rtp_transport);
6145 }
6146}
Steve Anton6fec8802017-12-04 10:37:29 -08006147
Zhi Huange830e682018-03-30 10:48:35 -07006148void PeerConnection::OnDtlsTransportChanged(
6149 const std::string& mid,
6150 cricket::DtlsTransportInternal* dtls_transport) {
6151 if (sctp_transport_) {
6152 RTC_DCHECK(mid == sctp_mid_);
Zhi Huang644fde42018-04-02 19:16:26 -07006153 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006154 }
6155}
6156
Harald Alvestrand89061872018-01-02 14:08:34 +01006157void PeerConnection::ClearStatsCache() {
6158 if (stats_collector_) {
6159 stats_collector_->ClearCachedStatsReport();
6160 }
6161}
6162
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006163} // namespace webrtc