blob: 6557fca23ba524f2278e52e9e85b980ee464f3cb [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,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700885 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100886 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700887
888 RTCError config_error = ValidateConfiguration(configuration);
889 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100890 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700891 return false;
892 }
893
Benjamin Wrightcab58882018-05-02 15:12:47 -0700894 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_ERROR)
896 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100897 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800898 return false;
899 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200900
Benjamin Wrightcab58882018-05-02 15:12:47 -0700901 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800902 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100903 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100904 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800905 return false;
906 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700907
Benjamin Wrightcab58882018-05-02 15:12:47 -0700908 observer_ = dependencies.observer;
909 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700910 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
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;
Zhi Huang365381f2018-04-13 16:44:34 -0700935 config.transport_observer = this;
Zhi Huange830e682018-03-30 10:48:35 -0700936#if defined(ENABLE_EXTERNAL_AUTH)
937 config.enable_external_auth = true;
938#endif
939 transport_controller_.reset(new JsepTransportController(
940 signaling_thread(), network_thread(), port_allocator_.get(), config));
941 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800942 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700943 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800944 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700945 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800946 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700947 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800948 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
949 transport_controller_->SignalDtlsHandshakeError.connect(
950 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
951
952 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700953
deadbeefab9b2d12015-10-14 11:33:11 -0700954 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700955 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000956
Steve Antonba818672017-11-06 10:21:57 -0800957 configuration_ = configuration;
958
Steve Anton75737c02017-11-06 10:37:17 -0800959 // Obtain a certificate from RTCConfiguration if any were provided (optional).
960 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
961 if (!configuration.certificates.empty()) {
962 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
963 // just picking the first one. The decision should be made based on the DTLS
964 // handshake. The DTLS negotiations need to know about all certificates.
965 certificate = configuration.certificates[0];
966 }
967
Steve Antond25da372017-11-06 14:50:29 -0800968 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800969
970 if (options.disable_encryption) {
971 dtls_enabled_ = false;
972 } else {
973 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700974 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800975 // |configuration| can override the default |dtls_enabled_| value.
976 if (configuration.enable_dtls_srtp) {
977 dtls_enabled_ = *(configuration.enable_dtls_srtp);
978 }
979 }
980
981 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
982 // It takes precendence over the disable_sctp_data_channels
983 // PeerConnectionFactoryInterface::Options.
984 if (configuration.enable_rtp_data_channel) {
985 data_channel_type_ = cricket::DCT_RTP;
986 } else {
987 // DTLS has to be enabled to use SCTP.
988 if (!options.disable_sctp_data_channels && dtls_enabled_) {
989 data_channel_type_ = cricket::DCT_SCTP;
990 }
991 }
992
993 video_options_.screencast_min_bitrate_kbps =
994 configuration.screencast_min_bitrate;
995 audio_options_.combined_audio_video_bwe =
996 configuration.combined_audio_video_bwe;
997
998 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100999 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001000
1001 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001002 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001003
1004 // Whether the certificate generator/certificate is null or not determines
1005 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1006 // the right instructions by clearing the variables if needed.
1007 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001008 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001009 certificate = nullptr;
1010 } else if (certificate) {
1011 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001012 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001013 }
1014
1015 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1016 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001017 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001018 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1019 this, &PeerConnection::OnCertificateReady);
1020
1021 if (options.disable_encryption) {
1022 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1023 }
1024
1025 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1026 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027
Steve Anton4171afb2017-11-20 10:20:22 -08001028 // Add default audio/video transceivers for Plan B SDP.
1029 if (!IsUnifiedPlan()) {
1030 transceivers_.push_back(
1031 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1032 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1033 transceivers_.push_back(
1034 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1035 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1036 }
1037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 return true;
1039}
1040
Steve Anton038834f2017-07-14 15:59:59 -07001041RTCError PeerConnection::ValidateConfiguration(
1042 const RTCConfiguration& config) const {
1043 if (config.ice_regather_interval_range &&
1044 config.continual_gathering_policy == GATHER_ONCE) {
1045 return RTCError(RTCErrorType::INVALID_PARAMETER,
1046 "ice_regather_interval_range specified but continual "
1047 "gathering policy is GATHER_ONCE");
1048 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001049 auto result =
1050 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1051 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001052}
1053
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001054rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001055PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001056 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1057 "Plan SdpSemantics. Please use GetSenders "
1058 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001059 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060}
1061
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001062rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001064 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1065 "Plan SdpSemantics. Please use GetReceivers "
1066 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001067 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068}
1069
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001070bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001071 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1072 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001073 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001074 if (IsClosed()) {
1075 return false;
1076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 return false;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080
1081 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001082 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1083 observer->SignalAudioTrackAdded.connect(this,
1084 &PeerConnection::OnAudioTrackAdded);
1085 observer->SignalAudioTrackRemoved.connect(
1086 this, &PeerConnection::OnAudioTrackRemoved);
1087 observer->SignalVideoTrackAdded.connect(this,
1088 &PeerConnection::OnVideoTrackAdded);
1089 observer->SignalVideoTrackRemoved.connect(
1090 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001091 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001092
deadbeefab9b2d12015-10-14 11:33:11 -07001093 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001094 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001095 }
1096 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001097 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001100 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 observer_->OnRenegotiationNeeded();
1102 return true;
1103}
1104
1105void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001106 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1107 "Plan SdpSemantics. Please use RemoveTrack "
1108 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001109 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001110 if (!IsClosed()) {
1111 for (const auto& track : local_stream->GetAudioTracks()) {
1112 RemoveAudioTrack(track.get(), local_stream);
1113 }
1114 for (const auto& track : local_stream->GetVideoTracks()) {
1115 RemoveVideoTrack(track.get(), local_stream);
1116 }
deadbeefab9b2d12015-10-14 11:33:11 -07001117 }
deadbeefab9b2d12015-10-14 11:33:11 -07001118 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001119 stream_observers_.erase(
1120 std::remove_if(
1121 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001122 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001123 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001124 }),
1125 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001126
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127 if (IsClosed()) {
1128 return;
1129 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 observer_->OnRenegotiationNeeded();
1131}
1132
deadbeefe1f9d832016-01-14 15:35:42 -08001133rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1134 MediaStreamTrackInterface* track,
1135 std::vector<MediaStreamInterface*> streams) {
1136 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001137 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001138 for (auto* stream : streams) {
1139 if (!stream) {
1140 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1141 return nullptr;
1142 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001143 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001144 }
Seth Hampson845e8782018-03-02 11:34:10 -08001145 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001146 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001147 return nullptr;
1148 }
Steve Antonf9381f02017-12-14 10:23:57 -08001149 return sender_or_error.MoveValue();
1150}
1151
Steve Anton2d6c76a2018-01-05 17:10:52 -08001152RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001153 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001154 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001155 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001156 if (!track) {
1157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1158 }
1159 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1160 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1162 "Track has invalid kind: " + track->kind());
1163 }
Steve Antonf9381f02017-12-14 10:23:57 -08001164 if (IsClosed()) {
1165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1166 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001167 }
Steve Anton4171afb2017-11-20 10:20:22 -08001168 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001169 LOG_AND_RETURN_ERROR(
1170 RTCErrorType::INVALID_PARAMETER,
1171 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001172 }
Steve Antonf9381f02017-12-14 10:23:57 -08001173 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001174 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1175 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001176 if (sender_or_error.ok()) {
1177 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001178 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001179 }
1180 return sender_or_error;
1181}
deadbeefe1f9d832016-01-14 15:35:42 -08001182
Steve Antonf9381f02017-12-14 10:23:57 -08001183RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1184PeerConnection::AddTrackPlanB(
1185 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001186 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001187 if (stream_ids.size() > 1u) {
1188 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1189 "AddTrack with more than one stream is not "
1190 "supported with Plan B semantics.");
1191 }
1192 std::vector<std::string> adjusted_stream_ids = stream_ids;
1193 if (adjusted_stream_ids.empty()) {
1194 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1195 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001196 cricket::MediaType media_type =
1197 (track->kind() == MediaStreamTrackInterface::kAudioKind
1198 ? cricket::MEDIA_TYPE_AUDIO
1199 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001200 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001201 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001202 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001203 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001204 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001205 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001206 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001207 if (sender_info) {
1208 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001209 }
Steve Antonf9381f02017-12-14 10:23:57 -08001210 } else {
1211 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001212 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001213 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001214 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001215 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001216 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001217 if (sender_info) {
1218 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001219 }
deadbeefe1f9d832016-01-14 15:35:42 -08001220 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001221 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001222}
deadbeefe1f9d832016-01-14 15:35:42 -08001223
Steve Antonf9381f02017-12-14 10:23:57 -08001224RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1225PeerConnection::AddTrackUnifiedPlan(
1226 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001227 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001228 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1229 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001230 RTC_LOG(LS_INFO) << "Reusing an existing "
1231 << cricket::MediaTypeToString(transceiver->media_type())
1232 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001233 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001234 transceiver->internal()->set_direction(
1235 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001236 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001239 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001240 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001241 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001242 } else {
1243 cricket::MediaType media_type =
1244 (track->kind() == MediaStreamTrackInterface::kAudioKind
1245 ? cricket::MEDIA_TYPE_AUDIO
1246 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001247 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1248 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001249 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001250 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1251 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001252 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001253 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001254 }
Steve Antonf9381f02017-12-14 10:23:57 -08001255 return transceiver->sender();
1256}
1257
1258rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1259PeerConnection::FindFirstTransceiverForAddedTrack(
1260 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1261 RTC_DCHECK(track);
1262 for (auto transceiver : transceivers_) {
1263 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001264 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001265 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001266 !transceiver->internal()->has_ever_been_used_to_send() &&
1267 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001268 return transceiver;
1269 }
1270 }
1271 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001272}
1273
1274bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1275 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001276 return RemoveTrackInternal(sender).ok();
1277}
1278
1279RTCError PeerConnection::RemoveTrackInternal(
1280 rtc::scoped_refptr<RtpSenderInterface> sender) {
1281 if (!sender) {
1282 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1283 }
deadbeefe1f9d832016-01-14 15:35:42 -08001284 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1286 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001287 }
Steve Antonf9381f02017-12-14 10:23:57 -08001288 if (IsUnifiedPlan()) {
1289 auto transceiver = FindTransceiverBySender(sender);
1290 if (!transceiver || !sender->track()) {
1291 return RTCError::OK();
1292 }
1293 sender->SetTrack(nullptr);
1294 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001295 transceiver->internal()->set_direction(
1296 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001297 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001300 }
Steve Anton4171afb2017-11-20 10:20:22 -08001301 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001302 bool removed;
1303 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1304 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1305 } else {
1306 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1307 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1308 }
1309 if (!removed) {
1310 LOG_AND_RETURN_ERROR(
1311 RTCErrorType::INVALID_PARAMETER,
1312 "Couldn't find sender " + sender->id() + " to remove.");
1313 }
Steve Anton4171afb2017-11-20 10:20:22 -08001314 }
deadbeefe1f9d832016-01-14 15:35:42 -08001315 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001316 return RTCError::OK();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindTransceiverBySender(
1321 rtc::scoped_refptr<RtpSenderInterface> sender) {
1322 for (auto transceiver : transceivers_) {
1323 if (transceiver->sender() == sender) {
1324 return transceiver;
1325 }
1326 }
1327 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001328}
1329
Steve Anton9158ef62017-11-27 13:01:52 -08001330RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1331PeerConnection::AddTransceiver(
1332 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1333 return AddTransceiver(track, RtpTransceiverInit());
1334}
1335
1336RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1337PeerConnection::AddTransceiver(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1339 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001340 RTC_CHECK(IsUnifiedPlan())
1341 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001342 if (!track) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1344 }
1345 cricket::MediaType media_type;
1346 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1347 media_type = cricket::MEDIA_TYPE_AUDIO;
1348 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1349 media_type = cricket::MEDIA_TYPE_VIDEO;
1350 } else {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1352 "Track kind is not audio or video");
1353 }
1354 return AddTransceiver(media_type, track, init);
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1359 return AddTransceiver(media_type, RtpTransceiverInit());
1360}
1361
1362RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1363PeerConnection::AddTransceiver(cricket::MediaType media_type,
1364 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001365 RTC_CHECK(IsUnifiedPlan())
1366 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001367 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1368 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1370 "media type is not audio or video");
1371 }
1372 return AddTransceiver(media_type, nullptr, init);
1373}
1374
1375RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1376PeerConnection::AddTransceiver(
1377 cricket::MediaType media_type,
1378 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001379 const RtpTransceiverInit& init,
1380 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001381 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1382 media_type == cricket::MEDIA_TYPE_VIDEO));
1383 if (track) {
1384 RTC_DCHECK_EQ(media_type,
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind
1386 ? cricket::MEDIA_TYPE_AUDIO
1387 : cricket::MEDIA_TYPE_VIDEO));
1388 }
1389
1390 // TODO(bugs.webrtc.org/7600): Verify init.
1391
Steve Anton3d954a62018-04-02 11:27:23 -07001392 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1393 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001394 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1396 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1397 transceiver->internal()->set_direction(init.direction);
1398
Steve Anton22da89f2018-01-25 13:58:07 -08001399 if (fire_callback) {
1400 observer_->OnRenegotiationNeeded();
1401 }
Steve Antonf9381f02017-12-14 10:23:57 -08001402
1403 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1404}
1405
Steve Anton02ee47c2018-01-10 16:26:06 -08001406rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1407PeerConnection::CreateSender(
1408 cricket::MediaType media_type,
1409 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001410 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001411 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001412 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1413 RTC_DCHECK(!track ||
1414 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1415 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1416 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001417 new AudioRtpSender(worker_thread(),
1418 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001419 stream_ids, stats_.get()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001420 } else {
1421 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1422 RTC_DCHECK(!track ||
1423 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1424 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1425 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001426 new VideoRtpSender(worker_thread(),
1427 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001428 stream_ids));
Steve Anton02ee47c2018-01-10 16:26:06 -08001429 }
Seth Hampson845e8782018-03-02 11:34:10 -08001430 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 return sender;
1432}
1433
1434rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1435PeerConnection::CreateReceiver(cricket::MediaType media_type,
1436 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001437 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1438 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001439 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001440 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001441 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001442 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001443 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001444 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001445 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1446 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001447 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Steve Anton9158ef62017-11-27 13:01:52 -08001448 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001449 return receiver;
1450}
1451
1452rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1453PeerConnection::CreateAndAddTransceiver(
1454 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1455 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1456 receiver) {
1457 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1458 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001459 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001460 transceiver->internal()->SignalNegotiationNeeded.connect(
1461 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001462 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001463}
1464
Steve Anton52d86772018-02-20 15:48:12 -08001465void PeerConnection::OnNegotiationNeeded() {
1466 RTC_DCHECK_RUN_ON(signaling_thread());
1467 RTC_DCHECK(!IsClosed());
1468 observer_->OnRenegotiationNeeded();
1469}
1470
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001471rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001472 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001473 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001474 if (IsClosed()) {
1475 return nullptr;
1476 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001477 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001478 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001479 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 }
Steve Anton4171afb2017-11-20 10:20:22 -08001481 auto track_sender = FindSenderForTrack(track);
1482 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001483 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001484 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001485 }
1486
Steve Anton4171afb2017-11-20 10:20:22 -08001487 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488}
1489
deadbeeffac06552015-11-25 11:26:01 -08001490rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001491 const std::string& kind,
1492 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001493 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1494 "Plan SdpSemantics. Please use AddTransceiver "
1495 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001496 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001497 if (IsClosed()) {
1498 return nullptr;
1499 }
Steve Anton4171afb2017-11-20 10:20:22 -08001500
Seth Hampson5b4f0752018-04-02 16:31:36 -07001501 // Internally we need to have one stream with Plan B semantics, so we
1502 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001503 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001504 if (stream_id.empty()) {
1505 stream_ids.push_back(rtc::CreateRandomUuid());
1506 RTC_LOG(LS_INFO)
1507 << "No stream_id specified for sender. Generated stream ID: "
1508 << stream_ids[0];
1509 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001510 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001511 }
1512
Steve Anton4171afb2017-11-20 10:20:22 -08001513 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001514 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001515 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001516 auto* audio_sender =
1517 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001518 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001519 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001520 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001521 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001522 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001523 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001524 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001525 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001526 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001527 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001528 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001529 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001530 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001531 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001532 }
Steve Anton4171afb2017-11-20 10:20:22 -08001533
deadbeefe1f9d832016-01-14 15:35:42 -08001534 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001535}
1536
deadbeef70ab1a12015-09-28 16:53:55 -07001537std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1538 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001539 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001540 for (auto sender : GetSendersInternal()) {
1541 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001542 }
1543 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001544}
1545
Steve Anton4171afb2017-11-20 10:20:22 -08001546std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1547PeerConnection::GetSendersInternal() const {
1548 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1549 all_senders;
1550 for (auto transceiver : transceivers_) {
1551 auto senders = transceiver->internal()->senders();
1552 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1553 }
1554 return all_senders;
1555}
1556
deadbeef70ab1a12015-09-28 16:53:55 -07001557std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1558PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001559 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001560 for (const auto& receiver : GetReceiversInternal()) {
1561 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001562 }
1563 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001564}
1565
Steve Anton4171afb2017-11-20 10:20:22 -08001566std::vector<
1567 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1568PeerConnection::GetReceiversInternal() const {
1569 std::vector<
1570 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1571 all_receivers;
1572 for (auto transceiver : transceivers_) {
1573 auto receivers = transceiver->internal()->receivers();
1574 all_receivers.insert(all_receivers.end(), receivers.begin(),
1575 receivers.end());
1576 }
1577 return all_receivers;
1578}
1579
Steve Anton9158ef62017-11-27 13:01:52 -08001580std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1581PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001582 RTC_CHECK(IsUnifiedPlan())
1583 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001584 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1585 for (auto transceiver : transceivers_) {
1586 all_transceivers.push_back(transceiver);
1587 }
1588 return all_transceivers;
1589}
1590
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001591bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001592 MediaStreamTrackInterface* track,
1593 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001594 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001595 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001596 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001597 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001598 return false;
1599 }
1600
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001601 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001602 // The StatsCollector is used to tell if a track is valid because it may
1603 // remember tracks that the PeerConnection previously removed.
1604 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001605 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1606 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001607 return false;
1608 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001609 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001610 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001611 return true;
1612}
1613
hbos74e1a4f2016-09-15 23:33:01 -07001614void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001615 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001616 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001617 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001618 stats_collector_->GetStatsReport(callback);
1619}
1620
Henrik Boström1df1bf82018-03-20 13:24:20 +01001621void PeerConnection::GetStats(
1622 rtc::scoped_refptr<RtpSenderInterface> selector,
1623 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1624 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1625 RTC_DCHECK(callback);
1626 RTC_DCHECK(stats_collector_);
1627 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1628 if (selector) {
1629 for (const auto& proxy_transceiver : transceivers_) {
1630 for (const auto& proxy_sender :
1631 proxy_transceiver->internal()->senders()) {
1632 if (proxy_sender == selector) {
1633 internal_sender = proxy_sender->internal();
1634 break;
1635 }
1636 }
1637 if (internal_sender)
1638 break;
1639 }
1640 }
1641 // If there is no |internal_sender| then |selector| is either null or does not
1642 // belong to the PeerConnection (in Plan B, senders can be removed from the
1643 // PeerConnection). This means that "all the stats objects representing the
1644 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1645 // produces an empty stats report.
1646 stats_collector_->GetStatsReport(internal_sender, callback);
1647}
1648
1649void PeerConnection::GetStats(
1650 rtc::scoped_refptr<RtpReceiverInterface> selector,
1651 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1652 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1653 RTC_DCHECK(callback);
1654 RTC_DCHECK(stats_collector_);
1655 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1656 if (selector) {
1657 for (const auto& proxy_transceiver : transceivers_) {
1658 for (const auto& proxy_receiver :
1659 proxy_transceiver->internal()->receivers()) {
1660 if (proxy_receiver == selector) {
1661 internal_receiver = proxy_receiver->internal();
1662 break;
1663 }
1664 }
1665 if (internal_receiver)
1666 break;
1667 }
1668 }
1669 // If there is no |internal_receiver| then |selector| is either null or does
1670 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1671 // the PeerConnection). This means that "all the stats objects representing
1672 // the selector" is an empty set. Invoking GetStatsReport() with a null
1673 // selector produces an empty stats report.
1674 stats_collector_->GetStatsReport(internal_receiver, callback);
1675}
1676
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001677PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1678 return signaling_state_;
1679}
1680
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681PeerConnectionInterface::IceConnectionState
1682PeerConnection::ice_connection_state() {
1683 return ice_connection_state_;
1684}
1685
1686PeerConnectionInterface::IceGatheringState
1687PeerConnection::ice_gathering_state() {
1688 return ice_gathering_state_;
1689}
1690
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001691rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001692PeerConnection::CreateDataChannel(
1693 const std::string& label,
1694 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001695 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001696
deadbeefab9b2d12015-10-14 11:33:11 -07001697 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001698
kwibergd1fe2812016-04-27 06:47:29 -07001699 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001700 if (config) {
1701 internal_config.reset(new InternalDataChannelInit(*config));
1702 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001703 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001704 InternalCreateDataChannel(label, internal_config.get()));
1705 if (!channel.get()) {
1706 return nullptr;
1707 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001709 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1710 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001711 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001712 observer_->OnRenegotiationNeeded();
1713 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001714
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001715 return DataChannelProxy::Create(signaling_thread(), channel.get());
1716}
1717
1718void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1719 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001720 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001721
zhihuang1c378ed2017-08-17 14:10:50 -07001722 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1723 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1724 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1725 // compares the mandatory fields parsed with the mandatory fields added in the
1726 // |constraints| and some downstream applications might create offers with
1727 // mandatory fields which would not be parsed in the helper method. For
1728 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1729 // |constraints| as a mandatory field but it is not parsed.
1730 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001731
zhihuang1c378ed2017-08-17 14:10:50 -07001732 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001733}
1734
1735void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1736 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001737 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001738
nisse7ce109a2017-01-31 00:57:56 -08001739 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001741 return;
1742 }
deadbeefab9b2d12015-10-14 11:33:11 -07001743
Steve Anton8d3444d2017-10-20 15:30:51 -07001744 if (IsClosed()) {
1745 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001746 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001747 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001748 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001749 return;
1750 }
1751
zhihuang1c378ed2017-08-17 14:10:50 -07001752 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001753 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001754 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001755 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001756 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001757 return;
1758 }
1759
Steve Anton22da89f2018-01-25 13:58:07 -08001760 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1761 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1762 if (IsUnifiedPlan()) {
1763 RTCError error = HandleLegacyOfferOptions(options);
1764 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001765 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001766 return;
1767 }
1768 }
1769
zhihuang1c378ed2017-08-17 14:10:50 -07001770 cricket::MediaSessionOptions session_options;
1771 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001772 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773}
1774
Steve Anton22da89f2018-01-25 13:58:07 -08001775RTCError PeerConnection::HandleLegacyOfferOptions(
1776 const RTCOfferAnswerOptions& options) {
1777 RTC_DCHECK(IsUnifiedPlan());
1778
1779 if (options.offer_to_receive_audio == 0) {
1780 RemoveRecvDirectionFromReceivingTransceiversOfType(
1781 cricket::MEDIA_TYPE_AUDIO);
1782 } else if (options.offer_to_receive_audio == 1) {
1783 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1784 } else if (options.offer_to_receive_audio > 1) {
1785 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1786 "offer_to_receive_audio > 1 is not supported.");
1787 }
1788
1789 if (options.offer_to_receive_video == 0) {
1790 RemoveRecvDirectionFromReceivingTransceiversOfType(
1791 cricket::MEDIA_TYPE_VIDEO);
1792 } else if (options.offer_to_receive_video == 1) {
1793 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1794 } else if (options.offer_to_receive_video > 1) {
1795 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1796 "offer_to_receive_video > 1 is not supported.");
1797 }
1798
1799 return RTCError::OK();
1800}
1801
1802void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1803 cricket::MediaType media_type) {
1804 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001805 RtpTransceiverDirection new_direction =
1806 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1807 if (new_direction != transceiver->direction()) {
1808 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1809 << " transceiver (MID="
1810 << transceiver->mid().value_or("<not set>") << ") from "
1811 << RtpTransceiverDirectionToString(
1812 transceiver->direction())
1813 << " to "
1814 << RtpTransceiverDirectionToString(new_direction)
1815 << " since CreateOffer specified offer_to_receive=0";
1816 transceiver->internal()->set_direction(new_direction);
1817 }
Steve Anton22da89f2018-01-25 13:58:07 -08001818 }
1819}
1820
1821void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1822 cricket::MediaType media_type) {
1823 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001824 RTC_LOG(LS_INFO)
1825 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1826 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001827 RtpTransceiverInit init;
1828 init.direction = RtpTransceiverDirection::kRecvOnly;
1829 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1830 }
1831}
1832
1833std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1834PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1835 std::vector<
1836 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1837 receiving_transceivers;
1838 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001839 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001840 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1841 receiving_transceivers.push_back(transceiver);
1842 }
1843 }
1844 return receiving_transceivers;
1845}
1846
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001847void PeerConnection::CreateAnswer(
1848 CreateSessionDescriptionObserver* observer,
1849 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001850 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001851
nisse7ce109a2017-01-31 00:57:56 -08001852 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001853 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854 return;
1855 }
deadbeefab9b2d12015-10-14 11:33:11 -07001856
zhihuang1c378ed2017-08-17 14:10:50 -07001857 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1858 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1859 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001860 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001861 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001862 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001863 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001864 return;
1865 }
1866
Steve Anton8d3444d2017-10-20 15:30:51 -07001867 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001868}
1869
1870void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1871 const RTCOfferAnswerOptions& options) {
1872 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001873 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001874 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001875 return;
1876 }
1877
Steve Antondffead82018-02-06 10:31:29 -08001878 if (!(signaling_state_ == kHaveRemoteOffer ||
1879 signaling_state_ == kHaveLocalPrAnswer)) {
1880 std::string error =
1881 "PeerConnection cannot create an answer in a state other than "
1882 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001883 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001884 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001885 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001886 return;
1887 }
1888
Steve Antondffead82018-02-06 10:31:29 -08001889 // The remote description should be set if we're in the right state.
1890 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001891
Steve Anton22da89f2018-01-25 13:58:07 -08001892 if (IsUnifiedPlan()) {
1893 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1894 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1895 "supported with Unified Plan semantics. Use the "
1896 "RtpTransceiver API instead.";
1897 }
1898 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1899 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1900 "supported with Unified Plan semantics. Use the "
1901 "RtpTransceiver API instead.";
1902 }
1903 }
1904
htaa2a49d92016-03-04 02:51:39 -08001905 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001906 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001907
Steve Antond25da372017-11-06 14:50:29 -08001908 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001909}
1910
1911void PeerConnection::SetLocalDescription(
1912 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001913 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001914 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001915
Steve Anton80dd7b52018-02-16 17:08:42 -08001916 // The SetLocalDescription contract is that we take ownership of the session
1917 // description regardless of the outcome, so wrap it in a unique_ptr right
1918 // away. Ideally, SetLocalDescription's signature will be changed to take the
1919 // description as a unique_ptr argument to formalize this agreement.
1920 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1921
nisse7ce109a2017-01-31 00:57:56 -08001922 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001923 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924 return;
1925 }
Steve Anton8a006912017-12-04 15:25:56 -08001926
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001928 PostSetSessionDescriptionFailure(
1929 observer,
1930 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 return;
1932 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001933
Steve Anton80dd7b52018-02-16 17:08:42 -08001934 // If a session error has occurred the PeerConnection is in a possibly
1935 // inconsistent state so fail right away.
1936 if (session_error() != SessionError::kNone) {
1937 std::string error_message = GetSessionErrorMsg();
1938 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001939 PostSetSessionDescriptionFailure(
1940 observer,
1941 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001942 return;
1943 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001944
Steve Anton80dd7b52018-02-16 17:08:42 -08001945 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1946 if (!error.ok()) {
1947 std::string error_message = GetSetDescriptionErrorMessage(
1948 cricket::CS_LOCAL, desc->GetType(), error);
1949 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001950 PostSetSessionDescriptionFailure(
1951 observer,
1952 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001953 return;
1954 }
1955
1956 // Grab the description type before moving ownership to ApplyLocalDescription,
1957 // which may destroy it before returning.
1958 const SdpType type = desc->GetType();
1959
1960 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001961 // |desc| may be destroyed at this point.
1962
1963 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001964 // If ApplyLocalDescription fails, the PeerConnection could be in an
1965 // inconsistent state, so act conservatively here and set the session error
1966 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1967 SetSessionError(SessionError::kContent, error.message());
1968 std::string error_message =
1969 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1970 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001971 PostSetSessionDescriptionFailure(
1972 observer,
1973 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001974 return;
1975 }
Steve Anton8a006912017-12-04 15:25:56 -08001976 RTC_DCHECK(local_description());
1977
1978 PostSetSessionDescriptionSuccess(observer);
1979
Steve Anton8a006912017-12-04 15:25:56 -08001980 // MaybeStartGathering needs to be called after posting
1981 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1982 // before signaling that SetLocalDescription completed.
1983 transport_controller_->MaybeStartGathering();
1984
Steve Antona3a92c22017-12-07 10:27:41 -08001985 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001986 // TODO(deadbeef): We already had to hop to the network thread for
1987 // MaybeStartGathering...
1988 network_thread()->Invoke<void>(
1989 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1990 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001991 // Make UMA notes about what was agreed to.
1992 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001993 }
1994}
1995
1996RTCError PeerConnection::ApplyLocalDescription(
1997 std::unique_ptr<SessionDescriptionInterface> desc) {
1998 RTC_DCHECK_RUN_ON(signaling_thread());
1999 RTC_DCHECK(desc);
2000
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002001 // Update stats here so that we have the most recent stats for tracks and
2002 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002003 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002004
Steve Antondcc3c022017-12-22 16:02:54 -08002005 // Take a reference to the old local description since it's used below to
2006 // compare against the new local description. When setting the new local
2007 // description, grab ownership of the replaced session description in case it
2008 // is the same as |old_local_description|, to keep it alive for the duration
2009 // of the method.
2010 const SessionDescriptionInterface* old_local_description =
2011 local_description();
2012 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002013 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002014 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002015 replaced_local_description = pending_local_description_
2016 ? std::move(pending_local_description_)
2017 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002018 current_local_description_ = std::move(desc);
2019 pending_local_description_ = nullptr;
2020 current_remote_description_ = std::move(pending_remote_description_);
2021 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002022 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002023 pending_local_description_ = std::move(desc);
2024 }
2025 // The session description to apply now must be accessed by
2026 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002027 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002028
Zhi Huange830e682018-03-30 10:48:35 -07002029 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2030 if (!error.ok()) {
2031 return error;
2032 }
2033
Steve Antondcc3c022017-12-22 16:02:54 -08002034 if (IsUnifiedPlan()) {
2035 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002036 cricket::CS_LOCAL, *local_description(), old_local_description,
2037 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002038 if (!error.ok()) {
2039 return error;
2040 }
Steve Antondcc3c022017-12-22 16:02:54 -08002041 for (auto transceiver : transceivers_) {
2042 const ContentInfo* content =
2043 FindMediaSectionForTransceiver(transceiver, local_description());
2044 if (!content) {
2045 continue;
2046 }
2047 const MediaContentDescription* media_desc = content->media_description();
2048 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2049 transceiver->internal()->set_current_direction(media_desc->direction());
2050 }
2051 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002052 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2053 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002054 transceiver->Stop();
2055 }
2056 }
2057 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002058 // Media channels will be created only when offer is set. These may use new
2059 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002060 if (type == SdpType::kOffer) {
2061 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2062 // description is applied. Restore back to old description.
2063 RTCError error = CreateChannels(*local_description()->description());
2064 if (!error.ok()) {
2065 return error;
2066 }
2067 }
Steve Antondcc3c022017-12-22 16:02:54 -08002068 // Remove unused channels if MediaContentDescription is rejected.
2069 RemoveUnusedChannels(local_description()->description());
2070 }
Steve Anton8a006912017-12-04 15:25:56 -08002071
Zhi Huange830e682018-03-30 10:48:35 -07002072 error = UpdateSessionState(type, cricket::CS_LOCAL,
2073 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002074 if (!error.ok()) {
2075 return error;
2076 }
Steve Antondcc3c022017-12-22 16:02:54 -08002077
Steve Anton8a006912017-12-04 15:25:56 -08002078 if (remote_description()) {
2079 // Now that we have a local description, we can push down remote candidates.
2080 UseCandidatesInSessionDescription(remote_description());
2081 }
2082
2083 pending_ice_restarts_.clear();
2084 if (session_error() != SessionError::kNone) {
2085 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2086 }
2087
deadbeefab9b2d12015-10-14 11:33:11 -07002088 // If setting the description decided our SSL role, allocate any necessary
2089 // SCTP sids.
2090 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002091 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002092 AllocateSctpSids(role);
2093 }
2094
Steve Antond3679212018-01-17 17:41:02 -08002095 if (IsUnifiedPlan()) {
2096 for (auto transceiver : transceivers_) {
2097 const ContentInfo* content =
2098 FindMediaSectionForTransceiver(transceiver, local_description());
2099 if (!content) {
2100 continue;
2101 }
Steve Anton74255ff2018-01-24 18:32:57 -08002102 const auto& streams = content->media_description()->streams();
2103 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002104 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002105 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002106 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002107 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002108 }
2109 }
2110 } else {
2111 // Plan B semantics.
2112
Steve Antondcc3c022017-12-22 16:02:54 -08002113 // Update state and SSRC of local MediaStreams and DataChannels based on the
2114 // local session description.
2115 const cricket::ContentInfo* audio_content =
2116 GetFirstAudioContent(local_description()->description());
2117 if (audio_content) {
2118 if (audio_content->rejected) {
2119 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2120 } else {
2121 const cricket::AudioContentDescription* audio_desc =
2122 audio_content->media_description()->as_audio();
2123 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2124 }
deadbeeffaac4972015-11-12 15:33:07 -08002125 }
deadbeefab9b2d12015-10-14 11:33:11 -07002126
Steve Antondcc3c022017-12-22 16:02:54 -08002127 const cricket::ContentInfo* video_content =
2128 GetFirstVideoContent(local_description()->description());
2129 if (video_content) {
2130 if (video_content->rejected) {
2131 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2132 } else {
2133 const cricket::VideoContentDescription* video_desc =
2134 video_content->media_description()->as_video();
2135 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2136 }
deadbeeffaac4972015-11-12 15:33:07 -08002137 }
deadbeefab9b2d12015-10-14 11:33:11 -07002138 }
2139
2140 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002141 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002142 if (data_content) {
2143 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002144 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002145 if (rtc::starts_with(data_desc->protocol().data(),
2146 cricket::kMediaProtocolRtpPrefix)) {
2147 UpdateLocalRtpDataChannels(data_desc->streams());
2148 }
2149 }
2150
Steve Anton8a006912017-12-04 15:25:56 -08002151 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002152}
2153
2154void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002155 SetSessionDescriptionObserver* observer,
2156 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002157 SetRemoteDescription(
2158 std::unique_ptr<SessionDescriptionInterface>(desc),
2159 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2160 new SetRemoteDescriptionObserverAdapter(this, observer)));
2161}
2162
2163void PeerConnection::SetRemoteDescription(
2164 std::unique_ptr<SessionDescriptionInterface> desc,
2165 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002166 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002167
nisse7ce109a2017-01-31 00:57:56 -08002168 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002169 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002170 return;
2171 }
Steve Anton8a006912017-12-04 15:25:56 -08002172
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002173 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002174 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002175 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176 return;
2177 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002178
Steve Anton80dd7b52018-02-16 17:08:42 -08002179 // If a session error has occurred the PeerConnection is in a possibly
2180 // inconsistent state so fail right away.
2181 if (session_error() != SessionError::kNone) {
2182 std::string error_message = GetSessionErrorMsg();
2183 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2184 observer->OnSetRemoteDescriptionComplete(
2185 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2186 return;
2187 }
Steve Anton71439a62018-02-15 11:53:06 -08002188
Steve Antonba42e992018-04-09 14:10:01 -07002189 if (desc->GetType() == SdpType::kOffer) {
2190 // Report to UMA the format of the received offer.
2191 ReportSdpFormatReceived(*desc);
2192 }
2193
Steve Anton80dd7b52018-02-16 17:08:42 -08002194 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002195 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002196 std::string error_message = GetSetDescriptionErrorMessage(
2197 cricket::CS_REMOTE, desc->GetType(), error);
2198 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002199 observer->OnSetRemoteDescriptionComplete(
2200 RTCError(error.type(), std::move(error_message)));
2201 return;
2202 }
Steve Anton71439a62018-02-15 11:53:06 -08002203
Steve Anton80dd7b52018-02-16 17:08:42 -08002204 // Grab the description type before moving ownership to
2205 // ApplyRemoteDescription, which may destroy it before returning.
2206 const SdpType type = desc->GetType();
2207
2208 error = ApplyRemoteDescription(std::move(desc));
2209 // |desc| may be destroyed at this point.
2210
2211 if (!error.ok()) {
2212 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2213 // inconsistent state, so act conservatively here and set the session error
2214 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2215 SetSessionError(SessionError::kContent, error.message());
2216 std::string error_message =
2217 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2218 RTC_LOG(LS_ERROR) << error_message;
2219 observer->OnSetRemoteDescriptionComplete(
2220 RTCError(error.type(), std::move(error_message)));
2221 return;
2222 }
2223 RTC_DCHECK(remote_description());
2224
2225 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002226 // TODO(deadbeef): We already had to hop to the network thread for
2227 // MaybeStartGathering...
2228 network_thread()->Invoke<void>(
2229 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2230 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002231 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002232 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002233 }
2234
2235 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
2236}
2237
2238RTCError PeerConnection::ApplyRemoteDescription(
2239 std::unique_ptr<SessionDescriptionInterface> desc) {
2240 RTC_DCHECK_RUN_ON(signaling_thread());
2241 RTC_DCHECK(desc);
2242
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 // Update stats here so that we have the most recent stats for tracks and
2244 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002245 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002246
Steve Antondcc3c022017-12-22 16:02:54 -08002247 // Take a reference to the old remote description since it's used below to
2248 // compare against the new remote description. When setting the new remote
2249 // description, grab ownership of the replaced session description in case it
2250 // is the same as |old_remote_description|, to keep it alive for the duration
2251 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002252 const SessionDescriptionInterface* old_remote_description =
2253 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002254 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002255 SdpType type = desc->GetType();
2256 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002257 replaced_remote_description = pending_remote_description_
2258 ? std::move(pending_remote_description_)
2259 : std::move(current_remote_description_);
2260 current_remote_description_ = std::move(desc);
2261 pending_remote_description_ = nullptr;
2262 current_local_description_ = std::move(pending_local_description_);
2263 } else {
2264 replaced_remote_description = std::move(pending_remote_description_);
2265 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002266 }
Steve Anton8a006912017-12-04 15:25:56 -08002267 // The session description to apply now must be accessed by
2268 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002269 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002270
Zhi Huange830e682018-03-30 10:48:35 -07002271 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2272 if (!error.ok()) {
2273 return error;
2274 }
Steve Anton8a006912017-12-04 15:25:56 -08002275 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002276 if (IsUnifiedPlan()) {
2277 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002278 cricket::CS_REMOTE, *remote_description(), local_description(),
2279 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002280 if (!error.ok()) {
2281 return error;
2282 }
Steve Antondcc3c022017-12-22 16:02:54 -08002283 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002284 // Media channels will be created only when offer is set. These may use new
2285 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002286 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002287 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002288 // description is applied. Restore back to old description.
2289 RTCError error = CreateChannels(*remote_description()->description());
2290 if (!error.ok()) {
2291 return error;
2292 }
2293 }
Steve Antondcc3c022017-12-22 16:02:54 -08002294 // Remove unused channels if MediaContentDescription is rejected.
2295 RemoveUnusedChannels(remote_description()->description());
2296 }
Steve Anton8a006912017-12-04 15:25:56 -08002297
Zhi Huange830e682018-03-30 10:48:35 -07002298 // NOTE: Candidates allocation will be initiated only when
2299 // SetLocalDescription is called.
2300 error = UpdateSessionState(type, cricket::CS_REMOTE,
2301 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002302 if (!error.ok()) {
2303 return error;
2304 }
2305
2306 if (local_description() &&
2307 !UseCandidatesInSessionDescription(remote_description())) {
2308 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2309 }
2310
2311 if (old_remote_description) {
2312 for (const cricket::ContentInfo& content :
2313 old_remote_description->description()->contents()) {
2314 // Check if this new SessionDescription contains new ICE ufrag and
2315 // password that indicates the remote peer requests an ICE restart.
2316 // TODO(deadbeef): When we start storing both the current and pending
2317 // remote description, this should reset pending_ice_restarts and compare
2318 // against the current description.
2319 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2320 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002321 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002322 pending_ice_restarts_.insert(content.name);
2323 }
2324 } else {
2325 // We retain all received candidates only if ICE is not restarted.
2326 // When ICE is restarted, all previous candidates belong to an old
2327 // generation and should not be kept.
2328 // TODO(deadbeef): This goes against the W3C spec which says the remote
2329 // description should only contain candidates from the last set remote
2330 // description plus any candidates added since then. We should remove
2331 // this once we're sure it won't break anything.
2332 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2333 old_remote_description, content.name, mutable_remote_description());
2334 }
2335 }
2336 }
2337
2338 if (session_error() != SessionError::kNone) {
2339 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2340 }
2341
2342 // Set the the ICE connection state to connecting since the connection may
2343 // become writable with peer reflexive candidates before any remote candidate
2344 // is signaled.
2345 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2346 // is to have a new signal the indicates a change in checking state from the
2347 // transport and expose a new checking() member from transport that can be
2348 // read to determine the current checking state. The existing SignalConnecting
2349 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002350 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002351 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002352 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2353 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2354 }
2355
deadbeefab9b2d12015-10-14 11:33:11 -07002356 // If setting the description decided our SSL role, allocate any necessary
2357 // SCTP sids.
2358 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002359 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002360 AllocateSctpSids(role);
2361 }
2362
Steve Antondcc3c022017-12-22 16:02:54 -08002363 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002364 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002365 now_receiving_transceivers;
2366 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2367 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002368 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002369 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002370 for (auto transceiver : transceivers_) {
2371 const ContentInfo* content =
2372 FindMediaSectionForTransceiver(transceiver, remote_description());
2373 if (!content) {
2374 continue;
2375 }
2376 const MediaContentDescription* media_desc = content->media_description();
2377 RtpTransceiverDirection local_direction =
2378 RtpTransceiverDirectionReversed(media_desc->direction());
2379 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2380 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2381 // transceiver's current direction is neither sendrecv nor recvonly,
2382 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002383 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002384 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002385 // The remote description has signaled the stream IDs.
2386 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002387 }
Steve Antondcc3c022017-12-22 16:02:54 -08002388 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2389 (!transceiver->current_direction() ||
2390 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002391 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002392 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002393 << content->name << " (added to "
2394 << GetStreamIdsString(stream_ids) << ").";
2395
2396 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2397 for (const std::string& stream_id : stream_ids) {
2398 rtc::scoped_refptr<MediaStreamInterface> stream =
2399 remote_streams_->find(stream_id);
2400 if (!stream) {
2401 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2402 MediaStream::Create(stream_id));
2403 remote_streams_->AddStream(stream);
2404 added_streams.push_back(stream);
2405 }
2406 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002407 }
Steve Anton3172c032018-05-03 15:30:18 -07002408 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002409 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002410 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002411 }
2412 // If direction is sendonly or inactive, and transceiver's current
2413 // direction is neither sendonly nor inactive, process the removal of a
2414 // remote track for the media description.
2415 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002416 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002417 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002418 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2419 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002420 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2421 transceiver->internal()->receiver_internal()->streams();
2422 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002423 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002424 no_longer_receiving_transceivers.push_back(transceiver);
2425 // Remove any streams that no longer have tracks.
2426 for (auto stream : media_streams) {
2427 if (stream->GetAudioTracks().empty() &&
2428 stream->GetVideoTracks().empty()) {
2429 remote_streams_->RemoveStream(stream);
2430 removed_streams.push_back(stream);
2431 }
2432 }
Steve Antondcc3c022017-12-22 16:02:54 -08002433 }
2434 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2435 transceiver->internal()->set_current_direction(local_direction);
2436 }
2437 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002438 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2439 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002440 transceiver->Stop();
2441 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002442 if (!content->rejected &&
2443 RtpTransceiverDirectionHasRecv(local_direction)) {
2444 // Set ssrc to 0 in the case of an unsignalled ssrc.
2445 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002446 if (!media_desc->streams().empty() &&
2447 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002448 ssrc = media_desc->streams()[0].first_ssrc();
2449 }
2450 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002451 }
Steve Antondcc3c022017-12-22 16:02:54 -08002452 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002453 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002454 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002455 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002456 observer_->OnTrack(transceiver);
2457 observer_->OnAddTrack(transceiver->receiver(),
2458 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002459 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002460 for (auto stream : added_streams) {
2461 observer_->OnAddStream(stream);
2462 }
Steve Anton3172c032018-05-03 15:30:18 -07002463 for (auto transceiver : no_longer_receiving_transceivers) {
2464 observer_->OnRemoveTrack(transceiver->receiver());
2465 }
2466 for (auto stream : removed_streams) {
2467 observer_->OnRemoveStream(stream);
2468 }
Steve Antondcc3c022017-12-22 16:02:54 -08002469 }
2470
Henrik Boströmfdb92012017-11-09 19:55:44 +01002471 const cricket::ContentInfo* audio_content =
2472 GetFirstAudioContent(remote_description()->description());
2473 const cricket::ContentInfo* video_content =
2474 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002475 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002476 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002477 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002478 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002479 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002480 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002481
2482 // Check if the descriptions include streams, just in case the peer supports
2483 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002484 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002485 (audio_desc && !audio_desc->streams().empty()) ||
2486 (video_desc && !video_desc->streams().empty())) {
2487 remote_peer_supports_msid_ = true;
2488 }
deadbeefab9b2d12015-10-14 11:33:11 -07002489
2490 // We wait to signal new streams until we finish processing the description,
2491 // since only at that point will new streams have all their tracks.
2492 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2493
Steve Antondcc3c022017-12-22 16:02:54 -08002494 if (!IsUnifiedPlan()) {
2495 // TODO(steveanton): When removing RTP senders/receivers in response to a
2496 // rejected media section, there is some cleanup logic that expects the
2497 // voice/ video channel to still be set. But in this method the voice/video
2498 // channel would have been destroyed by the SetRemoteDescription caller
2499 // above so the cleanup that relies on them fails to run. The RemoveSenders
2500 // calls should be moved to right before the DestroyChannel calls to fix
2501 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002502
Steve Antondcc3c022017-12-22 16:02:54 -08002503 // Find all audio rtp streams and create corresponding remote AudioTracks
2504 // and MediaStreams.
2505 if (audio_content) {
2506 if (audio_content->rejected) {
2507 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2508 } else {
2509 bool default_audio_track_needed =
2510 !remote_peer_supports_msid_ &&
2511 RtpTransceiverDirectionHasSend(audio_desc->direction());
2512 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2513 default_audio_track_needed, audio_desc->type(),
2514 new_streams);
2515 }
deadbeeffaac4972015-11-12 15:33:07 -08002516 }
deadbeefab9b2d12015-10-14 11:33:11 -07002517
Steve Antondcc3c022017-12-22 16:02:54 -08002518 // Find all video rtp streams and create corresponding remote VideoTracks
2519 // and MediaStreams.
2520 if (video_content) {
2521 if (video_content->rejected) {
2522 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2523 } else {
2524 bool default_video_track_needed =
2525 !remote_peer_supports_msid_ &&
2526 RtpTransceiverDirectionHasSend(video_desc->direction());
2527 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2528 default_video_track_needed, video_desc->type(),
2529 new_streams);
2530 }
deadbeeffaac4972015-11-12 15:33:07 -08002531 }
deadbeefab9b2d12015-10-14 11:33:11 -07002532
Steve Antondcc3c022017-12-22 16:02:54 -08002533 // Update the DataChannels with the information from the remote peer.
2534 if (data_desc) {
2535 if (rtc::starts_with(data_desc->protocol().data(),
2536 cricket::kMediaProtocolRtpPrefix)) {
2537 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2538 }
deadbeefab9b2d12015-10-14 11:33:11 -07002539 }
deadbeefab9b2d12015-10-14 11:33:11 -07002540
Steve Antondcc3c022017-12-22 16:02:54 -08002541 // Iterate new_streams and notify the observer about new MediaStreams.
2542 for (size_t i = 0; i < new_streams->count(); ++i) {
2543 MediaStreamInterface* new_stream = new_streams->at(i);
2544 stats_->AddStream(new_stream);
2545 observer_->OnAddStream(
2546 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2547 }
deadbeefab9b2d12015-10-14 11:33:11 -07002548
Steve Antondcc3c022017-12-22 16:02:54 -08002549 UpdateEndedRemoteMediaStreams();
2550 }
deadbeefab9b2d12015-10-14 11:33:11 -07002551
Steve Anton8a006912017-12-04 15:25:56 -08002552 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002553}
2554
Steve Antondcc3c022017-12-22 16:02:54 -08002555RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2556 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002557 const SessionDescriptionInterface& new_session,
2558 const SessionDescriptionInterface* old_local_description,
2559 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002560 RTC_DCHECK(IsUnifiedPlan());
2561
Steve Anton7464fca2018-01-19 11:10:37 -08002562 const cricket::ContentGroup* bundle_group = nullptr;
2563 if (new_session.GetType() == SdpType::kOffer) {
2564 auto bundle_group_or_error =
2565 GetEarlyBundleGroup(*new_session.description());
2566 if (!bundle_group_or_error.ok()) {
2567 return bundle_group_or_error.MoveError();
2568 }
2569 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002570 }
Steve Antondcc3c022017-12-22 16:02:54 -08002571
Steve Antondcc3c022017-12-22 16:02:54 -08002572 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002573 for (size_t i = 0; i < new_contents.size(); ++i) {
2574 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002575 cricket::MediaType media_type = new_content.media_description()->type();
2576 seen_mids_.insert(new_content.name);
2577 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2578 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002579 const cricket::ContentInfo* old_local_content = nullptr;
2580 if (old_local_description &&
2581 i < old_local_description->description()->contents().size()) {
2582 old_local_content =
2583 &old_local_description->description()->contents()[i];
2584 }
2585 const cricket::ContentInfo* old_remote_content = nullptr;
2586 if (old_remote_description &&
2587 i < old_remote_description->description()->contents().size()) {
2588 old_remote_content =
2589 &old_remote_description->description()->contents()[i];
2590 }
Steve Antondcc3c022017-12-22 16:02:54 -08002591 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002592 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2593 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002594 if (!transceiver_or_error.ok()) {
2595 return transceiver_or_error.MoveError();
2596 }
2597 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002598 RTCError error =
2599 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2600 if (!error.ok()) {
2601 return error;
2602 }
2603 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002604 if (GetDataMid() && new_content.name != *GetDataMid()) {
2605 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002606 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2607 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002608 continue;
2609 }
2610 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2611 if (!error.ok()) {
2612 return error;
2613 }
Steve Antondcc3c022017-12-22 16:02:54 -08002614 } else {
2615 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2616 "Unknown section type.");
2617 }
2618 }
2619
2620 return RTCError::OK();
2621}
2622
2623RTCError PeerConnection::UpdateTransceiverChannel(
2624 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2625 transceiver,
2626 const cricket::ContentInfo& content,
2627 const cricket::ContentGroup* bundle_group) {
2628 RTC_DCHECK(IsUnifiedPlan());
2629 RTC_DCHECK(transceiver);
2630 cricket::BaseChannel* channel = transceiver->internal()->channel();
2631 if (content.rejected) {
2632 if (channel) {
2633 transceiver->internal()->SetChannel(nullptr);
2634 DestroyBaseChannel(channel);
2635 }
2636 } else {
2637 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002638 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002639 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002640 } else {
Steve Anton69470252018-02-09 11:43:08 -08002641 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002642 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002643 }
2644 if (!channel) {
2645 LOG_AND_RETURN_ERROR(
2646 RTCErrorType::INTERNAL_ERROR,
2647 "Failed to create channel for mid=" + content.name);
2648 }
2649 transceiver->internal()->SetChannel(channel);
2650 }
2651 }
2652 return RTCError::OK();
2653}
2654
Steve Antonfa2260d2017-12-28 16:38:23 -08002655RTCError PeerConnection::UpdateDataChannel(
2656 cricket::ContentSource source,
2657 const cricket::ContentInfo& content,
2658 const cricket::ContentGroup* bundle_group) {
2659 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002660 // If data channels are disabled, ignore this media section. CreateAnswer
2661 // will take care of rejecting it.
2662 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002663 }
2664 if (content.rejected) {
2665 DestroyDataChannel();
2666 } else {
2667 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002668 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002669 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2670 "Failed to create data channel.");
2671 }
2672 }
2673 if (source == cricket::CS_REMOTE) {
2674 const MediaContentDescription* data_desc = content.media_description();
2675 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2676 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2677 }
2678 }
2679 }
2680 return RTCError::OK();
2681}
2682
Steve Antondcc3c022017-12-22 16:02:54 -08002683RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2684PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002685 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002686 size_t mline_index,
2687 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002688 const ContentInfo* old_local_content,
2689 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002690 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002691 // If this is an offer then the m= section might be recycled. If the m=
2692 // section is being recycled (defined as: rejected in the current local or
2693 // remote description and not rejected in new description), dissociate the
2694 // currently associated RtpTransceiver by setting its mid property to null,
2695 // and discard the mapping between the transceiver and its m= section index.
2696 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2697 old_remote_content)) {
2698 // We want to dissociate the transceiver that has the rejected mid.
2699 const std::string& old_mid =
2700 (old_local_content && old_local_content->rejected)
2701 ? old_local_content->name
2702 : old_remote_content->name;
2703 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002704 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002705 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2706 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-22 16:02:54 -08002707 old_transceiver->internal()->set_mid(rtc::nullopt);
2708 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2709 }
2710 }
2711 const MediaContentDescription* media_desc = content.media_description();
2712 auto transceiver = GetAssociatedTransceiver(content.name);
2713 if (source == cricket::CS_LOCAL) {
2714 // Find the RtpTransceiver that corresponds to this m= section, using the
2715 // mapping between transceivers and m= section indices established when
2716 // creating the offer.
2717 if (!transceiver) {
2718 transceiver = GetTransceiverByMLineIndex(mline_index);
2719 }
2720 if (!transceiver) {
2721 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2722 "Unknown transceiver");
2723 }
2724 } else {
2725 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2726 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2727 // of the same type...
2728 if (!transceiver &&
2729 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2730 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2731 }
2732 // If no RtpTransceiver was found in the previous step, create one with a
2733 // recvonly direction.
2734 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002735 RTC_LOG(LS_INFO) << "Adding "
2736 << cricket::MediaTypeToString(media_desc->type())
2737 << " transceiver for MID=" << content.name
2738 << " at i=" << mline_index
2739 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002740 auto sender =
2741 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002742 std::string receiver_id;
2743 if (!media_desc->streams().empty()) {
2744 receiver_id = media_desc->streams()[0].id;
2745 } else {
2746 receiver_id = rtc::CreateRandomUuid();
2747 }
2748 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002749 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002750 transceiver->internal()->set_direction(
2751 RtpTransceiverDirection::kRecvOnly);
2752 }
2753 }
2754 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002755 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002756 LOG_AND_RETURN_ERROR(
2757 RTCErrorType::INVALID_PARAMETER,
2758 "Transceiver type does not match media description type.");
2759 }
2760 // Associate the found or created RtpTransceiver with the m= section by
2761 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2762 // section, and establish a mapping between the transceiver and the index of
2763 // the m= section.
2764 transceiver->internal()->set_mid(content.name);
2765 transceiver->internal()->set_mline_index(mline_index);
2766 return std::move(transceiver);
2767}
2768
2769rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2770PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2771 RTC_DCHECK(IsUnifiedPlan());
2772 for (auto transceiver : transceivers_) {
2773 if (transceiver->mid() == mid) {
2774 return transceiver;
2775 }
2776 }
2777 return nullptr;
2778}
2779
2780rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2781PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2782 RTC_DCHECK(IsUnifiedPlan());
2783 for (auto transceiver : transceivers_) {
2784 if (transceiver->internal()->mline_index() == mline_index) {
2785 return transceiver;
2786 }
2787 }
2788 return nullptr;
2789}
2790
2791rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2792PeerConnection::FindAvailableTransceiverToReceive(
2793 cricket::MediaType media_type) const {
2794 RTC_DCHECK(IsUnifiedPlan());
2795 // From JSEP section 5.10 (Applying a Remote Description):
2796 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2797 // the same type that were added to the PeerConnection by addTrack and are not
2798 // associated with any m= section and are not stopped, find the first such
2799 // RtpTransceiver.
2800 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002801 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002802 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2803 !transceiver->stopped()) {
2804 return transceiver;
2805 }
2806 }
2807 return nullptr;
2808}
2809
Steve Antoned10bd92017-12-05 10:52:59 -08002810const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2811 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2812 transceiver,
2813 const SessionDescriptionInterface* sdesc) const {
2814 RTC_DCHECK(transceiver);
2815 RTC_DCHECK(sdesc);
2816 if (IsUnifiedPlan()) {
2817 if (!transceiver->internal()->mid()) {
2818 // This transceiver is not associated with a media section yet.
2819 return nullptr;
2820 }
2821 return sdesc->description()->GetContentByName(
2822 *transceiver->internal()->mid());
2823 } else {
2824 // Plan B only allows at most one audio and one video section, so use the
2825 // first media section of that type.
2826 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002827 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002828 }
2829}
2830
deadbeef46c73892016-11-16 19:42:04 -08002831PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2832 return configuration_;
2833}
2834
deadbeef293e9262017-01-11 12:28:30 -08002835bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2836 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002837 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002838
Steve Antonc79268f2018-04-24 09:54:10 -07002839 if (IsClosed()) {
2840 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2841 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2842 }
2843
Qingsi Wanga2d60672018-04-11 16:57:45 -07002844 // According to JSEP, after setLocalDescription, changing the candidate pool
2845 // size is not allowed, and changing the set of ICE servers will not result
2846 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002847 if (local_description() && configuration.ice_candidate_pool_size !=
2848 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002849 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2850 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002851 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002852 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002853
deadbeef293e9262017-01-11 12:28:30 -08002854 // The simplest (and most future-compatible) way to tell if the config was
2855 // modified in an invalid way is to copy each property we do support
2856 // modifying, then use operator==. There are far more properties we don't
2857 // support modifying than those we do, and more could be added.
2858 RTCConfiguration modified_config = configuration_;
2859 modified_config.servers = configuration.servers;
2860 modified_config.type = configuration.type;
2861 modified_config.ice_candidate_pool_size =
2862 configuration.ice_candidate_pool_size;
2863 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002864 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002865 modified_config.ice_check_interval_strong_connectivity =
2866 configuration.ice_check_interval_strong_connectivity;
2867 modified_config.ice_check_interval_weak_connectivity =
2868 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002869 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2870 modified_config.ice_unwritable_min_checks =
2871 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002872 modified_config.stun_candidate_keepalive_interval =
2873 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002874 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002875 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002876 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002877 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002878 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2879 }
2880
Steve Anton038834f2017-07-14 15:59:59 -07002881 // Validate the modified configuration.
2882 RTCError validate_error = ValidateConfiguration(modified_config);
2883 if (!validate_error.ok()) {
2884 return SafeSetError(std::move(validate_error), error);
2885 }
2886
deadbeef293e9262017-01-11 12:28:30 -08002887 // Note that this isn't possible through chromium, since it's an unsigned
2888 // short in WebIDL.
2889 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002890 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002891 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2892 }
2893
2894 // Parse ICE servers before hopping to network thread.
2895 cricket::ServerAddresses stun_servers;
2896 std::vector<cricket::RelayServerConfig> turn_servers;
2897 RTCErrorType parse_error =
2898 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2899 if (parse_error != RTCErrorType::NONE) {
2900 return SafeSetError(parse_error, error);
2901 }
2902
2903 // In theory this shouldn't fail.
2904 if (!network_thread()->Invoke<bool>(
2905 RTC_FROM_HERE,
2906 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2907 stun_servers, turn_servers, modified_config.type,
2908 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002909 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002910 modified_config.turn_customizer,
2911 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002912 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002913 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2914 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002915
deadbeefd1a38b52016-12-10 13:15:33 -08002916 // As described in JSEP, calling setConfiguration with new ICE servers or
2917 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2918 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002919 if (modified_config.servers != configuration_.servers ||
2920 modified_config.type != configuration_.type ||
2921 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002922 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002923 }
skvladd1f5fda2017-02-03 16:54:05 -08002924
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002925 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002926
deadbeef293e9262017-01-11 12:28:30 -08002927 configuration_ = modified_config;
2928 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002929}
2930
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002931bool PeerConnection::AddIceCandidate(
2932 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002933 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002934 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002935 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002936 return false;
2937 }
Steve Antond25da372017-11-06 14:50:29 -08002938
2939 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002940 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002941 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002942 return false;
2943 }
2944
2945 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002946 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002947 return false;
2948 }
2949
2950 bool valid = false;
2951 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2952 if (!valid) {
2953 return false;
2954 }
2955
2956 // Add this candidate to the remote session description.
2957 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002958 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002959 return false;
2960 }
2961
2962 if (ready) {
2963 return UseCandidate(ice_candidate);
2964 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002965 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002966 return true;
2967 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002968}
2969
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002970bool PeerConnection::RemoveIceCandidates(
2971 const std::vector<cricket::Candidate>& candidates) {
2972 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002973 if (IsClosed()) {
2974 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2975 return false;
2976 }
2977
Steve Antond25da372017-11-06 14:50:29 -08002978 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002979 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2980 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002981 return false;
2982 }
2983
2984 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002985 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002986 return false;
2987 }
2988
2989 size_t number_removed =
2990 mutable_remote_description()->RemoveCandidates(candidates);
2991 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002992 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07002993 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002994 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01002995 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002996 }
2997
2998 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07002999 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3000 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003001 RTC_LOG(LS_ERROR)
3002 << "RemoveIceCandidates: Error when removing remote candidates: "
3003 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003004 }
3005 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003006}
3007
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003008void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003009 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003010 network_thread()->Invoke<void>(
3011 RTC_FROM_HERE,
3012 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3013 // Send information about IPv4/IPv6 status.
3014 if (uma_observer_) {
3015 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3016 uma_observer_->IncrementEnumCounter(
3017 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3018 kPeerConnectionAddressFamilyCounter_Max);
3019 } else {
3020 uma_observer_->IncrementEnumCounter(
3021 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3022 kPeerConnectionAddressFamilyCounter_Max);
3023 }
3024 }
3025}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003026
Qingsi Wanga2d60672018-04-11 16:57:45 -07003027void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3028 RTC_DCHECK(network_thread()->IsCurrent());
3029 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003030 if (transport_controller_) {
3031 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003032 }
3033
3034 for (auto transceiver : transceivers_) {
3035 auto* channel = transceiver->internal()->channel();
3036 if (channel) {
3037 channel->SetMetricsObserver(uma_observer_);
3038 }
3039 }
3040
deadbeef293e9262017-01-11 12:28:30 -08003041 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003042 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003043 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003044}
3045
Niels Möller0c4f7be2018-05-07 14:01:37 +02003046RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003047 if (!worker_thread()->IsCurrent()) {
3048 return worker_thread()->Invoke<RTCError>(
Niels Möller0c4f7be2018-05-07 14:01:37 +02003049 RTC_FROM_HERE, [&](){ return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003050 }
3051
Niels Möller0c4f7be2018-05-07 14:01:37 +02003052 const bool has_min = bitrate.min_bitrate_bps.has_value();
3053 const bool has_start = bitrate.start_bitrate_bps.has_value();
3054 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003055 if (has_min && *bitrate.min_bitrate_bps < 0) {
3056 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3057 "min_bitrate_bps <= 0");
3058 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003059 if (has_start) {
3060 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003061 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003062 "start_bitrate_bps < min_bitrate_bps");
3063 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003064 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3065 "curent_bitrate_bps < 0");
3066 }
3067 }
3068 if (has_max) {
Niels Möller0c4f7be2018-05-07 14:01:37 +02003069 if (has_start &&
3070 *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003071 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003072 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003073 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3074 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3075 "max_bitrate_bps < min_bitrate_bps");
3076 } else if (*bitrate.max_bitrate_bps < 0) {
3077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3078 "max_bitrate_bps < 0");
3079 }
3080 }
3081
zstein4b979802017-06-02 14:37:37 -07003082 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003083 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003084
3085 return RTCError::OK();
3086}
3087
Alex Narest78609d52017-10-20 10:37:47 +02003088void PeerConnection::SetBitrateAllocationStrategy(
3089 std::unique_ptr<rtc::BitrateAllocationStrategy>
3090 bitrate_allocation_strategy) {
3091 rtc::Thread* worker_thread = factory_->worker_thread();
3092 if (!worker_thread->IsCurrent()) {
3093 rtc::BitrateAllocationStrategy* strategy_raw =
3094 bitrate_allocation_strategy.release();
3095 auto functor = [this, strategy_raw]() {
3096 call_->SetBitrateAllocationStrategy(
3097 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3098 };
3099 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3100 return;
3101 }
3102 RTC_DCHECK(call_.get());
3103 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3104}
3105
henrika5f6bf242017-11-01 11:06:56 +01003106void PeerConnection::SetAudioPlayout(bool playout) {
3107 if (!worker_thread()->IsCurrent()) {
3108 worker_thread()->Invoke<void>(
3109 RTC_FROM_HERE,
3110 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3111 return;
3112 }
3113 auto audio_state =
3114 factory_->channel_manager()->media_engine()->GetAudioState();
3115 audio_state->SetPlayout(playout);
3116}
3117
3118void PeerConnection::SetAudioRecording(bool recording) {
3119 if (!worker_thread()->IsCurrent()) {
3120 worker_thread()->Invoke<void>(
3121 RTC_FROM_HERE,
3122 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3123 return;
3124 }
3125 auto audio_state =
3126 factory_->channel_manager()->media_engine()->GetAudioState();
3127 audio_state->SetRecording(recording);
3128}
3129
Steve Anton8c0f7a72017-10-03 10:03:10 -07003130std::unique_ptr<rtc::SSLCertificate>
3131PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003132 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3133 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003134 return nullptr;
3135 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003136 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003137}
3138
Zhi Huang70b820f2018-01-27 14:16:15 -08003139std::unique_ptr<rtc::SSLCertChain>
3140PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003141 auto audio_transceiver = GetFirstAudioTransceiver();
3142 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003143 return nullptr;
3144 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003145 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003146 audio_transceiver->internal()->channel()->transport_name());
3147}
3148
3149rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3150PeerConnection::GetFirstAudioTransceiver() const {
3151 for (auto transceiver : transceivers_) {
3152 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3153 return transceiver;
3154 }
3155 }
3156 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003157}
3158
ivoc14d5dbe2016-07-04 07:06:55 -07003159bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3160 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003161 // TODO(eladalon): It would be better to not allow negative values into PC.
3162 const size_t max_size = (max_size_bytes < 0)
3163 ? RtcEventLog::kUnlimitedOutput
3164 : rtc::saturated_cast<size_t>(max_size_bytes);
3165 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003166 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3167 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003168}
3169
Bjorn Tereliusde939432017-11-20 17:38:14 +01003170bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3171 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003172 // TODO(eladalon): In C++14, this can be done with a lambda.
3173 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003174 bool operator()() {
3175 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3176 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003177 PeerConnection* const pc;
3178 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003179 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003180 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003181 return worker_thread()->Invoke<bool>(
3182 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003183}
3184
3185void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003186 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003187 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3188}
3189
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003190const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003191 return pending_local_description_ ? pending_local_description_.get()
3192 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003193}
3194
3195const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003196 return pending_remote_description_ ? pending_remote_description_.get()
3197 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198}
3199
deadbeeffe4a8a42016-12-20 17:56:17 -08003200const SessionDescriptionInterface* PeerConnection::current_local_description()
3201 const {
Steve Anton75737c02017-11-06 10:37:17 -08003202 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003203}
3204
3205const SessionDescriptionInterface* PeerConnection::current_remote_description()
3206 const {
Steve Anton75737c02017-11-06 10:37:17 -08003207 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003208}
3209
3210const SessionDescriptionInterface* PeerConnection::pending_local_description()
3211 const {
Steve Anton75737c02017-11-06 10:37:17 -08003212 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003213}
3214
3215const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3216 const {
Steve Anton75737c02017-11-06 10:37:17 -08003217 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003218}
3219
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003220void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003221 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003222 // Update stats here so that we have the most recent stats for tracks and
3223 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003224 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225
Steve Anton75737c02017-11-06 10:37:17 -08003226 ChangeSignalingState(PeerConnectionInterface::kClosed);
Steve Anton3fe1b152017-12-12 10:20:08 -08003227
Steve Anton8af21862017-12-15 11:20:13 -08003228 for (auto transceiver : transceivers_) {
3229 transceiver->Stop();
3230 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003231
3232 // Ensure that all asynchronous stats requests are completed before destroying
3233 // the transport controller below.
3234 if (stats_collector_) {
3235 stats_collector_->WaitForPendingRequest();
3236 }
3237
3238 // Don't destroy BaseChannels until after stats has been cleaned up so that
3239 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003240 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003241
Qingsi Wang93a84392018-01-30 17:13:09 -08003242 // The event log is used in the transport controller, which must be outlived
3243 // by the former. CreateOffer by the peer connection is implemented
3244 // asynchronously and if the peer connection is closed without resetting the
3245 // WebRTC session description factory, the session description factory would
3246 // call the transport controller.
3247 webrtc_session_desc_factory_.reset();
3248 transport_controller_.reset();
3249
deadbeef42a42632017-03-10 15:18:00 -08003250 network_thread()->Invoke<void>(
3251 RTC_FROM_HERE,
3252 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3253 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003254
Steve Anton978b8762017-09-29 12:15:02 -07003255 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003256 call_.reset();
3257 // The event log must outlive call (and any other object that uses it).
3258 event_log_.reset();
3259 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003260}
3261
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003262void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003264 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3265 SetSessionDescriptionMsg* param =
3266 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3267 param->observer->OnSuccess();
3268 delete param;
3269 break;
3270 }
3271 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3272 SetSessionDescriptionMsg* param =
3273 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003274 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 delete param;
3276 break;
3277 }
deadbeefab9b2d12015-10-14 11:33:11 -07003278 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3279 CreateSessionDescriptionMsg* param =
3280 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003281 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003282 delete param;
3283 break;
3284 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003285 case MSG_GETSTATS: {
3286 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003287 StatsReports reports;
3288 stats_->GetStats(param->track, &reports);
3289 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003290 delete param;
3291 break;
3292 }
deadbeefbd292462015-12-14 18:15:29 -08003293 case MSG_FREE_DATACHANNELS: {
3294 sctp_data_channels_to_free_.clear();
3295 break;
3296 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003297 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003298 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003299 break;
3300 }
3301}
3302
Steve Antonafb0bb72018-02-20 11:35:37 -08003303cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3304 RTC_DCHECK(!IsUnifiedPlan());
3305 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3306 GetAudioTransceiver()->internal()->channel());
3307 if (voice_channel) {
3308 return voice_channel->media_channel();
3309 } else {
3310 return nullptr;
3311 }
3312}
3313
3314cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3315 RTC_DCHECK(!IsUnifiedPlan());
3316 auto* video_channel = static_cast<cricket::VideoChannel*>(
3317 GetVideoTransceiver()->internal()->channel());
3318 if (video_channel) {
3319 return video_channel->media_channel();
3320 } else {
3321 return nullptr;
3322 }
3323}
3324
Steve Anton4171afb2017-11-20 10:20:22 -08003325void PeerConnection::CreateAudioReceiver(
3326 MediaStreamInterface* stream,
3327 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003328 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3329 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003330 auto* audio_receiver = new AudioRtpReceiver(
3331 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003332 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003333 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3334 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3335 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003336 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003337 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003338}
3339
Steve Anton4171afb2017-11-20 10:20:22 -08003340void PeerConnection::CreateVideoReceiver(
3341 MediaStreamInterface* stream,
3342 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003343 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3344 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003345 auto* video_receiver = new VideoRtpReceiver(
3346 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003347 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003348 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3349 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3350 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003351 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003352 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003353}
3354
deadbeef70ab1a12015-09-28 16:53:55 -07003355// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3356// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003357rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003358 const RtpSenderInfo& remote_sender_info) {
3359 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3360 if (!receiver) {
3361 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3362 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003363 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003364 }
Steve Anton4171afb2017-11-20 10:20:22 -08003365 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3366 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3367 } else {
3368 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3369 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003370 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371}
3372
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003373void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3374 MediaStreamInterface* stream) {
3375 RTC_DCHECK(!IsClosed());
3376 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003377 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003378 // We already have a sender for this track, so just change the stream_id
3379 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003380 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003381 return;
3382 }
3383
3384 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003385 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003386 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003387 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003388 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003389 // If the sender has already been configured in SDP, we call SetSsrc,
3390 // which will connect the sender to the underlying transport. This can
3391 // occur if a local session description that contains the ID of the sender
3392 // is set before AddStream is called. It can also occur if the local
3393 // session description is not changed and RemoveStream is called, and
3394 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003395 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003396 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003397 if (sender_info) {
3398 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003399 }
3400}
3401
3402// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3403// indefinitely, when we have unified plan SDP.
3404void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3405 MediaStreamInterface* stream) {
3406 RTC_DCHECK(!IsClosed());
3407 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003408 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003409 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3410 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003411 return;
3412 }
Steve Anton4171afb2017-11-20 10:20:22 -08003413 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003414}
3415
3416void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3417 MediaStreamInterface* stream) {
3418 RTC_DCHECK(!IsClosed());
3419 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003420 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003421 // We already have a sender for this track, so just change the stream_id
3422 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003423 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003424 return;
3425 }
3426
3427 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003428 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003429 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003430 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003431 GetVideoTransceiver()->internal()->AddSender(new_sender);
3432 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003433 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003434 if (sender_info) {
3435 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003436 }
3437}
3438
3439void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3440 MediaStreamInterface* stream) {
3441 RTC_DCHECK(!IsClosed());
3442 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003443 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003444 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3445 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003446 return;
3447 }
Steve Anton4171afb2017-11-20 10:20:22 -08003448 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003449}
3450
Steve Antonba818672017-11-06 10:21:57 -08003451void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003452 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003453 if (ice_connection_state_ == new_state) {
3454 return;
3455 }
3456
deadbeefcbecd352015-09-23 11:50:27 -07003457 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003458 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003459 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003460 return;
3461 }
Steve Antonba818672017-11-06 10:21:57 -08003462
Mirko Bonadei675513b2017-11-09 11:09:25 +01003463 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3464 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003465 RTC_DCHECK(ice_connection_state_ !=
3466 PeerConnectionInterface::kIceConnectionClosed);
3467
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003468 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003469 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003470}
3471
3472void PeerConnection::OnIceGatheringChange(
3473 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003474 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003475 if (IsClosed()) {
3476 return;
3477 }
3478 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003479 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003480}
3481
jbauch81bf7b02017-03-25 08:31:12 -07003482void PeerConnection::OnIceCandidate(
3483 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003484 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003485 if (IsClosed()) {
3486 return;
3487 }
jbauch81bf7b02017-03-25 08:31:12 -07003488 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003489}
3490
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003491void PeerConnection::OnIceCandidatesRemoved(
3492 const std::vector<cricket::Candidate>& candidates) {
3493 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003494 if (IsClosed()) {
3495 return;
3496 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003497 observer_->OnIceCandidatesRemoved(candidates);
3498}
3499
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003500void PeerConnection::ChangeSignalingState(
3501 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003502 RTC_DCHECK(signaling_thread()->IsCurrent());
3503 if (signaling_state_ == signaling_state) {
3504 return;
3505 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003506 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3507 << GetSignalingStateString(signaling_state_)
3508 << " New state: "
3509 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003510 signaling_state_ = signaling_state;
3511 if (signaling_state == kClosed) {
3512 ice_connection_state_ = kIceConnectionClosed;
3513 observer_->OnIceConnectionChange(ice_connection_state_);
3514 if (ice_gathering_state_ != kIceGatheringComplete) {
3515 ice_gathering_state_ = kIceGatheringComplete;
3516 observer_->OnIceGatheringChange(ice_gathering_state_);
3517 }
3518 }
3519 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520}
3521
deadbeefeb459812015-12-15 19:24:43 -08003522void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3523 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003524 if (IsClosed()) {
3525 return;
3526 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003527 AddAudioTrack(track, stream);
3528 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003529}
3530
deadbeefeb459812015-12-15 19:24:43 -08003531void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3532 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003533 if (IsClosed()) {
3534 return;
3535 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003536 RemoveAudioTrack(track, stream);
3537 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003538}
3539
3540void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3541 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003542 if (IsClosed()) {
3543 return;
3544 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003545 AddVideoTrack(track, stream);
3546 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003547}
3548
3549void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3550 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003551 if (IsClosed()) {
3552 return;
3553 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003554 RemoveVideoTrack(track, stream);
3555 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003556}
3557
Henrik Boström31638672017-11-23 17:48:32 +01003558void PeerConnection::PostSetSessionDescriptionSuccess(
3559 SetSessionDescriptionObserver* observer) {
3560 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3561 signaling_thread()->Post(RTC_FROM_HERE, this,
3562 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3563}
3564
deadbeefab9b2d12015-10-14 11:33:11 -07003565void PeerConnection::PostSetSessionDescriptionFailure(
3566 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003567 RTCError&& error) {
3568 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003569 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003570 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003571 signaling_thread()->Post(RTC_FROM_HERE, this,
3572 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003573}
3574
3575void PeerConnection::PostCreateSessionDescriptionFailure(
3576 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003577 RTCError error) {
3578 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003579 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003580 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003581 signaling_thread()->Post(RTC_FROM_HERE, this,
3582 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003583}
3584
zhihuang1c378ed2017-08-17 14:10:50 -07003585void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003586 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003587 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003588 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003589
Steve Antondcc3c022017-12-22 16:02:54 -08003590 if (IsUnifiedPlan()) {
3591 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3592 } else {
3593 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3594 }
3595
Steve Antonfa2260d2017-12-28 16:38:23 -08003596 // Intentionally unset the data channel type for RTP data channel with the
3597 // second condition. Otherwise the RTP data channels would be successfully
3598 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3599 // when building with chromium. We want to leave RTP data channels broken, so
3600 // people won't try to use them.
3601 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3602 session_options->data_channel_type = data_channel_type();
3603 }
3604
Steve Antondcc3c022017-12-22 16:02:54 -08003605 // Apply ICE restart flag and renomination flag.
3606 for (auto& options : session_options->media_description_options) {
3607 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3608 options.transport_options.enable_ice_renomination =
3609 configuration_.enable_ice_renomination;
3610 }
3611
3612 session_options->rtcp_cname = rtcp_cname_;
3613 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003614 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003615}
3616
3617void PeerConnection::GetOptionsForPlanBOffer(
3618 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3619 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003620 // Figure out transceiver directional preferences.
3621 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3622 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3623
3624 // By default, generate sendrecv/recvonly m= sections.
3625 bool recv_audio = true;
3626 bool recv_video = true;
3627
3628 // By default, only offer a new m= section if we have media to send with it.
3629 bool offer_new_audio_description = send_audio;
3630 bool offer_new_video_description = send_video;
3631 bool offer_new_data_description = HasDataChannels();
3632
3633 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003634 if (offer_answer_options.offer_to_receive_audio !=
3635 RTCOfferAnswerOptions::kUndefined) {
3636 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003637 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003638 offer_new_audio_description ||
3639 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003640 }
Steve Antondcc3c022017-12-22 16:02:54 -08003641 if (offer_answer_options.offer_to_receive_video !=
3642 RTCOfferAnswerOptions::kUndefined) {
3643 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003644 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003645 offer_new_video_description ||
3646 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003647 }
3648
3649 rtc::Optional<size_t> audio_index;
3650 rtc::Optional<size_t> video_index;
3651 rtc::Optional<size_t> data_index;
3652 // If a current description exists, generate m= sections in the same order,
3653 // using the first audio/video/data section that appears and rejecting
3654 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003655 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003656 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003657 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003658 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3659 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3660 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003661 }
3662
zhihuang1c378ed2017-08-17 14:10:50 -07003663 // Add audio/video/data m= sections to the end if needed.
3664 if (!audio_index && offer_new_audio_description) {
3665 session_options->media_description_options.push_back(
3666 cricket::MediaDescriptionOptions(
3667 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003668 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3669 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003670 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003671 }
zhihuang1c378ed2017-08-17 14:10:50 -07003672 if (!video_index && offer_new_video_description) {
3673 session_options->media_description_options.push_back(
3674 cricket::MediaDescriptionOptions(
3675 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003676 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3677 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003678 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003679 }
zhihuang1c378ed2017-08-17 14:10:50 -07003680 if (!data_index && offer_new_data_description) {
3681 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003682 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003683 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003684 }
3685
3686 cricket::MediaDescriptionOptions* audio_media_description_options =
3687 !audio_index ? nullptr
3688 : &session_options->media_description_options[*audio_index];
3689 cricket::MediaDescriptionOptions* video_media_description_options =
3690 !video_index ? nullptr
3691 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003692
Steve Anton4171afb2017-11-20 10:20:22 -08003693 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003694 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003695}
3696
3697// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3698// and return a reference to it.
3699// Generated MIDs should be no more than 3 bytes long to take up less space in
3700// the RTP packet.
3701static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3702 RTC_DCHECK(used_mids);
3703 // We're boring: just generate MIDs 0, 1, 2, ...
3704 size_t i = 0;
3705 std::set<std::string>::iterator it;
3706 bool inserted;
3707 do {
3708 std::string mid = rtc::ToString(i++);
3709 auto insert_result = used_mids->insert(mid);
3710 it = insert_result.first;
3711 inserted = insert_result.second;
3712 } while (!inserted);
3713 return *it;
3714}
3715
3716static cricket::MediaDescriptionOptions
3717GetMediaDescriptionOptionsForTransceiver(
3718 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3719 transceiver,
3720 const std::string& mid) {
3721 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003722 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003723 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003724 // This behavior is specified in JSEP. The gist is that:
3725 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3726 // sendrecv.
3727 // 2. If the MSID is included, then it must be included in any subsequent
3728 // offer/answer exactly the same until the RtpTransceiver is stopped.
3729 if (!transceiver->stopped() &&
3730 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3731 transceiver->internal()->has_ever_been_used_to_send())) {
3732 cricket::SenderOptions sender_options;
3733 sender_options.track_id = transceiver->sender()->id();
3734 sender_options.stream_ids = transceiver->sender()->stream_ids();
3735 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3736 // set in the RTP parameters when the transceiver was added.
3737 sender_options.num_sim_layers = 1;
3738 media_description_options.sender_options.push_back(sender_options);
3739 }
Steve Antondcc3c022017-12-22 16:02:54 -08003740 return media_description_options;
3741}
3742
3743void PeerConnection::GetOptionsForUnifiedPlanOffer(
3744 const RTCOfferAnswerOptions& offer_answer_options,
3745 cricket::MediaSessionOptions* session_options) {
3746 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3747 // Offers) and 5.2.2 (Subsequent Offers).
3748 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3749 const ContentInfos& local_contents =
3750 (local_description() ? local_description()->description()->contents()
3751 : ContentInfos());
3752 const ContentInfos& remote_contents =
3753 (remote_description() ? remote_description()->description()->contents()
3754 : ContentInfos());
3755 // The mline indices that can be recycled. New transceivers should reuse these
3756 // slots first.
3757 std::queue<size_t> recycleable_mline_indices;
3758 // Track the MIDs used in previous offer/answer exchanges and the current
3759 // offer so that new, unique MIDs are generated.
3760 std::set<std::string> used_mids = seen_mids_;
3761 // First, go through each media section that exists in either the local or
3762 // remote description and generate a media section in this offer for the
3763 // associated transceiver. If a media section can be recycled, generate a
3764 // default, rejected media section here that can be later overwritten.
3765 for (size_t i = 0;
3766 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3767 // Either |local_content| or |remote_content| is non-null.
3768 const ContentInfo* local_content =
3769 (i < local_contents.size() ? &local_contents[i] : nullptr);
3770 const ContentInfo* remote_content =
3771 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3772 bool had_been_rejected = (local_content && local_content->rejected) ||
3773 (remote_content && remote_content->rejected);
3774 const std::string& mid =
3775 (local_content ? local_content->name : remote_content->name);
3776 cricket::MediaType media_type =
3777 (local_content ? local_content->media_description()->type()
3778 : remote_content->media_description()->type());
3779 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3780 media_type == cricket::MEDIA_TYPE_VIDEO) {
3781 auto transceiver = GetAssociatedTransceiver(mid);
3782 RTC_CHECK(transceiver);
3783 // A media section is considered eligible for recycling if it is marked as
3784 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003785 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003786 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003787 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3788 RtpTransceiverDirection::kInactive,
3789 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003790 recycleable_mline_indices.push(i);
3791 } else {
3792 session_options->media_description_options.push_back(
3793 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3794 // CreateOffer shouldn't really cause any state changes in
3795 // PeerConnection, but we need a way to match new transceivers to new
3796 // media sections in SetLocalDescription and JSEP specifies this is done
3797 // by recording the index of the media section generated for the
3798 // transceiver in the offer.
3799 transceiver->internal()->set_mline_index(i);
3800 }
3801 } else {
3802 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003803 RTC_CHECK(GetDataMid());
3804 if (had_been_rejected || mid != *GetDataMid()) {
3805 session_options->media_description_options.push_back(
3806 GetMediaDescriptionOptionsForRejectedData(mid));
3807 } else {
3808 session_options->media_description_options.push_back(
3809 GetMediaDescriptionOptionsForActiveData(mid));
3810 }
Steve Antondcc3c022017-12-22 16:02:54 -08003811 }
3812 }
3813 // Next, look for transceivers that are newly added (that is, are not stopped
3814 // and not associated). Reuse media sections marked as recyclable first,
3815 // otherwise append to the end of the offer. New media sections should be
3816 // added in the order they were added to the PeerConnection.
3817 for (auto transceiver : transceivers_) {
3818 if (transceiver->mid() || transceiver->stopped()) {
3819 continue;
3820 }
3821 size_t mline_index;
3822 if (!recycleable_mline_indices.empty()) {
3823 mline_index = recycleable_mline_indices.front();
3824 recycleable_mline_indices.pop();
3825 session_options->media_description_options[mline_index] =
3826 GetMediaDescriptionOptionsForTransceiver(transceiver,
3827 AllocateMid(&used_mids));
3828 } else {
3829 mline_index = session_options->media_description_options.size();
3830 session_options->media_description_options.push_back(
3831 GetMediaDescriptionOptionsForTransceiver(transceiver,
3832 AllocateMid(&used_mids)));
3833 }
3834 // See comment above for why CreateOffer changes the transceiver's state.
3835 transceiver->internal()->set_mline_index(mline_index);
3836 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003837 // Lastly, add a m-section if we have local data channels and an m section
3838 // does not already exist.
3839 if (!GetDataMid() && HasDataChannels()) {
3840 session_options->media_description_options.push_back(
3841 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3842 }
Steve Antondcc3c022017-12-22 16:02:54 -08003843}
3844
3845void PeerConnection::GetOptionsForAnswer(
3846 const RTCOfferAnswerOptions& offer_answer_options,
3847 cricket::MediaSessionOptions* session_options) {
3848 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3849
3850 if (IsUnifiedPlan()) {
3851 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3852 } else {
3853 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3854 }
3855
Steve Antonfa2260d2017-12-28 16:38:23 -08003856 // Intentionally unset the data channel type for RTP data channel. Otherwise
3857 // the RTP data channels would be successfully negotiated by default and the
3858 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3859 // We want to leave RTP data channels broken, so people won't try to use them.
3860 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3861 session_options->data_channel_type = data_channel_type();
3862 }
3863
Steve Antondcc3c022017-12-22 16:02:54 -08003864 // Apply ICE renomination flag.
3865 for (auto& options : session_options->media_description_options) {
3866 options.transport_options.enable_ice_renomination =
3867 configuration_.enable_ice_renomination;
3868 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003869
3870 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003871 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003872 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003873}
3874
Steve Antondcc3c022017-12-22 16:02:54 -08003875void PeerConnection::GetOptionsForPlanBAnswer(
3876 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003877 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003878 // Figure out transceiver directional preferences.
3879 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3880 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3881
3882 // By default, generate sendrecv/recvonly m= sections. The direction is also
3883 // restricted by the direction in the offer.
3884 bool recv_audio = true;
3885 bool recv_video = true;
3886
3887 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003888 if (offer_answer_options.offer_to_receive_audio !=
3889 RTCOfferAnswerOptions::kUndefined) {
3890 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003891 }
Steve Antondcc3c022017-12-22 16:02:54 -08003892 if (offer_answer_options.offer_to_receive_video !=
3893 RTCOfferAnswerOptions::kUndefined) {
3894 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003895 }
3896
3897 rtc::Optional<size_t> audio_index;
3898 rtc::Optional<size_t> video_index;
3899 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003900
3901 // Generate m= sections that match those in the offer.
3902 // Note that mediasession.cc will handle intersection our preferred
3903 // direction with the offered direction.
3904 GenerateMediaDescriptionOptions(
3905 remote_description(),
3906 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3907 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3908 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003909
3910 cricket::MediaDescriptionOptions* audio_media_description_options =
3911 !audio_index ? nullptr
3912 : &session_options->media_description_options[*audio_index];
3913 cricket::MediaDescriptionOptions* video_media_description_options =
3914 !video_index ? nullptr
3915 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003916
Steve Anton4171afb2017-11-20 10:20:22 -08003917 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003918 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003919}
zhihuangaf388472016-11-02 16:49:48 -07003920
Steve Antondcc3c022017-12-22 16:02:54 -08003921void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3922 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3923 cricket::MediaSessionOptions* session_options) {
3924 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3925 // Answers) and 5.3.2 (Subsequent Answers).
3926 RTC_DCHECK(remote_description());
3927 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3928 for (const ContentInfo& content :
3929 remote_description()->description()->contents()) {
3930 cricket::MediaType media_type = content.media_description()->type();
3931 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3932 media_type == cricket::MEDIA_TYPE_VIDEO) {
3933 auto transceiver = GetAssociatedTransceiver(content.name);
3934 RTC_CHECK(transceiver);
3935 session_options->media_description_options.push_back(
3936 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3937 } else {
3938 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003939 // Reject all data sections if data channels are disabled.
3940 // Reject a data section if it has already been rejected.
3941 // Reject all data sections except for the first one.
3942 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3943 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003944 session_options->media_description_options.push_back(
3945 GetMediaDescriptionOptionsForRejectedData(content.name));
3946 } else {
3947 session_options->media_description_options.push_back(
3948 GetMediaDescriptionOptionsForActiveData(content.name));
3949 }
Steve Antondcc3c022017-12-22 16:02:54 -08003950 }
3951 }
htaa2a49d92016-03-04 02:51:39 -08003952}
3953
zhihuang1c378ed2017-08-17 14:10:50 -07003954void PeerConnection::GenerateMediaDescriptionOptions(
3955 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003956 RtpTransceiverDirection audio_direction,
3957 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003958 rtc::Optional<size_t>* audio_index,
3959 rtc::Optional<size_t>* video_index,
3960 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003961 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003962 for (const cricket::ContentInfo& content :
3963 session_desc->description()->contents()) {
3964 if (IsAudioContent(&content)) {
3965 // If we already have an audio m= section, reject this extra one.
3966 if (*audio_index) {
3967 session_options->media_description_options.push_back(
3968 cricket::MediaDescriptionOptions(
3969 cricket::MEDIA_TYPE_AUDIO, 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_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003975 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003976 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003977 }
3978 } else if (IsVideoContent(&content)) {
3979 // If we already have an video m= section, reject this extra one.
3980 if (*video_index) {
3981 session_options->media_description_options.push_back(
3982 cricket::MediaDescriptionOptions(
3983 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003984 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003985 } else {
3986 session_options->media_description_options.push_back(
3987 cricket::MediaDescriptionOptions(
3988 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003989 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003990 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003991 }
3992 } else {
3993 RTC_DCHECK(IsDataContent(&content));
3994 // If we already have an data m= section, reject this extra one.
3995 if (*data_index) {
3996 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003997 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07003998 } else {
3999 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004000 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004001 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004002 }
4003 }
htaa2a49d92016-03-04 02:51:39 -08004004 }
deadbeefab9b2d12015-10-14 11:33:11 -07004005}
4006
Steve Antonfa2260d2017-12-28 16:38:23 -08004007cricket::MediaDescriptionOptions
4008PeerConnection::GetMediaDescriptionOptionsForActiveData(
4009 const std::string& mid) const {
4010 // Direction for data sections is meaningless, but legacy endpoints might
4011 // expect sendrecv.
4012 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4013 RtpTransceiverDirection::kSendRecv,
4014 /*stopped=*/false);
4015 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4016 return options;
4017}
4018
4019cricket::MediaDescriptionOptions
4020PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4021 const std::string& mid) const {
4022 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4023 RtpTransceiverDirection::kInactive,
4024 /*stopped=*/true);
4025 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4026 return options;
4027}
4028
4029rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4030 switch (data_channel_type_) {
4031 case cricket::DCT_RTP:
4032 if (!rtp_data_channel_) {
4033 return rtc::nullopt;
4034 }
4035 return rtp_data_channel_->content_name();
4036 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004037 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004038 default:
4039 return rtc::nullopt;
4040 }
4041}
4042
Steve Anton4171afb2017-11-20 10:20:22 -08004043void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4044 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4045 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004046 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004047}
4048
Steve Anton4171afb2017-11-20 10:20:22 -08004049void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004050 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004051 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004052 cricket::MediaType media_type,
4053 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004054 RTC_DCHECK(!IsUnifiedPlan());
4055
Steve Anton4171afb2017-11-20 10:20:22 -08004056 std::vector<RtpSenderInfo>* current_senders =
4057 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004058
Steve Anton4171afb2017-11-20 10:20:22 -08004059 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004060 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004061 for (auto sender_it = current_senders->begin();
4062 sender_it != current_senders->end();
4063 /* incremented manually */) {
4064 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004065 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004066 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004067 std::string params_stream_id;
4068 if (params) {
4069 params_stream_id =
4070 (!params->first_stream_id().empty() ? params->first_stream_id()
4071 : kDefaultStreamId);
4072 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004073 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004074 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004075 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004076 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004077 sender_exists) {
4078 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004079 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004080 OnRemoteSenderRemoved(info, media_type);
4081 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004082 }
4083 }
4084
Steve Anton4171afb2017-11-20 10:20:22 -08004085 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004086 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004087 if (!params.has_ssrcs()) {
4088 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4089 // sender, this means it is coming from a Unified Plan endpoint,so we just
4090 // create a default.
4091 default_sender_needed = true;
4092 break;
4093 }
4094
Seth Hampson845e8782018-03-02 11:34:10 -08004095 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004096 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004097 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4098 // not supported in Plan B, we just take the first here and create the
4099 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004100 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004101 (!params.first_stream_id().empty() ? params.first_stream_id()
4102 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004103 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004104 uint32_t ssrc = params.first_ssrc();
4105
4106 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004107 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004108 if (!stream) {
4109 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004110 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004111 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004112 remote_streams_->AddStream(stream);
4113 new_streams->AddStream(stream);
4114 }
4115
Steve Anton4171afb2017-11-20 10:20:22 -08004116 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004117 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004118 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004119 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004120 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004121 }
4122 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004123
Steve Anton4171afb2017-11-20 10:20:22 -08004124 // Add default sender if necessary.
4125 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004126 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004127 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004128 if (!default_stream) {
4129 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004130 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004131 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004132 remote_streams_->AddStream(default_stream);
4133 new_streams->AddStream(default_stream);
4134 }
Steve Anton4171afb2017-11-20 10:20:22 -08004135 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4136 ? kDefaultAudioSenderId
4137 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004138 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004139 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004140 if (!default_sender_info) {
4141 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004142 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004143 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004144 }
4145 }
deadbeefab9b2d12015-10-14 11:33:11 -07004146}
4147
Steve Anton4171afb2017-11-20 10:20:22 -08004148void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4149 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004150 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4151 << " receiver for track_id=" << sender_info.sender_id
4152 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004153
Steve Anton3d954a62018-04-02 11:27:23 -07004154 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004155 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004156 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004157 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004158 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004159 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004160 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004161 }
4162}
4163
Steve Anton4171afb2017-11-20 10:20:22 -08004164void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4165 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004166 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4167 << " receiver for track_id=" << sender_info.sender_id
4168 << " and stream_id=" << sender_info.stream_id;
4169
Seth Hampson845e8782018-03-02 11:34:10 -08004170 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004171
Henrik Boström933d8b02017-10-10 10:05:16 -07004172 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004173 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004174 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4175 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004176 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004177 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004178 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004179 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004180 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004181 }
4182 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004183 // Stopping or destroying a VideoRtpReceiver will end the
4184 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004185 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004186 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004187 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004188 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004189 // There's no guarantee the track is still available, e.g. the track may
4190 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004191 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004192 }
4193 } else {
nisseede5da42017-01-12 05:15:36 -08004194 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004195 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004196 if (receiver) {
4197 observer_->OnRemoveTrack(receiver);
4198 }
deadbeefab9b2d12015-10-14 11:33:11 -07004199}
4200
4201void PeerConnection::UpdateEndedRemoteMediaStreams() {
4202 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4203 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4204 MediaStreamInterface* stream = remote_streams_->at(i);
4205 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4206 streams_to_remove.push_back(stream);
4207 }
4208 }
4209
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004210 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004211 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004212 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004213 }
4214}
4215
Steve Anton4171afb2017-11-20 10:20:22 -08004216void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004217 const std::vector<cricket::StreamParams>& streams,
4218 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004219 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004220
Seth Hampson845e8782018-03-02 11:34:10 -08004221 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004222 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004223 for (auto sender_it = current_senders->begin();
4224 sender_it != current_senders->end();
4225 /* incremented manually */) {
4226 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004227 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004228 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4229 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004230 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004231 OnLocalSenderRemoved(info, media_type);
4232 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004233 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004234 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004235 }
4236 }
4237
Steve Anton4171afb2017-11-20 10:20:22 -08004238 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004239 for (const cricket::StreamParams& params : streams) {
4240 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004241 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004242 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004243 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004244 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004245 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004246 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004247 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004248 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004249 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004250 }
4251 }
4252}
4253
Steve Anton4171afb2017-11-20 10:20:22 -08004254void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4255 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004256 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004257 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004258 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004259 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4260 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004261 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004262 return;
4263 }
4264
deadbeeffac06552015-11-25 11:26:01 -08004265 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004266 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004267 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004268 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004269 }
deadbeeffac06552015-11-25 11:26:01 -08004270
Seth Hampson5b4f0752018-04-02 16:31:36 -07004271 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004272 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004273}
4274
Steve Anton4171afb2017-11-20 10:20:22 -08004275void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4276 cricket::MediaType media_type) {
4277 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004278 if (!sender) {
4279 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004280 // SessionDescriptions has been renegotiated.
4281 return;
4282 }
deadbeeffac06552015-11-25 11:26:01 -08004283
4284 // A sender has been removed from the SessionDescription but it's still
4285 // associated with the PeerConnection. This only occurs if the SDP doesn't
4286 // match with the calls to CreateSender, AddStream and RemoveStream.
4287 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004288 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004289 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004290 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004291 }
deadbeeffac06552015-11-25 11:26:01 -08004292
Steve Anton4171afb2017-11-20 10:20:22 -08004293 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004294}
4295
4296void PeerConnection::UpdateLocalRtpDataChannels(
4297 const cricket::StreamParamsVec& streams) {
4298 std::vector<std::string> existing_channels;
4299
4300 // Find new and active data channels.
4301 for (const cricket::StreamParams& params : streams) {
4302 // |it->sync_label| is actually the data channel label. The reason is that
4303 // we use the same naming of data channels as we do for
4304 // MediaStreams and Tracks.
4305 // For MediaStreams, the sync_label is the MediaStream label and the
4306 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004307 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004308 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004309 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004310 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004311 continue;
4312 }
4313 // Set the SSRC the data channel should use for sending.
4314 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4315 existing_channels.push_back(data_channel_it->first);
4316 }
4317
4318 UpdateClosingRtpDataChannels(existing_channels, true);
4319}
4320
4321void PeerConnection::UpdateRemoteRtpDataChannels(
4322 const cricket::StreamParamsVec& streams) {
4323 std::vector<std::string> existing_channels;
4324
4325 // Find new and active data channels.
4326 for (const cricket::StreamParams& params : streams) {
4327 // The data channel label is either the mslabel or the SSRC if the mslabel
4328 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004329 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004330 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004331 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004332 auto data_channel_it = rtp_data_channels_.find(label);
4333 if (data_channel_it == rtp_data_channels_.end()) {
4334 // This is a new data channel.
4335 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4336 } else {
4337 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4338 }
4339 existing_channels.push_back(label);
4340 }
4341
4342 UpdateClosingRtpDataChannels(existing_channels, false);
4343}
4344
4345void PeerConnection::UpdateClosingRtpDataChannels(
4346 const std::vector<std::string>& active_channels,
4347 bool is_local_update) {
4348 auto it = rtp_data_channels_.begin();
4349 while (it != rtp_data_channels_.end()) {
4350 DataChannel* data_channel = it->second;
4351 if (std::find(active_channels.begin(), active_channels.end(),
4352 data_channel->label()) != active_channels.end()) {
4353 ++it;
4354 continue;
4355 }
4356
4357 if (is_local_update) {
4358 data_channel->SetSendSsrc(0);
4359 } else {
4360 data_channel->RemotePeerRequestClose();
4361 }
4362
4363 if (data_channel->state() == DataChannel::kClosed) {
4364 rtp_data_channels_.erase(it);
4365 it = rtp_data_channels_.begin();
4366 } else {
4367 ++it;
4368 }
4369 }
4370}
4371
4372void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4373 uint32_t remote_ssrc) {
4374 rtc::scoped_refptr<DataChannel> channel(
4375 InternalCreateDataChannel(label, nullptr));
4376 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004377 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004378 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004379 return;
4380 }
4381 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004382 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4383 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004384 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004385}
4386
4387rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4388 const std::string& label,
4389 const InternalDataChannelInit* config) {
4390 if (IsClosed()) {
4391 return nullptr;
4392 }
Steve Anton75737c02017-11-06 10:37:17 -08004393 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004394 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004395 << "InternalCreateDataChannel: Data is not supported in this call.";
4396 return nullptr;
4397 }
4398 InternalDataChannelInit new_config =
4399 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004400 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004401 if (new_config.id < 0) {
4402 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004403 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004404 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004405 RTC_LOG(LS_ERROR)
4406 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004407 return nullptr;
4408 }
4409 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004410 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004411 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004412 return nullptr;
4413 }
4414 }
4415
Steve Anton75737c02017-11-06 10:37:17 -08004416 rtc::scoped_refptr<DataChannel> channel(
4417 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004418 if (!channel) {
4419 sid_allocator_.ReleaseSid(new_config.id);
4420 return nullptr;
4421 }
4422
4423 if (channel->data_channel_type() == cricket::DCT_RTP) {
4424 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004425 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4426 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004427 return nullptr;
4428 }
4429 rtp_data_channels_[channel->label()] = channel;
4430 } else {
4431 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4432 sctp_data_channels_.push_back(channel);
4433 channel->SignalClosed.connect(this,
4434 &PeerConnection::OnSctpDataChannelClosed);
4435 }
4436
Steve Anton2d8609c2018-01-23 16:38:46 -08004437 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004438 return channel;
4439}
4440
4441bool PeerConnection::HasDataChannels() const {
4442 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4443}
4444
4445void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4446 for (const auto& channel : sctp_data_channels_) {
4447 if (channel->id() < 0) {
4448 int sid;
4449 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004450 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004451 continue;
4452 }
4453 channel->SetSctpSid(sid);
4454 }
4455 }
4456}
4457
4458void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004459 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004460 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4461 ++it) {
4462 if (it->get() == channel) {
4463 if (channel->id() >= 0) {
4464 sid_allocator_.ReleaseSid(channel->id());
4465 }
deadbeefbd292462015-12-14 18:15:29 -08004466 // Since this method is triggered by a signal from the DataChannel,
4467 // we can't free it directly here; we need to free it asynchronously.
4468 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004469 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004470 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4471 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004472 return;
4473 }
4474 }
4475}
4476
deadbeefab9b2d12015-10-14 11:33:11 -07004477void PeerConnection::OnDataChannelDestroyed() {
4478 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4479 // DataChannel may callback to us and try to modify the list.
4480 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4481 temp_rtp_dcs.swap(rtp_data_channels_);
4482 for (const auto& kv : temp_rtp_dcs) {
4483 kv.second->OnTransportChannelDestroyed();
4484 }
4485
4486 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4487 temp_sctp_dcs.swap(sctp_data_channels_);
4488 for (const auto& channel : temp_sctp_dcs) {
4489 channel->OnTransportChannelDestroyed();
4490 }
4491}
4492
4493void PeerConnection::OnDataChannelOpenMessage(
4494 const std::string& label,
4495 const InternalDataChannelInit& config) {
4496 rtc::scoped_refptr<DataChannel> channel(
4497 InternalCreateDataChannel(label, &config));
4498 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004499 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004500 return;
4501 }
4502
deadbeefa601f5c2016-06-06 14:27:39 -07004503 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4504 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004505 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004506}
4507
Steve Anton4171afb2017-11-20 10:20:22 -08004508rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4509PeerConnection::GetAudioTransceiver() 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_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004515 return transceiver;
4516 }
4517 }
4518 RTC_NOTREACHED();
4519 return nullptr;
4520}
4521
4522rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4523PeerConnection::GetVideoTransceiver() const {
4524 // This method only works with Plan B SDP, where there is a single
4525 // audio/video transceiver.
4526 RTC_DCHECK(!IsUnifiedPlan());
4527 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004528 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004529 return transceiver;
4530 }
4531 }
4532 RTC_NOTREACHED();
4533 return nullptr;
4534}
4535
4536// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4537// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004538bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004539 switch (type) {
4540 case cricket::MEDIA_TYPE_AUDIO:
4541 return !GetAudioTransceiver()->internal()->senders().empty();
4542 case cricket::MEDIA_TYPE_VIDEO:
4543 return !GetVideoTransceiver()->internal()->senders().empty();
4544 case cricket::MEDIA_TYPE_DATA:
4545 return false;
4546 }
4547 RTC_NOTREACHED();
4548 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004549}
4550
Steve Anton4171afb2017-11-20 10:20:22 -08004551rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4552PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4553 for (auto transceiver : transceivers_) {
4554 for (auto sender : transceiver->internal()->senders()) {
4555 if (sender->track() == track) {
4556 return sender;
4557 }
4558 }
4559 }
4560 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004561}
4562
Steve Anton4171afb2017-11-20 10:20:22 -08004563rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4564PeerConnection::FindSenderById(const std::string& sender_id) const {
4565 for (auto transceiver : transceivers_) {
4566 for (auto sender : transceiver->internal()->senders()) {
4567 if (sender->id() == sender_id) {
4568 return sender;
4569 }
4570 }
4571 }
4572 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004573}
4574
Steve Anton4171afb2017-11-20 10:20:22 -08004575rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4576PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4577 for (auto transceiver : transceivers_) {
4578 for (auto receiver : transceiver->internal()->receivers()) {
4579 if (receiver->id() == receiver_id) {
4580 return receiver;
4581 }
4582 }
4583 }
4584 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004585}
4586
Steve Anton4171afb2017-11-20 10:20:22 -08004587std::vector<PeerConnection::RtpSenderInfo>*
4588PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4589 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4590 media_type == cricket::MEDIA_TYPE_VIDEO);
4591 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4592 ? &remote_audio_sender_infos_
4593 : &remote_video_sender_infos_;
4594}
4595
4596std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004597 cricket::MediaType media_type) {
4598 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4599 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004600 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4601 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004602}
4603
Steve Anton4171afb2017-11-20 10:20:22 -08004604const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4605 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004606 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004607 const std::string sender_id) const {
4608 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004609 if (sender_info.stream_id == stream_id &&
4610 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004611 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004612 }
4613 }
4614 return nullptr;
4615}
4616
4617DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4618 for (const auto& channel : sctp_data_channels_) {
4619 if (channel->id() == sid) {
4620 return channel;
4621 }
4622 }
4623 return nullptr;
4624}
4625
deadbeef91dd5672016-05-18 16:55:30 -07004626bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004627 const RTCConfiguration& configuration) {
4628 cricket::ServerAddresses stun_servers;
4629 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004630 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4631 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004632 return false;
4633 }
4634
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004635 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004636 // To handle both internal and externally created port allocator, we will
4637 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004638 port_allocator_flags_ = port_allocator_->flags();
4639 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4640 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4641 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004642 // If the disable-IPv6 flag was specified, we'll not override it
4643 // by experiment.
4644 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004645 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004646 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4647 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004648 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004649 }
4650
zhihuangb09b3f92017-03-07 14:40:51 -08004651 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004652 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004653 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004654 }
4655
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004656 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004657 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004658 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004659 }
4660
honghaiz60347052016-05-31 18:29:12 -07004661 if (configuration.candidate_network_policy ==
4662 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004663 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004664 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004665 }
4666
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004667 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004668 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004669 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4670 }
4671
Qingsi Wanga2d60672018-04-11 16:57:45 -07004672 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004673 // No step delay is used while allocating ports.
4674 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4675 port_allocator_->set_candidate_filter(
4676 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004677 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004678
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004679 if (tls_cert_verifier_ != nullptr) {
4680 for (auto& turn_server : turn_servers) {
4681 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4682 }
4683 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004684 // Call this last since it may create pooled allocator sessions using the
4685 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004686 port_allocator_->SetConfiguration(
4687 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4688 configuration.prune_turn_ports, configuration.turn_customizer,
4689 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004690 return true;
4691}
4692
deadbeef91dd5672016-05-18 16:55:30 -07004693bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004694 const cricket::ServerAddresses& stun_servers,
4695 const std::vector<cricket::RelayServerConfig>& turn_servers,
4696 IceTransportsType type,
4697 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004698 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004699 webrtc::TurnCustomizer* turn_customizer,
4700 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004701 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004702 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004703 // According to JSEP, after setLocalDescription, changing the candidate pool
4704 // size is not allowed, and changing the set of ICE servers will not result
4705 // in new candidates being gathered.
4706 if (local_description()) {
4707 port_allocator_->FreezeCandidatePool();
4708 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004709 // Call this last since it may create pooled allocator sessions using the
4710 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004711 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004712 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004713 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004714}
4715
Steve Antonba818672017-11-06 10:21:57 -08004716cricket::ChannelManager* PeerConnection::channel_manager() const {
4717 return factory_->channel_manager();
4718}
4719
4720MetricsObserverInterface* PeerConnection::metrics_observer() const {
4721 return uma_observer_;
4722}
4723
Elad Alon99c3fe52017-10-13 16:29:40 +02004724bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004725 std::unique_ptr<RtcEventLogOutput> output,
4726 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004727 if (!event_log_) {
4728 return false;
4729 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004730 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004731}
4732
4733void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004734 if (event_log_) {
4735 event_log_->StopLogging();
4736 }
ivoc14d5dbe2016-07-04 07:06:55 -07004737}
nisseeaabdf62017-05-05 02:23:02 -07004738
Steve Anton75737c02017-11-06 10:37:17 -08004739cricket::BaseChannel* PeerConnection::GetChannel(
4740 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004741 for (auto transceiver : transceivers_) {
4742 cricket::BaseChannel* channel = transceiver->internal()->channel();
4743 if (channel && channel->content_name() == content_name) {
4744 return channel;
4745 }
Steve Anton75737c02017-11-06 10:37:17 -08004746 }
4747 if (rtp_data_channel() &&
4748 rtp_data_channel()->content_name() == content_name) {
4749 return rtp_data_channel();
4750 }
4751 return nullptr;
4752}
4753
4754bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4755 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004756 RTC_LOG(LS_INFO)
4757 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004758 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004759 return false;
4760 }
4761 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004762 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004763 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004764 return false;
4765 }
4766
Zhi Huange830e682018-03-30 10:48:35 -07004767 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4768 if (dtls_role) {
4769 *role = *dtls_role;
4770 return true;
4771 }
4772 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004773}
4774
4775bool PeerConnection::GetSslRole(const std::string& content_name,
4776 rtc::SSLRole* role) {
4777 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004778 RTC_LOG(LS_INFO)
4779 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004780 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004781 return false;
4782 }
4783
Zhi Huange830e682018-03-30 10:48:35 -07004784 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4785 if (dtls_role) {
4786 *role = *dtls_role;
4787 return true;
4788 }
4789 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004790}
4791
Steve Antonf8470812017-12-04 10:46:21 -08004792void PeerConnection::SetSessionError(SessionError error,
4793 const std::string& error_desc) {
4794 RTC_DCHECK_RUN_ON(signaling_thread());
4795 if (error != session_error_) {
4796 session_error_ = error;
4797 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004798 }
4799}
4800
Zhi Huange830e682018-03-30 10:48:35 -07004801RTCError PeerConnection::UpdateSessionState(
4802 SdpType type,
4803 cricket::ContentSource source,
4804 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004805 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004806
4807 // If there's already a pending error then no state transition should happen.
4808 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004809 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004810
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004811 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004812 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004813 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004814 }
4815
4816 // Update the signaling state according to the specified state machine (see
4817 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004818 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004819 ChangeSignalingState(source == cricket::CS_LOCAL
4820 ? PeerConnectionInterface::kHaveLocalOffer
4821 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004822 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004823 ChangeSignalingState(source == cricket::CS_LOCAL
4824 ? PeerConnectionInterface::kHaveLocalPrAnswer
4825 : PeerConnectionInterface::kHaveRemotePrAnswer);
4826 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004827 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004828 ChangeSignalingState(PeerConnectionInterface::kStable);
4829 }
4830
4831 // Update internal objects according to the session description's media
4832 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004833 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004834 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004835 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004836 }
4837
Steve Anton8a006912017-12-04 15:25:56 -08004838 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004839}
4840
Steve Anton8a006912017-12-04 15:25:56 -08004841RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004842 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004843 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004844 const SessionDescriptionInterface* sdesc =
4845 (source == cricket::CS_LOCAL ? local_description()
4846 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004847 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004848
4849 // Push down the new SDP media section for each audio/video transceiver.
4850 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004851 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004852 FindMediaSectionForTransceiver(transceiver, sdesc);
4853 cricket::BaseChannel* channel = transceiver->internal()->channel();
4854 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004855 continue;
4856 }
4857 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004858 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004859 if (!content_desc) {
4860 continue;
4861 }
4862 std::string error;
4863 bool success =
4864 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004865 ? channel->SetLocalContent(content_desc, type, &error)
4866 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004867 if (!success) {
4868 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4869 }
4870 }
4871
4872 // If using the RtpDataChannel, push down the new SDP section for it too.
4873 if (rtp_data_channel_) {
4874 const ContentInfo* data_content =
4875 cricket::GetFirstDataContent(sdesc->description());
4876 if (data_content && !data_content->rejected) {
4877 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004878 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004879 if (data_desc) {
4880 std::string error;
4881 bool success =
4882 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004883 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4884 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004885 &error);
4886 if (!success) {
4887 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4888 std::move(error));
4889 }
Steve Anton75737c02017-11-06 10:37:17 -08004890 }
4891 }
4892 }
Steve Antoned10bd92017-12-05 10:52:59 -08004893
Steve Anton75737c02017-11-06 10:37:17 -08004894 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4895 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4896 if (sctp_transport_ && local_description() && remote_description() &&
4897 cricket::GetFirstDataContent(local_description()->description()) &&
4898 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004899 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004900 RTC_FROM_HERE,
4901 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004902 if (!success) {
4903 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4904 "Failed to push down SCTP parameters.");
4905 }
Steve Anton75737c02017-11-06 10:37:17 -08004906 }
Steve Antoned10bd92017-12-05 10:52:59 -08004907
Steve Anton8a006912017-12-04 15:25:56 -08004908 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004909}
4910
4911bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4912 RTC_DCHECK(network_thread()->IsCurrent());
4913 RTC_DCHECK(local_description());
4914 RTC_DCHECK(remote_description());
4915 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4916 // When we support "max-message-size", that would also be pushed down here.
4917 return sctp_transport_->Start(
4918 GetSctpPort(local_description()->description()),
4919 GetSctpPort(remote_description()->description()));
4920}
4921
Steve Anton8a006912017-12-04 15:25:56 -08004922RTCError PeerConnection::PushdownTransportDescription(
4923 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004924 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004925 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004926
Zhi Huange830e682018-03-30 10:48:35 -07004927 if (source == cricket::CS_LOCAL) {
4928 const SessionDescriptionInterface* sdesc = local_description();
4929 RTC_DCHECK(sdesc);
4930 return transport_controller_->SetLocalDescription(type,
4931 sdesc->description());
4932 } else {
4933 const SessionDescriptionInterface* sdesc = remote_description();
4934 RTC_DCHECK(sdesc);
4935 return transport_controller_->SetRemoteDescription(type,
4936 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004937 }
Steve Anton75737c02017-11-06 10:37:17 -08004938}
4939
4940bool PeerConnection::GetTransportDescription(
4941 const SessionDescription* description,
4942 const std::string& content_name,
4943 cricket::TransportDescription* tdesc) {
4944 if (!description || !tdesc) {
4945 return false;
4946 }
4947 const TransportInfo* transport_info =
4948 description->GetTransportInfoByName(content_name);
4949 if (!transport_info) {
4950 return false;
4951 }
4952 *tdesc = transport_info->description;
4953 return true;
4954}
4955
Steve Anton75737c02017-11-06 10:37:17 -08004956cricket::IceConfig PeerConnection::ParseIceConfig(
4957 const PeerConnectionInterface::RTCConfiguration& config) const {
4958 cricket::ContinualGatheringPolicy gathering_policy;
4959 // TODO(honghaiz): Add the third continual gathering policy in
4960 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4961 switch (config.continual_gathering_policy) {
4962 case PeerConnectionInterface::GATHER_ONCE:
4963 gathering_policy = cricket::GATHER_ONCE;
4964 break;
4965 case PeerConnectionInterface::GATHER_CONTINUALLY:
4966 gathering_policy = cricket::GATHER_CONTINUALLY;
4967 break;
4968 default:
4969 RTC_NOTREACHED();
4970 gathering_policy = cricket::GATHER_ONCE;
4971 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004972
Steve Anton75737c02017-11-06 10:37:17 -08004973 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004974 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4975 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004976 ice_config.prioritize_most_likely_candidate_pairs =
4977 config.prioritize_most_likely_ice_candidate_pairs;
4978 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004979 RTCConfigurationToIceConfigOptionalInt(
4980 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004981 ice_config.continual_gathering_policy = gathering_policy;
4982 ice_config.presume_writable_when_fully_relayed =
4983 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004984 ice_config.ice_check_interval_strong_connectivity =
4985 config.ice_check_interval_strong_connectivity;
4986 ice_config.ice_check_interval_weak_connectivity =
4987 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004988 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004989 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004990 ice_config.regather_all_networks_interval_range =
4991 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004992 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004993 return ice_config;
4994}
4995
Steve Anton75737c02017-11-06 10:37:17 -08004996bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
4997 std::string* track_id) {
4998 if (!local_description()) {
4999 return false;
5000 }
5001 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5002 track_id);
5003}
5004
5005bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5006 std::string* track_id) {
5007 if (!remote_description()) {
5008 return false;
5009 }
5010 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5011 track_id);
5012}
5013
5014bool PeerConnection::SendData(const cricket::SendDataParams& params,
5015 const rtc::CopyOnWriteBuffer& payload,
5016 cricket::SendDataResult* result) {
5017 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005019 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005020 return false;
5021 }
5022 return rtp_data_channel_
5023 ? rtp_data_channel_->SendData(params, payload, result)
5024 : network_thread()->Invoke<bool>(
5025 RTC_FROM_HERE,
5026 Bind(&cricket::SctpTransportInternal::SendData,
5027 sctp_transport_.get(), params, payload, result));
5028}
5029
5030bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5031 if (!rtp_data_channel_ && !sctp_transport_) {
5032 // Don't log an error here, because DataChannels are expected to call
5033 // ConnectDataChannel in this state. It's the only way to initially tell
5034 // whether or not the underlying transport is ready.
5035 return false;
5036 }
5037 if (rtp_data_channel_) {
5038 rtp_data_channel_->SignalReadyToSendData.connect(
5039 webrtc_data_channel, &DataChannel::OnChannelReady);
5040 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5041 &DataChannel::OnDataReceived);
5042 } else {
5043 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5044 &DataChannel::OnChannelReady);
5045 SignalSctpDataReceived.connect(webrtc_data_channel,
5046 &DataChannel::OnDataReceived);
5047 SignalSctpStreamClosedRemotely.connect(
5048 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5049 }
5050 return true;
5051}
5052
5053void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5054 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005055 RTC_LOG(LS_ERROR)
5056 << "DisconnectDataChannel called when rtp_data_channel_ and "
5057 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005058 return;
5059 }
5060 if (rtp_data_channel_) {
5061 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5062 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5063 } else {
5064 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5065 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5066 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5067 }
5068}
5069
5070void PeerConnection::AddSctpDataStream(int sid) {
5071 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005072 RTC_LOG(LS_ERROR)
5073 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005074 return;
5075 }
5076 network_thread()->Invoke<void>(
5077 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5078 sctp_transport_.get(), sid));
5079}
5080
5081void PeerConnection::RemoveSctpDataStream(int sid) {
5082 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005083 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005084 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005085 return;
5086 }
5087 network_thread()->Invoke<void>(
5088 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5089 sctp_transport_.get(), sid));
5090}
5091
5092bool PeerConnection::ReadyToSendData() const {
5093 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5094 sctp_ready_to_send_data_;
5095}
5096
Zhi Huange830e682018-03-30 10:48:35 -07005097rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5098 if (sctp_mid_ && transport_controller_) {
5099 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5100 if (dtls_transport) {
5101 return dtls_transport->transport_name();
5102 }
5103 return rtc::Optional<std::string>();
5104 }
5105 return rtc::Optional<std::string>();
5106}
5107
Qingsi Wang72a43a12018-02-20 16:03:18 -08005108cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5109 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005110 network_thread()->Invoke<void>(
5111 RTC_FROM_HERE,
5112 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5113 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005114 return candidate_states_list;
5115}
5116
Steve Anton5dfde182018-02-06 10:34:40 -08005117std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5118 const {
5119 std::map<std::string, std::string> transport_names_by_mid;
5120 for (auto transceiver : transceivers_) {
5121 cricket::BaseChannel* channel = transceiver->internal()->channel();
5122 if (channel) {
5123 transport_names_by_mid[channel->content_name()] =
5124 channel->transport_name();
5125 }
Steve Anton75737c02017-11-06 10:37:17 -08005126 }
Steve Anton5dfde182018-02-06 10:34:40 -08005127 if (rtp_data_channel_) {
5128 transport_names_by_mid[rtp_data_channel_->content_name()] =
5129 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005130 }
5131 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005132 rtc::Optional<std::string> transport_name = sctp_transport_name();
5133 RTC_DCHECK(transport_name);
5134 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005135 }
Steve Anton5dfde182018-02-06 10:34:40 -08005136 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005137}
5138
Steve Anton5dfde182018-02-06 10:34:40 -08005139std::map<std::string, cricket::TransportStats>
5140PeerConnection::GetTransportStatsByNames(
5141 const std::set<std::string>& transport_names) {
5142 if (!network_thread()->IsCurrent()) {
5143 return network_thread()
5144 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5145 RTC_FROM_HERE,
5146 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005147 }
Steve Anton5dfde182018-02-06 10:34:40 -08005148 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5149 for (const std::string& transport_name : transport_names) {
5150 cricket::TransportStats transport_stats;
5151 bool success =
5152 transport_controller_->GetStats(transport_name, &transport_stats);
5153 if (success) {
5154 transport_stats_by_name[transport_name] = std::move(transport_stats);
5155 } else {
5156 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5157 << transport_name;
5158 }
5159 }
5160 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005161}
5162
5163bool PeerConnection::GetLocalCertificate(
5164 const std::string& transport_name,
5165 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005166 if (!certificate) {
5167 return false;
5168 }
5169 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5170 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005171}
5172
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005173std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005174 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005175 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005176}
5177
5178cricket::DataChannelType PeerConnection::data_channel_type() const {
5179 return data_channel_type_;
5180}
5181
5182bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5183 return pending_ice_restarts_.find(content_name) !=
5184 pending_ice_restarts_.end();
5185}
5186
Steve Anton75737c02017-11-06 10:37:17 -08005187bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5188 return transport_controller_->NeedsIceRestart(content_name);
5189}
5190
5191void PeerConnection::OnCertificateReady(
5192 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5193 transport_controller_->SetLocalCertificate(certificate);
5194}
5195
5196void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005197 SetSessionError(SessionError::kTransport,
5198 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005199}
5200
5201void PeerConnection::OnTransportControllerConnectionState(
5202 cricket::IceConnectionState state) {
5203 switch (state) {
5204 case cricket::kIceConnectionConnecting:
5205 // If the current state is Connected or Completed, then there were
5206 // writable channels but now there are not, so the next state must
5207 // be Disconnected.
5208 // kIceConnectionConnecting is currently used as the default,
5209 // un-connected state by the TransportController, so its only use is
5210 // detecting disconnections.
5211 if (ice_connection_state_ ==
5212 PeerConnectionInterface::kIceConnectionConnected ||
5213 ice_connection_state_ ==
5214 PeerConnectionInterface::kIceConnectionCompleted) {
5215 SetIceConnectionState(
5216 PeerConnectionInterface::kIceConnectionDisconnected);
5217 }
5218 break;
5219 case cricket::kIceConnectionFailed:
5220 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5221 break;
5222 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005223 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005224 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005225 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5226 break;
5227 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005228 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005229 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005230 if (ice_connection_state_ !=
5231 PeerConnectionInterface::kIceConnectionConnected) {
5232 // If jumping directly from "checking" to "connected",
5233 // signal "connected" first.
5234 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5235 }
5236 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5237 if (metrics_observer()) {
5238 ReportTransportStats();
5239 }
5240 break;
5241 default:
5242 RTC_NOTREACHED();
5243 }
5244}
5245
5246void PeerConnection::OnTransportControllerCandidatesGathered(
5247 const std::string& transport_name,
5248 const cricket::Candidates& candidates) {
5249 RTC_DCHECK(signaling_thread()->IsCurrent());
5250 int sdp_mline_index;
5251 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005252 RTC_LOG(LS_ERROR)
5253 << "OnTransportControllerCandidatesGathered: content name "
5254 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005255 return;
5256 }
5257
5258 for (cricket::Candidates::const_iterator citer = candidates.begin();
5259 citer != candidates.end(); ++citer) {
5260 // Use transport_name as the candidate media id.
5261 std::unique_ptr<JsepIceCandidate> candidate(
5262 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5263 if (local_description()) {
5264 mutable_local_description()->AddCandidate(candidate.get());
5265 }
5266 OnIceCandidate(std::move(candidate));
5267 }
5268}
5269
5270void PeerConnection::OnTransportControllerCandidatesRemoved(
5271 const std::vector<cricket::Candidate>& candidates) {
5272 RTC_DCHECK(signaling_thread()->IsCurrent());
5273 // Sanity check.
5274 for (const cricket::Candidate& candidate : candidates) {
5275 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005276 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005277 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005278 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005279 return;
5280 }
5281 }
5282
5283 if (local_description()) {
5284 mutable_local_description()->RemoveCandidates(candidates);
5285 }
5286 OnIceCandidatesRemoved(candidates);
5287}
5288
5289void PeerConnection::OnTransportControllerDtlsHandshakeError(
5290 rtc::SSLHandshakeError error) {
5291 if (metrics_observer()) {
5292 metrics_observer()->IncrementEnumCounter(
5293 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5294 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5295 }
5296}
5297
Steve Antoned10bd92017-12-05 10:52:59 -08005298void PeerConnection::EnableSending() {
5299 for (auto transceiver : transceivers_) {
5300 cricket::BaseChannel* channel = transceiver->internal()->channel();
5301 if (channel && !channel->enabled()) {
5302 channel->Enable(true);
5303 }
Steve Anton75737c02017-11-06 10:37:17 -08005304 }
5305
Steve Anton4171afb2017-11-20 10:20:22 -08005306 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005307 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005308 }
Steve Anton75737c02017-11-06 10:37:17 -08005309}
5310
5311// Returns the media index for a local ice candidate given the content name.
5312bool PeerConnection::GetLocalCandidateMediaIndex(
5313 const std::string& content_name,
5314 int* sdp_mline_index) {
5315 if (!local_description() || !sdp_mline_index) {
5316 return false;
5317 }
5318
5319 bool content_found = false;
5320 const ContentInfos& contents = local_description()->description()->contents();
5321 for (size_t index = 0; index < contents.size(); ++index) {
5322 if (contents[index].name == content_name) {
5323 *sdp_mline_index = static_cast<int>(index);
5324 content_found = true;
5325 break;
5326 }
5327 }
5328 return content_found;
5329}
5330
5331bool PeerConnection::UseCandidatesInSessionDescription(
5332 const SessionDescriptionInterface* remote_desc) {
5333 if (!remote_desc) {
5334 return true;
5335 }
5336 bool ret = true;
5337
5338 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5339 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5340 for (size_t n = 0; n < candidates->count(); ++n) {
5341 const IceCandidateInterface* candidate = candidates->at(n);
5342 bool valid = false;
5343 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5344 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005345 RTC_LOG(LS_INFO)
5346 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005347 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005348 }
5349 continue;
5350 }
5351 ret = UseCandidate(candidate);
5352 if (!ret) {
5353 break;
5354 }
5355 }
5356 }
5357 return ret;
5358}
5359
5360bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5361 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5362 size_t remote_content_size =
5363 remote_description()->description()->contents().size();
5364 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005365 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005366 return false;
5367 }
5368
5369 cricket::ContentInfo content =
5370 remote_description()->description()->contents()[mediacontent_index];
5371 std::vector<cricket::Candidate> candidates;
5372 candidates.push_back(candidate->candidate());
5373 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005374 RTCError error =
5375 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005376 if (error.ok()) {
5377 // Candidates successfully submitted for checking.
5378 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5379 ice_connection_state_ ==
5380 PeerConnectionInterface::kIceConnectionDisconnected) {
5381 // If state is New, then the session has just gotten its first remote ICE
5382 // candidates, so go to Checking.
5383 // If state is Disconnected, the session is re-using old candidates or
5384 // receiving additional ones, so go to Checking.
5385 // If state is Connected, stay Connected.
5386 // TODO(bemasc): If state is Connected, and the new candidates are for a
5387 // newly added transport, then the state actually _should_ move to
5388 // checking. Add a way to distinguish that case.
5389 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5390 }
5391 // TODO(bemasc): If state is Completed, go back to Connected.
5392 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005393 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005394 }
5395 return true;
5396}
5397
5398void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005399 // Destroy video channel first since it may have a pointer to the
5400 // voice channel.
5401 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005402 if (!video_info || video_info->rejected) {
5403 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005404 }
5405
Steve Anton6fec8802017-12-04 10:37:29 -08005406 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5407 if (!audio_info || audio_info->rejected) {
5408 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005409 }
5410
5411 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5412 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005413 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005414 }
5415}
5416
Steve Antondcc3c022017-12-22 16:02:54 -08005417RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5418 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005419 const cricket::ContentGroup* bundle_group = nullptr;
5420 if (configuration_.bundle_policy ==
5421 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005422 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005423 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005424 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5425 "max-bundle configured but session description "
5426 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005427 }
5428 }
Steve Antondcc3c022017-12-22 16:02:54 -08005429 return std::move(bundle_group);
5430}
5431
5432RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005433 // Creating the media channels. Transports should already have been created
5434 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005435 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005436 if (voice && !voice->rejected &&
5437 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005438 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005439 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005440 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5441 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005442 }
5443 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5444 }
5445
Steve Antondcc3c022017-12-22 16:02:54 -08005446 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005447 if (video && !video->rejected &&
5448 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005449 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005450 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005451 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5452 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005453 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005454 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005455 }
5456
Steve Antondcc3c022017-12-22 16:02:54 -08005457 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005458 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5459 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005460 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005461 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5462 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005463 }
5464 }
5465
Steve Anton8a006912017-12-04 15:25:56 -08005466 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005467}
5468
Steve Anton4171afb2017-11-20 10:20:22 -08005469// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005470cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005471 const std::string& mid) {
5472 RtpTransportInternal* rtp_transport =
5473 transport_controller_->GetRtpTransport(mid);
5474 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005475 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005476 call_.get(), configuration_.media_config, rtp_transport,
5477 signaling_thread(), mid, SrtpRequired(),
5478 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005479 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005480 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005481 }
Steve Anton75737c02017-11-06 10:37:17 -08005482 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5483 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005484 voice_channel->SignalSentPacket.connect(this,
5485 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005486 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005487 if (uma_observer_) {
5488 voice_channel->SetMetricsObserver(uma_observer_);
5489 }
Steve Anton4171afb2017-11-20 10:20:22 -08005490
Steve Antoneda6ccd2017-12-04 10:21:55 -08005491 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005492}
5493
Steve Anton4171afb2017-11-20 10:20:22 -08005494// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005495cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005496 const std::string& mid) {
5497 RtpTransportInternal* rtp_transport =
5498 transport_controller_->GetRtpTransport(mid);
5499 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005500 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005501 call_.get(), configuration_.media_config, rtp_transport,
5502 signaling_thread(), mid, SrtpRequired(),
5503 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005504 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005505 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005506 }
Steve Anton75737c02017-11-06 10:37:17 -08005507 video_channel->SignalDtlsSrtpSetupFailure.connect(
5508 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005509 video_channel->SignalSentPacket.connect(this,
5510 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005511 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005512 if (uma_observer_) {
5513 video_channel->SetMetricsObserver(uma_observer_);
5514 }
Steve Anton4171afb2017-11-20 10:20:22 -08005515
Steve Antoneda6ccd2017-12-04 10:21:55 -08005516 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005517}
5518
Zhi Huange830e682018-03-30 10:48:35 -07005519bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005520 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5521 if (sctp) {
5522 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005523 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005524 << "Trying to create SCTP transport, but didn't compile with "
5525 "SCTP support (HAVE_SCTP)";
5526 return false;
5527 }
5528 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005529 RTC_FROM_HERE,
5530 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005531 return false;
5532 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005533 for (const auto& channel : sctp_data_channels_) {
5534 channel->OnTransportChannelCreated();
5535 }
Steve Anton75737c02017-11-06 10:37:17 -08005536 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005537 RtpTransportInternal* rtp_transport =
5538 transport_controller_->GetRtpTransport(mid);
5539 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005540 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005541 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5542 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005543 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005544 return false;
5545 }
Steve Anton75737c02017-11-06 10:37:17 -08005546 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5547 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5548 rtp_data_channel_->SignalSentPacket.connect(
5549 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005550 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005551 if (uma_observer_) {
5552 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5553 }
Steve Anton75737c02017-11-06 10:37:17 -08005554 }
5555
Steve Anton75737c02017-11-06 10:37:17 -08005556 return true;
5557}
5558
5559Call::Stats PeerConnection::GetCallStats() {
5560 if (!worker_thread()->IsCurrent()) {
5561 return worker_thread()->Invoke<Call::Stats>(
5562 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5563 }
5564 if (call_) {
5565 return call_->GetStats();
5566 } else {
5567 return Call::Stats();
5568 }
5569}
5570
Zhi Huange830e682018-03-30 10:48:35 -07005571bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005572 RTC_DCHECK(network_thread()->IsCurrent());
5573 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005574 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005575 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005576 RTC_DCHECK(dtls_transport);
5577 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005578 RTC_DCHECK(sctp_transport_);
5579 sctp_invoker_.reset(new rtc::AsyncInvoker());
5580 sctp_transport_->SignalReadyToSendData.connect(
5581 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5582 sctp_transport_->SignalDataReceived.connect(
5583 this, &PeerConnection::OnSctpTransportDataReceived_n);
5584 sctp_transport_->SignalStreamClosedRemotely.connect(
5585 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Zhi Huange830e682018-03-30 10:48:35 -07005586 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005587 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005588 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005589}
5590
5591void PeerConnection::DestroySctpTransport_n() {
5592 RTC_DCHECK(network_thread()->IsCurrent());
5593 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005594 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005595 sctp_invoker_.reset(nullptr);
5596 sctp_ready_to_send_data_ = false;
5597}
5598
5599void PeerConnection::OnSctpTransportReadyToSendData_n() {
5600 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5601 RTC_DCHECK(network_thread()->IsCurrent());
5602 // Note: Cannot use rtc::Bind here because it will grab a reference to
5603 // PeerConnection and potentially cause PeerConnection to live longer than
5604 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5605 // be destroyed before PeerConnection is destroyed, and at that point all
5606 // pending tasks will be cleared.
5607 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5608 OnSctpTransportReadyToSendData_s(true);
5609 });
5610}
5611
5612void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5613 RTC_DCHECK(signaling_thread()->IsCurrent());
5614 sctp_ready_to_send_data_ = ready;
5615 SignalSctpReadyToSendData(ready);
5616}
5617
5618void PeerConnection::OnSctpTransportDataReceived_n(
5619 const cricket::ReceiveDataParams& params,
5620 const rtc::CopyOnWriteBuffer& payload) {
5621 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5622 RTC_DCHECK(network_thread()->IsCurrent());
5623 // Note: Cannot use rtc::Bind here because it will grab a reference to
5624 // PeerConnection and potentially cause PeerConnection to live longer than
5625 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5626 // be destroyed before PeerConnection is destroyed, and at that point all
5627 // pending tasks will be cleared.
5628 sctp_invoker_->AsyncInvoke<void>(
5629 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5630 OnSctpTransportDataReceived_s(params, payload);
5631 });
5632}
5633
5634void PeerConnection::OnSctpTransportDataReceived_s(
5635 const cricket::ReceiveDataParams& params,
5636 const rtc::CopyOnWriteBuffer& payload) {
5637 RTC_DCHECK(signaling_thread()->IsCurrent());
5638 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5639 // Received OPEN message; parse and signal that a new data channel should
5640 // be created.
5641 std::string label;
5642 InternalDataChannelInit config;
5643 config.id = params.ssrc;
5644 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005645 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5646 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005647 return;
5648 }
5649 config.open_handshake_role = InternalDataChannelInit::kAcker;
5650 OnDataChannelOpenMessage(label, config);
5651 } else {
5652 // Otherwise just forward the signal.
5653 SignalSctpDataReceived(params, payload);
5654 }
5655}
5656
5657void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5658 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5659 RTC_DCHECK(network_thread()->IsCurrent());
5660 sctp_invoker_->AsyncInvoke<void>(
5661 RTC_FROM_HERE, signaling_thread(),
5662 rtc::Bind(&sigslot::signal1<int>::operator(),
5663 &SignalSctpStreamClosedRemotely, sid));
5664}
5665
5666// Returns false if bundle is enabled and rtcp_mux is disabled.
5667bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5668 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5669 if (!bundle_enabled)
5670 return true;
5671
5672 const cricket::ContentGroup* bundle_group =
5673 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5674 RTC_DCHECK(bundle_group != NULL);
5675
5676 const cricket::ContentInfos& contents = desc->contents();
5677 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5678 citer != contents.end(); ++citer) {
5679 const cricket::ContentInfo* content = (&*citer);
5680 RTC_DCHECK(content != NULL);
5681 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005682 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005683 if (!HasRtcpMuxEnabled(content))
5684 return false;
5685 }
5686 }
5687 // RTCP-MUX is enabled in all the contents.
5688 return true;
5689}
5690
5691bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005692 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005693}
5694
Steve Anton8a006912017-12-04 15:25:56 -08005695RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005696 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005697 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005698 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005699 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005700 }
5701
5702 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005703 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005704 }
5705
Steve Anton3828c062017-12-06 10:34:51 -08005706 SdpType type = sdesc->GetType();
5707 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5708 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005709 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005710 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005711 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005712 }
5713
5714 // Verify crypto settings.
5715 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005716 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5717 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005718 RTCError crypto_error =
5719 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005720 if (!crypto_error.ok()) {
5721 return crypto_error;
5722 }
Steve Anton75737c02017-11-06 10:37:17 -08005723 }
5724
5725 // Verify ice-ufrag and ice-pwd.
5726 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5728 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005729 }
5730
5731 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005732 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5733 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005734 }
5735
5736 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5737 // m-lines that do not rtcp-mux enabled.
5738
5739 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005740 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005741 // With an answer we want to compare the new answer session description with
5742 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005743 const cricket::SessionDescription* offer_desc =
5744 (source == cricket::CS_LOCAL) ? remote_description()->description()
5745 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005746 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5747 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5748 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5750 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005751 }
5752 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005753 // The re-offers should respect the order of m= sections in current
5754 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005755 // With a re-offer, either the current local or current remote descriptions
5756 // could be the most up to date, so we would like to check against both of
5757 // them if they exist. It could be the case that one of them has a 0 port
5758 // for a media section, but the other does not. This is important to check
5759 // against in the case that we are recycling an m= section.
5760 const cricket::SessionDescription* current_desc = nullptr;
5761 const cricket::SessionDescription* secondary_current_desc = nullptr;
5762 if (local_description()) {
5763 current_desc = local_description()->description();
5764 if (remote_description()) {
5765 secondary_current_desc = remote_description()->description();
5766 }
5767 } else if (remote_description()) {
5768 current_desc = remote_description()->description();
5769 }
Steve Anton75737c02017-11-06 10:37:17 -08005770 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005771 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5772 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005773 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5774 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776 }
5777
Steve Antonba42e992018-04-09 14:10:01 -07005778 if (IsUnifiedPlan()) {
5779 // Ensure that each audio and video media section has at most one
5780 // "StreamParams". This will return an error if receiving a session
5781 // description from a "Plan B" endpoint which adds multiple tracks of the
5782 // same type. With Unified Plan, there can only be at most one track per
5783 // media section.
5784 for (const ContentInfo& content : sdesc->description()->contents()) {
5785 const MediaContentDescription& desc = *content.description;
5786 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5787 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5788 desc.streams().size() > 1u) {
5789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5790 "Media section has more than one track specified "
5791 "with a=ssrc lines which is not supported with "
5792 "Unified Plan.");
5793 }
5794 }
5795 }
5796
Steve Anton8a006912017-12-04 15:25:56 -08005797 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005798}
5799
Steve Anton3828c062017-12-06 10:34:51 -08005800bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005801 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005802 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005803 return (state == PeerConnectionInterface::kStable) ||
5804 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005805 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005806 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005807 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5808 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5809 }
5810}
5811
Steve Anton3828c062017-12-06 10:34:51 -08005812bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005813 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005814 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005815 return (state == PeerConnectionInterface::kStable) ||
5816 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005817 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005818 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005819 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5820 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5821 }
5822}
5823
Steve Antonf8470812017-12-04 10:46:21 -08005824const char* PeerConnection::SessionErrorToString(SessionError error) const {
5825 switch (error) {
5826 case SessionError::kNone:
5827 return "ERROR_NONE";
5828 case SessionError::kContent:
5829 return "ERROR_CONTENT";
5830 case SessionError::kTransport:
5831 return "ERROR_TRANSPORT";
5832 }
5833 RTC_NOTREACHED();
5834 return "";
5835}
5836
Steve Anton75737c02017-11-06 10:37:17 -08005837std::string PeerConnection::GetSessionErrorMsg() {
5838 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005839 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5840 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005841 return desc.str();
5842}
5843
Steve Anton8e20f172018-03-06 10:55:04 -08005844void PeerConnection::ReportSdpFormatReceived(
5845 const SessionDescriptionInterface& remote_offer) {
5846 if (!uma_observer_) {
5847 return;
5848 }
5849 int num_audio_mlines = 0;
5850 int num_video_mlines = 0;
5851 int num_audio_tracks = 0;
5852 int num_video_tracks = 0;
5853 for (const ContentInfo& content : remote_offer.description()->contents()) {
5854 cricket::MediaType media_type = content.media_description()->type();
5855 int num_tracks = std::max(
5856 1, static_cast<int>(content.media_description()->streams().size()));
5857 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5858 num_audio_mlines += 1;
5859 num_audio_tracks += num_tracks;
5860 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5861 num_video_mlines += 1;
5862 num_video_tracks += num_tracks;
5863 }
5864 }
5865 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5866 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5867 format = kSdpFormatReceivedComplexUnifiedPlan;
5868 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5869 format = kSdpFormatReceivedComplexPlanB;
5870 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5871 format = kSdpFormatReceivedSimple;
5872 }
5873 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5874 kSdpFormatReceivedMax);
5875}
5876
Steve Anton0ffaaa22018-02-23 10:31:30 -08005877void PeerConnection::ReportNegotiatedSdpSemantics(
5878 const SessionDescriptionInterface& answer) {
5879 if (!uma_observer_) {
5880 return;
5881 }
5882 switch (answer.description()->msid_signaling()) {
5883 case 0:
5884 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5885 kSdpSemanticNegotiatedNone,
5886 kSdpSemanticNegotiatedMax);
5887 break;
5888 case cricket::kMsidSignalingMediaSection:
5889 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5890 kSdpSemanticNegotiatedUnifiedPlan,
5891 kSdpSemanticNegotiatedMax);
5892 break;
5893 case cricket::kMsidSignalingSsrcAttribute:
5894 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5895 kSdpSemanticNegotiatedPlanB,
5896 kSdpSemanticNegotiatedMax);
5897 break;
5898 case cricket::kMsidSignalingMediaSection |
5899 cricket::kMsidSignalingSsrcAttribute:
5900 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5901 kSdpSemanticNegotiatedMixed,
5902 kSdpSemanticNegotiatedMax);
5903 break;
5904 default:
5905 RTC_NOTREACHED();
5906 }
5907}
5908
Steve Anton75737c02017-11-06 10:37:17 -08005909// We need to check the local/remote description for the Transport instead of
5910// the session, because a new Transport added during renegotiation may have
5911// them unset while the session has them set from the previous negotiation.
5912// Not doing so may trigger the auto generation of transport description and
5913// mess up DTLS identity information, ICE credential, etc.
5914bool PeerConnection::ReadyToUseRemoteCandidate(
5915 const IceCandidateInterface* candidate,
5916 const SessionDescriptionInterface* remote_desc,
5917 bool* valid) {
5918 *valid = true;
5919
5920 const SessionDescriptionInterface* current_remote_desc =
5921 remote_desc ? remote_desc : remote_description();
5922
5923 if (!current_remote_desc) {
5924 return false;
5925 }
5926
5927 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5928 size_t remote_content_size =
5929 current_remote_desc->description()->contents().size();
5930 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005931 RTC_LOG(LS_ERROR)
5932 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5933 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005934
5935 *valid = false;
5936 return false;
5937 }
5938
5939 cricket::ContentInfo content =
5940 current_remote_desc->description()->contents()[mediacontent_index];
5941
5942 const std::string transport_name = GetTransportName(content.name);
5943 if (transport_name.empty()) {
5944 return false;
5945 }
Zhi Huange830e682018-03-30 10:48:35 -07005946 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005947}
5948
5949bool PeerConnection::SrtpRequired() const {
5950 return dtls_enabled_ ||
5951 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5952}
5953
5954void PeerConnection::OnTransportControllerGatheringState(
5955 cricket::IceGatheringState state) {
5956 RTC_DCHECK(signaling_thread()->IsCurrent());
5957 if (state == cricket::kIceGatheringGathering) {
5958 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5959 } else if (state == cricket::kIceGatheringComplete) {
5960 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5961 }
5962}
5963
5964void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005965 std::map<std::string, std::set<cricket::MediaType>>
5966 media_types_by_transport_name;
5967 for (auto transceiver : transceivers_) {
5968 if (transceiver->internal()->channel()) {
5969 const std::string& transport_name =
5970 transceiver->internal()->channel()->transport_name();
5971 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08005972 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08005973 }
Steve Anton75737c02017-11-06 10:37:17 -08005974 }
5975 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08005976 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
5977 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005978 }
Zhi Huange830e682018-03-30 10:48:35 -07005979
5980 rtc::Optional<std::string> transport_name = sctp_transport_name();
5981 if (transport_name) {
5982 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08005983 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08005984 }
Zhi Huange830e682018-03-30 10:48:35 -07005985
Steve Antonc7b964c2018-02-01 14:39:45 -08005986 for (const auto& entry : media_types_by_transport_name) {
5987 const std::string& transport_name = entry.first;
5988 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08005989 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08005990 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08005991 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08005992 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08005993 }
5994 }
5995}
5996// Walk through the ConnectionInfos to gather best connection usage
5997// for IPv4 and IPv6.
5998void PeerConnection::ReportBestConnectionState(
5999 const cricket::TransportStats& stats) {
6000 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006001 for (const cricket::TransportChannelStats& channel_stats :
6002 stats.channel_stats) {
6003 for (const cricket::ConnectionInfo& connection_info :
6004 channel_stats.connection_infos) {
6005 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006006 continue;
6007 }
6008
6009 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006010 const cricket::Candidate& local = connection_info.local_candidate;
6011 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006012
6013 // Increment the counter for IceCandidatePairType.
6014 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6015 (local.type() == RELAY_PORT_TYPE &&
6016 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6017 type = kEnumCounterIceCandidatePairTypeTcp;
6018 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6019 type = kEnumCounterIceCandidatePairTypeUdp;
6020 } else {
6021 RTC_CHECK(0);
6022 }
6023 metrics_observer()->IncrementEnumCounter(
6024 type, GetIceCandidatePairCounter(local, remote),
6025 kIceCandidatePairMax);
6026
6027 // Increment the counter for IP type.
6028 if (local.address().family() == AF_INET) {
6029 metrics_observer()->IncrementEnumCounter(
6030 kEnumCounterAddressFamily, kBestConnections_IPv4,
6031 kPeerConnectionAddressFamilyCounter_Max);
6032
6033 } else if (local.address().family() == AF_INET6) {
6034 metrics_observer()->IncrementEnumCounter(
6035 kEnumCounterAddressFamily, kBestConnections_IPv6,
6036 kPeerConnectionAddressFamilyCounter_Max);
6037 } else {
6038 RTC_CHECK(0);
6039 }
6040
6041 return;
6042 }
6043 }
6044}
6045
6046void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006047 const cricket::TransportStats& stats,
6048 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006049 RTC_DCHECK(metrics_observer());
6050 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6051 return;
6052 }
6053
6054 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6055 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6056 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6057 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6058 return;
6059 }
6060
Steve Antonc7b964c2018-02-01 14:39:45 -08006061 for (cricket::MediaType media_type : media_types) {
6062 PeerConnectionEnumCounterType srtp_counter_type;
6063 PeerConnectionEnumCounterType ssl_counter_type;
6064 switch (media_type) {
6065 case cricket::MEDIA_TYPE_AUDIO:
6066 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6067 ssl_counter_type = kEnumCounterAudioSslCipher;
6068 break;
6069 case cricket::MEDIA_TYPE_VIDEO:
6070 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6071 ssl_counter_type = kEnumCounterVideoSslCipher;
6072 break;
6073 case cricket::MEDIA_TYPE_DATA:
6074 srtp_counter_type = kEnumCounterDataSrtpCipher;
6075 ssl_counter_type = kEnumCounterDataSslCipher;
6076 break;
6077 default:
6078 RTC_NOTREACHED();
6079 continue;
6080 }
6081 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6082 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6083 srtp_crypto_suite);
6084 }
6085 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6086 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6087 ssl_cipher_suite);
6088 }
Steve Anton75737c02017-11-06 10:37:17 -08006089 }
6090}
6091
6092void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6093 RTC_DCHECK(worker_thread()->IsCurrent());
6094 RTC_DCHECK(call_);
6095 call_->OnSentPacket(sent_packet);
6096}
6097
6098const std::string PeerConnection::GetTransportName(
6099 const std::string& content_name) {
6100 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006101 if (channel) {
6102 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006103 }
Steve Anton6fec8802017-12-04 10:37:29 -08006104 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006105 RTC_DCHECK(sctp_mid_);
6106 if (content_name == *sctp_mid_) {
6107 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006108 }
6109 }
6110 // Return an empty string if failed to retrieve the transport name.
6111 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006112}
6113
Steve Anton6fec8802017-12-04 10:37:29 -08006114void PeerConnection::DestroyTransceiverChannel(
6115 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6116 transceiver) {
6117 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006118
Steve Anton6fec8802017-12-04 10:37:29 -08006119 cricket::BaseChannel* channel = transceiver->internal()->channel();
6120 if (channel) {
6121 transceiver->internal()->SetChannel(nullptr);
6122 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006123 }
6124}
6125
6126void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006127 if (rtp_data_channel_) {
6128 OnDataChannelDestroyed();
6129 DestroyBaseChannel(rtp_data_channel_);
6130 rtp_data_channel_ = nullptr;
6131 }
6132
6133 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6134 // grab a reference to this PeerConnection. If this is called from the
6135 // PeerConnection destructor, the RefCountedObject vtable will have already
6136 // been destroyed (since it is a subclass of PeerConnection) and using
6137 // rtc::Bind will cause "Pure virtual function called" error to appear.
6138
6139 if (sctp_transport_) {
6140 OnDataChannelDestroyed();
6141 network_thread()->Invoke<void>(RTC_FROM_HERE,
6142 [this] { DestroySctpTransport_n(); });
6143 }
6144}
6145
6146void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6147 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006148 switch (channel->media_type()) {
6149 case cricket::MEDIA_TYPE_AUDIO:
6150 channel_manager()->DestroyVoiceChannel(
6151 static_cast<cricket::VoiceChannel*>(channel));
6152 break;
6153 case cricket::MEDIA_TYPE_VIDEO:
6154 channel_manager()->DestroyVideoChannel(
6155 static_cast<cricket::VideoChannel*>(channel));
6156 break;
6157 case cricket::MEDIA_TYPE_DATA:
6158 channel_manager()->DestroyRtpDataChannel(
6159 static_cast<cricket::RtpDataChannel*>(channel));
6160 break;
6161 default:
6162 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6163 break;
6164 }
Zhi Huange830e682018-03-30 10:48:35 -07006165}
Steve Anton6fec8802017-12-04 10:37:29 -08006166
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006167bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006168 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006169 RtpTransportInternal* rtp_transport,
6170 cricket::DtlsTransportInternal* dtls_transport) {
6171 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006172 auto base_channel = GetChannel(mid);
6173 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006174 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006175 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006176 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006177 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006178 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006179 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006180}
6181
Harald Alvestrand89061872018-01-02 14:08:34 +01006182void PeerConnection::ClearStatsCache() {
6183 if (stats_collector_) {
6184 stats_collector_->ClearCachedStatsReport();
6185 }
6186}
6187
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006188} // namespace webrtc