blob: d99e97f2c961fa50c5838bfc063ff5d7f358acae [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>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/jsepicecandidate.h"
21#include "api/jsepsessiondescription.h"
22#include "api/mediaconstraintsinterface.h"
23#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
25#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080026#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020027#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080031#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080037#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080040#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080041#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010048#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020049#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
Steve Anton75737c02017-11-06 10:37:17 -080056using cricket::ContentInfo;
57using cricket::ContentInfos;
58using cricket::MediaContentDescription;
59using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080060using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::TransportInfo;
62
63using cricket::LOCAL_PORT_TYPE;
64using cricket::STUN_PORT_TYPE;
65using cricket::RELAY_PORT_TYPE;
66using cricket::PRFLX_PORT_TYPE;
67
Steve Antonba818672017-11-06 10:21:57 -080068namespace webrtc {
69
Steve Anton75737c02017-11-06 10:37:17 -080070// Error messages
71const char kBundleWithoutRtcpMux[] =
72 "rtcp-mux must be enabled when BUNDLE "
73 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080074const char kInvalidCandidates[] = "Description contains invalid candidates.";
75const char kInvalidSdp[] = "Invalid session description.";
76const char kMlineMismatchInAnswer[] =
77 "The order of m-lines in answer doesn't match order in offer. Rejecting "
78 "answer.";
79const char kMlineMismatchInSubsequentOffer[] =
80 "The order of m-lines in subsequent offer doesn't match order from "
81 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080082const char kSdpWithoutDtlsFingerprint[] =
83 "Called with SDP without DTLS fingerprint.";
84const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
85const char kSdpWithoutIceUfragPwd[] =
86 "Called with SDP without ice-ufrag and ice-pwd.";
87const char kSessionError[] = "Session error code: ";
88const char kSessionErrorDesc[] = "Session error description: ";
89const char kDtlsSrtpSetupFailureRtp[] =
90 "Couldn't set up DTLS-SRTP on RTP channel.";
91const char kDtlsSrtpSetupFailureRtcp[] =
92 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 15:03:05 +0200114 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115
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)
Yves Gerey665174f2018-06-19 15:03:05 +0200132 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135};
136
deadbeefab9b2d12015-10-14 11:33:11 -0700137// Check if we can send |new_stream| on a PeerConnection.
138bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
139 webrtc::MediaStreamInterface* new_stream) {
140 if (!new_stream || !current_streams) {
141 return false;
142 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700143 if (current_streams->find(new_stream->id()) != nullptr) {
144 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100145 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700146 return false;
147 }
148 return true;
149}
150
deadbeef5e97fb52015-10-15 12:49:08 -0700151// If the direction is "recvonly" or "inactive", treat the description
152// as containing no streams.
153// See: https://code.google.com/p/webrtc/issues/detail?id=5054
154std::vector<cricket::StreamParams> GetActiveStreams(
155 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800156 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700157 ? desc->streams()
158 : std::vector<cricket::StreamParams>();
159}
160
deadbeefab9b2d12015-10-14 11:33:11 -0700161bool IsValidOfferToReceiveMedia(int value) {
162 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
163 return (value >= Options::kUndefined) &&
164 (value <= Options::kMaxOfferToReceiveMedia);
165}
166
zhihuang1c378ed2017-08-17 14:10:50 -0700167// Add options to |[audio/video]_media_description_options| from |senders|.
168void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700169 const std::vector<rtc::scoped_refptr<
170 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700171 cricket::MediaDescriptionOptions* audio_media_description_options,
172 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700173 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700174 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
175 if (audio_media_description_options) {
176 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700177 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700178 }
179 } else {
180 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
181 if (video_media_description_options) {
182 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700186 }
zhihuang1c378ed2017-08-17 14:10:50 -0700187}
olka3c747662017-08-17 06:50:32 -0700188
zhihuang1c378ed2017-08-17 14:10:50 -0700189// Add options to |session_options| from |rtp_data_channels|.
190void AddRtpDataChannelOptions(
191 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
192 rtp_data_channels,
193 cricket::MediaDescriptionOptions* data_media_description_options) {
194 if (!data_media_description_options) {
195 return;
196 }
deadbeefab9b2d12015-10-14 11:33:11 -0700197 // Check for data channels.
198 for (const auto& kv : rtp_data_channels) {
199 const DataChannel* channel = kv.second;
200 if (channel->state() == DataChannel::kConnecting ||
201 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700202 // Legacy RTP data channels are signaled with the track/stream ID set to
203 // the data channel's label.
204 data_media_description_options->AddRtpDataChannel(channel->label(),
205 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700206 }
207 }
208}
209
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700210uint32_t ConvertIceTransportTypeToCandidateFilter(
211 PeerConnectionInterface::IceTransportsType type) {
212 switch (type) {
213 case PeerConnectionInterface::kNone:
214 return cricket::CF_NONE;
215 case PeerConnectionInterface::kRelay:
216 return cricket::CF_RELAY;
217 case PeerConnectionInterface::kNoHost:
218 return (cricket::CF_ALL & ~cricket::CF_HOST);
219 case PeerConnectionInterface::kAll:
220 return cricket::CF_ALL;
221 default:
nissec80e7412017-01-11 05:56:46 -0800222 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700223 }
224 return cricket::CF_NONE;
225}
226
deadbeef293e9262017-01-11 12:28:30 -0800227// Helper to set an error and return from a method.
228bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
229 if (error) {
230 error->set_type(type);
231 }
232 return type == webrtc::RTCErrorType::NONE;
233}
234
Steve Anton038834f2017-07-14 15:59:59 -0700235bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
236 if (error_out) {
237 *error_out = std::move(error);
238 }
239 return error.ok();
240}
241
Steve Antonba818672017-11-06 10:21:57 -0800242std::string GetSignalingStateString(
243 PeerConnectionInterface::SignalingState state) {
244 switch (state) {
245 case PeerConnectionInterface::kStable:
246 return "kStable";
247 case PeerConnectionInterface::kHaveLocalOffer:
248 return "kHaveLocalOffer";
249 case PeerConnectionInterface::kHaveLocalPrAnswer:
250 return "kHavePrAnswer";
251 case PeerConnectionInterface::kHaveRemoteOffer:
252 return "kHaveRemoteOffer";
253 case PeerConnectionInterface::kHaveRemotePrAnswer:
254 return "kHaveRemotePrAnswer";
255 case PeerConnectionInterface::kClosed:
256 return "kClosed";
257 }
258 RTC_NOTREACHED();
259 return "";
260}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261
Steve Anton75737c02017-11-06 10:37:17 -0800262IceCandidatePairType GetIceCandidatePairCounter(
263 const cricket::Candidate& local,
264 const cricket::Candidate& remote) {
265 const auto& l = local.type();
266 const auto& r = remote.type();
267 const auto& host = LOCAL_PORT_TYPE;
268 const auto& srflx = STUN_PORT_TYPE;
269 const auto& relay = RELAY_PORT_TYPE;
270 const auto& prflx = PRFLX_PORT_TYPE;
271 if (l == host && r == host) {
272 bool local_private = IPIsPrivate(local.address().ipaddr());
273 bool remote_private = IPIsPrivate(remote.address().ipaddr());
274 if (local_private) {
275 if (remote_private) {
276 return kIceCandidatePairHostPrivateHostPrivate;
277 } else {
278 return kIceCandidatePairHostPrivateHostPublic;
279 }
280 } else {
281 if (remote_private) {
282 return kIceCandidatePairHostPublicHostPrivate;
283 } else {
284 return kIceCandidatePairHostPublicHostPublic;
285 }
286 }
287 }
288 if (l == host && r == srflx)
289 return kIceCandidatePairHostSrflx;
290 if (l == host && r == relay)
291 return kIceCandidatePairHostRelay;
292 if (l == host && r == prflx)
293 return kIceCandidatePairHostPrflx;
294 if (l == srflx && r == host)
295 return kIceCandidatePairSrflxHost;
296 if (l == srflx && r == srflx)
297 return kIceCandidatePairSrflxSrflx;
298 if (l == srflx && r == relay)
299 return kIceCandidatePairSrflxRelay;
300 if (l == srflx && r == prflx)
301 return kIceCandidatePairSrflxPrflx;
302 if (l == relay && r == host)
303 return kIceCandidatePairRelayHost;
304 if (l == relay && r == srflx)
305 return kIceCandidatePairRelaySrflx;
306 if (l == relay && r == relay)
307 return kIceCandidatePairRelayRelay;
308 if (l == relay && r == prflx)
309 return kIceCandidatePairRelayPrflx;
310 if (l == prflx && r == host)
311 return kIceCandidatePairPrflxHost;
312 if (l == prflx && r == srflx)
313 return kIceCandidatePairPrflxSrflx;
314 if (l == prflx && r == relay)
315 return kIceCandidatePairPrflxRelay;
316 return kIceCandidatePairMax;
317}
318
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800319// Logic to decide if an m= section can be recycled. This means that the new
320// m= section is not rejected, but the old local or remote m= section is
321// rejected. |old_content_one| and |old_content_two| refer to the m= section
322// of the old remote and old local descriptions in no particular order.
323// We need to check both the old local and remote because either
324// could be the most current from the latest negotation.
325bool IsMediaSectionBeingRecycled(SdpType type,
326 const ContentInfo& content,
327 const ContentInfo* old_content_one,
328 const ContentInfo* old_content_two) {
329 return type == SdpType::kOffer && !content.rejected &&
330 ((old_content_one && old_content_one->rejected) ||
331 (old_content_two && old_content_two->rejected));
332}
333
Steve Anton75737c02017-11-06 10:37:17 -0800334// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800335// |current_desc|. The number of m= sections in |new_desc| should be no
336// less than |current_desc|. In the case of checking an answer's
337// |new_desc|, the |current_desc| is the last offer that was set as the
338// local or remote. In the case of checking an offer's |new_desc| we
339// check against the local and remote descriptions stored from the last
340// negotiation, because either of these could be the most up to date for
341// possible rejected m sections. These are the |current_desc| and
342// |secondary_current_desc|.
343bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
344 const SessionDescription* secondary_current_desc,
345 const SessionDescription& new_desc,
346 const SdpType type) {
347 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800348 return false;
349 }
350
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800351 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
352 const cricket::ContentInfo* secondary_content_info = nullptr;
353 if (secondary_current_desc &&
354 i < secondary_current_desc->contents().size()) {
355 secondary_content_info = &secondary_current_desc->contents()[i];
356 }
357 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
358 &current_desc.contents()[i],
359 secondary_content_info)) {
360 // For new offer descriptions, if the media section can be recycled, it's
361 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800362 continue;
363 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800364 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800365 return false;
366 }
367 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368 new_desc.contents()[i].media_description();
369 const MediaContentDescription* current_desc_mdesc =
370 current_desc.contents()[i].media_description();
371 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 return false;
373 }
374 }
375 return true;
376}
377
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800378bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
379 const SessionDescription& desc2) {
380 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800381}
382
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100383void NoteKeyProtocolAndMedia(
384 KeyExchangeProtocolType protocol_type,
385 cricket::MediaType media_type,
386 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
387 if (!uma_observer)
388 return;
389 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
390 protocol_type,
391 webrtc::kEnumCounterKeyProtocolMax);
392 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
393 KeyExchangeProtocolMedia>
394 proto_media_counter_map = {
395 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
396 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
398 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
400 kEnumCounterKeyProtocolMediaTypeDtlsData},
401 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
402 kEnumCounterKeyProtocolMediaTypeSdesAudio},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
404 kEnumCounterKeyProtocolMediaTypeSdesVideo},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
406 kEnumCounterKeyProtocolMediaTypeSdesData}};
407
408 auto it = proto_media_counter_map.find({protocol_type, media_type});
409 if (it != proto_media_counter_map.end()) {
410 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
411 it->second,
412 kEnumCounterKeyProtocolMediaTypeMax);
413 }
414}
415
Steve Anton75737c02017-11-06 10:37:17 -0800416// Checks that each non-rejected content has SDES crypto keys or a DTLS
417// fingerprint, unless it's in a BUNDLE group, in which case only the
418// BUNDLE-tag section (first media section/description in the BUNDLE group)
419// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
420// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
421// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100422RTCError VerifyCrypto(const SessionDescription* desc,
423 bool dtls_enabled,
424 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800425 const cricket::ContentGroup* bundle =
426 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800427 for (const cricket::ContentInfo& content_info : desc->contents()) {
428 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800429 continue;
430 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100431 // Note what media is used with each crypto protocol, for all sections.
432 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
433 : webrtc::kEnumCounterKeyProtocolSdes,
434 content_info.media_description()->type(),
435 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800436 const std::string& mid = content_info.name;
437 if (bundle && bundle->HasContentName(mid) &&
438 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 // This isn't the first media section in the BUNDLE group, so it's not
440 // required to have crypto attributes, since only the crypto attributes
441 // from the first section actually get used.
442 continue;
443 }
444
445 // If the content isn't rejected or bundled into another m= section, crypto
446 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800447 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800448 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800449 if (!media || !tinfo) {
450 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800452 }
453 if (dtls_enabled) {
454 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 RTC_LOG(LS_WARNING)
456 << "Session description must have DTLS fingerprint if "
457 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800458 return RTCError(RTCErrorType::INVALID_PARAMETER,
459 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800460 }
461 } else {
462 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800464 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800465 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800466 }
467 }
468 }
Steve Anton8a006912017-12-04 15:25:56 -0800469 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800470}
471
472// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
473// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
474// media section/description in the BUNDLE group) needs a ufrag and pwd.
475bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 const std::string& mid = content_info.name;
483 if (bundle && bundle->HasContentName(mid) &&
484 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800485 // This isn't the first media section in the BUNDLE group, so it's not
486 // required to have ufrag/password, since only the ufrag/password from
487 // the first section actually get used.
488 continue;
489 }
490
491 // If the content isn't rejected or bundled into another m= section,
492 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800493 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800494 if (!tinfo) {
495 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100496 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800497 return false;
498 }
499 if (tinfo->description.ice_ufrag.empty() ||
500 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100501 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800502 return false;
503 }
504 }
505 return true;
506}
507
508bool GetTrackIdBySsrc(const SessionDescription* session_description,
509 uint32_t ssrc,
510 std::string* track_id) {
511 RTC_DCHECK(track_id != NULL);
512
Steve Antonb1c1de12017-12-21 15:14:30 -0800513 const cricket::AudioContentDescription* audio_desc =
514 cricket::GetFirstAudioContentDescription(session_description);
515 if (audio_desc) {
516 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800517 if (found) {
518 *track_id = found->id;
519 return true;
520 }
521 }
522
Steve Antonb1c1de12017-12-21 15:14:30 -0800523 const cricket::VideoContentDescription* video_desc =
524 cricket::GetFirstVideoContentDescription(session_description);
525 if (video_desc) {
526 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800527 if (found) {
528 *track_id = found->id;
529 return true;
530 }
531 }
532 return false;
533}
534
535// Get the SCTP port out of a SessionDescription.
536// Return -1 if not found.
537int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800538 const cricket::DataContentDescription* data_desc =
539 GetFirstDataContentDescription(session_description);
540 RTC_DCHECK(data_desc);
541 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800542 return -1;
543 }
Steve Anton75737c02017-11-06 10:37:17 -0800544 std::string value;
545 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
546 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800547 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800548 if (!codec.Matches(match_pattern)) {
549 continue;
550 }
551 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
552 return rtc::FromString<int>(value);
553 }
554 }
555 return -1;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
559bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
560 const SessionDescriptionInterface* new_desc,
561 const std::string& content_name) {
562 if (!old_desc) {
563 return false;
564 }
565 const SessionDescription* new_sd = new_desc->description();
566 const SessionDescription* old_sd = old_desc->description();
567 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
568 if (!cinfo || cinfo->rejected) {
569 return false;
570 }
571 // If the content isn't rejected, check if ufrag and password has changed.
572 const cricket::TransportDescription* new_transport_desc =
573 new_sd->GetTransportDescriptionByName(content_name);
574 const cricket::TransportDescription* old_transport_desc =
575 old_sd->GetTransportDescriptionByName(content_name);
576 if (!new_transport_desc || !old_transport_desc) {
577 // No transport description exists. This is not an ICE restart.
578 return false;
579 }
580 if (cricket::IceCredentialsChanged(
581 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
582 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-16 17:08:42 -0800590// Generates a string error message for SetLocalDescription/SetRemoteDescription
591// from an RTCError.
592std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
593 SdpType type,
594 const RTCError& error) {
595 std::ostringstream oss;
596 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
597 << " " << SdpTypeToString(type) << " sdp: " << error.message();
598 return oss.str();
599}
600
Seth Hampson5b4f0752018-04-02 16:31:36 -0700601std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
602 std::string output = "streams=[";
603 const char* separator = "";
604 for (const auto& stream_id : stream_ids) {
605 output.append(separator).append(stream_id);
606 separator = ", ";
607 }
608 output.append("]");
609 return output;
610}
611
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 }
618 return rtc_configuration_parameter;
619}
620
Steve Anton75737c02017-11-06 10:37:17 -0800621} // namespace
622
Henrik Boström31638672017-11-23 17:48:32 +0100623// Upon completion, posts a task to execute the callback of the
624// SetSessionDescriptionObserver asynchronously on the same thread. At this
625// point, the state of the peer connection might no longer reflect the effects
626// of the SetRemoteDescription operation, as the peer connection could have been
627// modified during the post.
628// TODO(hbos): Remove this class once we remove the version of
629// PeerConnectionInterface::SetRemoteDescription() that takes a
630// SetSessionDescriptionObserver as an argument.
631class PeerConnection::SetRemoteDescriptionObserverAdapter
632 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
633 public:
634 SetRemoteDescriptionObserverAdapter(
635 rtc::scoped_refptr<PeerConnection> pc,
636 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
637 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
638
639 // SetRemoteDescriptionObserverInterface implementation.
640 void OnSetRemoteDescriptionComplete(RTCError error) override {
641 if (error.ok())
642 pc_->PostSetSessionDescriptionSuccess(wrapper_);
643 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100644 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100645 }
646
647 private:
648 rtc::scoped_refptr<PeerConnection> pc_;
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
650};
651
deadbeef293e9262017-01-11 12:28:30 -0800652bool PeerConnectionInterface::RTCConfiguration::operator==(
653 const PeerConnectionInterface::RTCConfiguration& o) const {
654 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700655 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800656 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000657 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800659 BundlePolicy bundle_policy;
660 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700661 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
662 int ice_candidate_pool_size;
663 bool disable_ipv6;
664 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700665 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100666 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700667 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200668 absl::optional<int> screencast_min_bitrate;
669 absl::optional<bool> combined_audio_video_bwe;
670 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800671 TcpCandidatePolicy tcp_candidate_policy;
672 CandidateNetworkPolicy candidate_network_policy;
673 int audio_jitter_buffer_max_packets;
674 bool audio_jitter_buffer_fast_accelerate;
675 int ice_connection_receiving_timeout;
676 int ice_backup_candidate_pair_ping_interval;
677 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800678 bool prioritize_most_likely_ice_candidate_pairs;
679 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800680 bool prune_turn_ports;
681 bool presume_writable_when_fully_relayed;
682 bool enable_ice_renomination;
683 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200684 absl::optional<int> ice_check_interval_strong_connectivity;
685 absl::optional<int> ice_check_interval_weak_connectivity;
686 absl::optional<int> ice_check_min_interval;
687 absl::optional<int> ice_unwritable_timeout;
688 absl::optional<int> ice_unwritable_min_checks;
689 absl::optional<int> stun_candidate_keepalive_interval;
690 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200691 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800692 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200693 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700694 bool active_reset_srtp_params;
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 &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700741 network_preference == o.network_preference &&
742 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800743}
744
745bool PeerConnectionInterface::RTCConfiguration::operator!=(
746 const PeerConnectionInterface::RTCConfiguration& o) const {
747 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800748}
749
zhihuang8f65cdf2016-05-06 18:40:30 -0700750// Generate a RTCP CNAME when a PeerConnection is created.
751std::string GenerateRtcpCname() {
752 std::string cname;
753 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100754 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800755 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700756 }
757 return cname;
758}
759
zhihuang1c378ed2017-08-17 14:10:50 -0700760bool ValidateOfferAnswerOptions(
761 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
762 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
763 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700764}
765
zhihuang1c378ed2017-08-17 14:10:50 -0700766// From |rtc_options|, fill parts of |session_options| shared by all generated
767// m= sections (in other words, nothing that involves a map/array).
768void ExtractSharedMediaSessionOptions(
769 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
770 cricket::MediaSessionOptions* session_options) {
771 session_options->vad_enabled = rtc_options.voice_activity_detection;
772 session_options->bundle_enabled = rtc_options.use_rtp_mux;
773}
zhihuanga77e6bb2017-08-14 18:17:48 -0700774
zhihuang1c378ed2017-08-17 14:10:50 -0700775bool ConvertConstraintsToOfferAnswerOptions(
776 const MediaConstraintsInterface* constraints,
777 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700778 if (!constraints) {
779 return true;
780 }
zhihuang1c378ed2017-08-17 14:10:50 -0700781
782 bool value = false;
783 size_t mandatory_constraints_satisfied = 0;
784
785 if (FindConstraint(constraints,
786 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
787 &mandatory_constraints_satisfied)) {
788 offer_answer_options->offer_to_receive_audio =
789 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
790 kOfferToReceiveMediaTrue
791 : 0;
792 }
793
794 if (FindConstraint(constraints,
795 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
796 &mandatory_constraints_satisfied)) {
797 offer_answer_options->offer_to_receive_video =
798 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
799 kOfferToReceiveMediaTrue
800 : 0;
801 }
802 if (FindConstraint(constraints,
803 MediaConstraintsInterface::kVoiceActivityDetection, &value,
804 &mandatory_constraints_satisfied)) {
805 offer_answer_options->voice_activity_detection = value;
806 }
807 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
808 &mandatory_constraints_satisfied)) {
809 offer_answer_options->use_rtp_mux = value;
810 }
811 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
812 &value, &mandatory_constraints_satisfied)) {
813 offer_answer_options->ice_restart = value;
814 }
815
deadbeefab9b2d12015-10-14 11:33:11 -0700816 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
817}
818
zhihuang38ede132017-06-15 12:52:32 -0700819PeerConnection::PeerConnection(PeerConnectionFactory* factory,
820 std::unique_ptr<RtcEventLog> event_log,
821 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700823 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700824 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700825 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700826 remote_streams_(StreamCollection::Create()),
827 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828
829PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800831 RTC_DCHECK_RUN_ON(signaling_thread());
832
Steve Anton8af21862017-12-15 11:20:13 -0800833 // Need to stop transceivers before destroying the stats collector because
834 // AudioRtpSender has a reference to the StatsCollector it will update when
835 // stopping.
836 for (auto transceiver : transceivers_) {
837 transceiver->Stop();
838 }
Steve Anton4171afb2017-11-20 10:20:22 -0800839
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700840 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800841 if (stats_collector_) {
842 stats_collector_->WaitForPendingRequest();
843 stats_collector_ = nullptr;
844 }
Steve Anton75737c02017-11-06 10:37:17 -0800845
Steve Anton8af21862017-12-15 11:20:13 -0800846 // Don't destroy BaseChannels until after stats has been cleaned up so that
847 // the last stats request can still read from the channels.
848 DestroyAllChannels();
849
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800851
852 webrtc_session_desc_factory_.reset();
853 sctp_invoker_.reset();
854 sctp_factory_.reset();
855 transport_controller_.reset();
856
deadbeef91dd5672016-05-18 16:55:30 -0700857 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700858 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700859 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700860 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700861 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700862 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800863 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700864 event_log_.reset();
865 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866}
867
Steve Anton8af21862017-12-15 11:20:13 -0800868void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800869 // Destroy video channels first since they may have a pointer to a voice
870 // channel.
871 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800872 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800873 DestroyTransceiverChannel(transceiver);
874 }
875 }
876 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800877 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800878 DestroyTransceiverChannel(transceiver);
879 }
880 }
881 DestroyDataChannel();
882}
883
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000885 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700886 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100887 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700888
889 RTCError config_error = ValidateConfiguration(configuration);
890 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100891 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700892 return false;
893 }
894
Benjamin Wrightcab58882018-05-02 15:12:47 -0700895 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100896 RTC_LOG(LS_ERROR)
897 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100898 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800899 return false;
900 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200901
Benjamin Wrightcab58882018-05-02 15:12:47 -0700902 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800903 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100905 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800906 return false;
907 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700908
Benjamin Wrightcab58882018-05-02 15:12:47 -0700909 observer_ = dependencies.observer;
910 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700911 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800912
deadbeef91dd5672016-05-18 16:55:30 -0700913 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700914 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700915 if (!network_thread()->Invoke<bool>(
916 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
917 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 return false;
919 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920
Zhi Huange830e682018-03-30 10:48:35 -0700921 const PeerConnectionFactoryInterface::Options& options = factory_->options();
922
Steve Anton75737c02017-11-06 10:37:17 -0800923 // RFC 3264: The numeric value of the session id and version in the
924 // o line MUST be representable with a "64 bit signed integer".
925 // Due to this constraint session id |session_id_| is max limited to
926 // LLONG_MAX.
927 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700928 JsepTransportController::Config config;
929 config.redetermine_role_on_ice_restart =
930 configuration.redetermine_role_on_ice_restart;
931 config.ssl_max_version = factory_->options().ssl_max_version;
932 config.disable_encryption = options.disable_encryption;
933 config.bundle_policy = configuration.bundle_policy;
934 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
935 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700936 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700937 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700938#if defined(ENABLE_EXTERNAL_AUTH)
939 config.enable_external_auth = true;
940#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700941 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700942 transport_controller_.reset(new JsepTransportController(
943 signaling_thread(), network_thread(), port_allocator_.get(), config));
944 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800945 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700946 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800947 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700948 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800949 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700950 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800951 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
952 transport_controller_->SignalDtlsHandshakeError.connect(
953 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
954
955 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700956
deadbeefab9b2d12015-10-14 11:33:11 -0700957 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700958 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959
Steve Antonba818672017-11-06 10:21:57 -0800960 configuration_ = configuration;
961
Steve Anton75737c02017-11-06 10:37:17 -0800962 // Obtain a certificate from RTCConfiguration if any were provided (optional).
963 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
964 if (!configuration.certificates.empty()) {
965 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
966 // just picking the first one. The decision should be made based on the DTLS
967 // handshake. The DTLS negotiations need to know about all certificates.
968 certificate = configuration.certificates[0];
969 }
970
Steve Antond25da372017-11-06 14:50:29 -0800971 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800972
973 if (options.disable_encryption) {
974 dtls_enabled_ = false;
975 } else {
976 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700977 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800978 // |configuration| can override the default |dtls_enabled_| value.
979 if (configuration.enable_dtls_srtp) {
980 dtls_enabled_ = *(configuration.enable_dtls_srtp);
981 }
982 }
983
984 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
985 // It takes precendence over the disable_sctp_data_channels
986 // PeerConnectionFactoryInterface::Options.
987 if (configuration.enable_rtp_data_channel) {
988 data_channel_type_ = cricket::DCT_RTP;
989 } else {
990 // DTLS has to be enabled to use SCTP.
991 if (!options.disable_sctp_data_channels && dtls_enabled_) {
992 data_channel_type_ = cricket::DCT_SCTP;
993 }
994 }
995
996 video_options_.screencast_min_bitrate_kbps =
997 configuration.screencast_min_bitrate;
998 audio_options_.combined_audio_video_bwe =
999 configuration.combined_audio_video_bwe;
1000
1001 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001002 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001003
1004 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001005 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001006
1007 // Whether the certificate generator/certificate is null or not determines
1008 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1009 // the right instructions by clearing the variables if needed.
1010 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001011 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001012 certificate = nullptr;
1013 } else if (certificate) {
1014 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001015 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001016 }
1017
1018 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1019 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001020 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001021 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1022 this, &PeerConnection::OnCertificateReady);
1023
1024 if (options.disable_encryption) {
1025 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1026 }
1027
1028 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1029 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030
Steve Anton4171afb2017-11-20 10:20:22 -08001031 // Add default audio/video transceivers for Plan B SDP.
1032 if (!IsUnifiedPlan()) {
1033 transceivers_.push_back(
1034 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1035 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1036 transceivers_.push_back(
1037 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1038 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1039 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001040 return true;
1041}
1042
Steve Anton038834f2017-07-14 15:59:59 -07001043RTCError PeerConnection::ValidateConfiguration(
1044 const RTCConfiguration& config) const {
1045 if (config.ice_regather_interval_range &&
1046 config.continual_gathering_policy == GATHER_ONCE) {
1047 return RTCError(RTCErrorType::INVALID_PARAMETER,
1048 "ice_regather_interval_range specified but continual "
1049 "gathering policy is GATHER_ONCE");
1050 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001051 auto result =
1052 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1053 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001054}
1055
Yves Gerey665174f2018-06-19 15:03:05 +02001056rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001057 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1058 "Plan SdpSemantics. Please use GetSenders "
1059 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001060 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061}
1062
Yves Gerey665174f2018-06-19 15:03:05 +02001063rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::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()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001420 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001421 } else {
1422 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1423 RTC_DCHECK(!track ||
1424 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1425 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1426 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001427 new VideoRtpSender(worker_thread(),
1428 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001429 stream_ids));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001430 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001432 return sender;
1433}
1434
1435rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1436PeerConnection::CreateReceiver(cricket::MediaType media_type,
1437 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001438 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1439 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001440 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001441 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001442 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001443 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001444 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001445 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001446 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001447 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1448 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001449 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001450 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001451 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001452 return receiver;
1453}
1454
1455rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1456PeerConnection::CreateAndAddTransceiver(
1457 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1458 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1459 receiver) {
1460 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1461 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001462 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001463 transceiver->internal()->SignalNegotiationNeeded.connect(
1464 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001465 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001466}
1467
Steve Anton52d86772018-02-20 15:48:12 -08001468void PeerConnection::OnNegotiationNeeded() {
1469 RTC_DCHECK_RUN_ON(signaling_thread());
1470 RTC_DCHECK(!IsClosed());
1471 observer_->OnRenegotiationNeeded();
1472}
1473
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001474rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001475 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001476 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001477 if (IsClosed()) {
1478 return nullptr;
1479 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001480 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001481 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001482 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 }
Steve Anton4171afb2017-11-20 10:20:22 -08001484 auto track_sender = FindSenderForTrack(track);
1485 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001486 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001487 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001488 }
1489
Steve Anton4171afb2017-11-20 10:20:22 -08001490 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491}
1492
deadbeeffac06552015-11-25 11:26:01 -08001493rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001494 const std::string& kind,
1495 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001496 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1497 "Plan SdpSemantics. Please use AddTransceiver "
1498 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001499 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001500 if (IsClosed()) {
1501 return nullptr;
1502 }
Steve Anton4171afb2017-11-20 10:20:22 -08001503
Seth Hampson5b4f0752018-04-02 16:31:36 -07001504 // Internally we need to have one stream with Plan B semantics, so we
1505 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001506 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001507 if (stream_id.empty()) {
1508 stream_ids.push_back(rtc::CreateRandomUuid());
1509 RTC_LOG(LS_INFO)
1510 << "No stream_id specified for sender. Generated stream ID: "
1511 << stream_ids[0];
1512 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001513 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001514 }
1515
Steve Anton4171afb2017-11-20 10:20:22 -08001516 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001517 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001518 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001519 auto* audio_sender =
1520 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001521 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001522 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001523 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001524 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001525 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001526 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001527 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001528 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001529 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001530 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001531 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001532 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001533 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001534 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001535 }
Steve Anton4171afb2017-11-20 10:20:22 -08001536
deadbeefe1f9d832016-01-14 15:35:42 -08001537 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001538}
1539
deadbeef70ab1a12015-09-28 16:53:55 -07001540std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1541 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001542 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001543 for (auto sender : GetSendersInternal()) {
1544 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001545 }
1546 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001547}
1548
Steve Anton4171afb2017-11-20 10:20:22 -08001549std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1550PeerConnection::GetSendersInternal() const {
1551 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1552 all_senders;
1553 for (auto transceiver : transceivers_) {
1554 auto senders = transceiver->internal()->senders();
1555 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1556 }
1557 return all_senders;
1558}
1559
deadbeef70ab1a12015-09-28 16:53:55 -07001560std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1561PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001562 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001563 for (const auto& receiver : GetReceiversInternal()) {
1564 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001565 }
1566 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001567}
1568
Steve Anton4171afb2017-11-20 10:20:22 -08001569std::vector<
1570 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1571PeerConnection::GetReceiversInternal() const {
1572 std::vector<
1573 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1574 all_receivers;
1575 for (auto transceiver : transceivers_) {
1576 auto receivers = transceiver->internal()->receivers();
1577 all_receivers.insert(all_receivers.end(), receivers.begin(),
1578 receivers.end());
1579 }
1580 return all_receivers;
1581}
1582
Steve Anton9158ef62017-11-27 13:01:52 -08001583std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1584PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001585 RTC_CHECK(IsUnifiedPlan())
1586 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001587 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1588 for (auto transceiver : transceivers_) {
1589 all_transceivers.push_back(transceiver);
1590 }
1591 return all_transceivers;
1592}
1593
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001594bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001595 MediaStreamTrackInterface* track,
1596 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001597 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001598 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001599 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001600 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001601 return false;
1602 }
1603
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001604 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001605 // The StatsCollector is used to tell if a track is valid because it may
1606 // remember tracks that the PeerConnection previously removed.
1607 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001608 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1609 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001610 return false;
1611 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001612 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001613 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001614 return true;
1615}
1616
hbos74e1a4f2016-09-15 23:33:01 -07001617void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001618 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001619 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001620 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001621 stats_collector_->GetStatsReport(callback);
1622}
1623
Henrik Boström1df1bf82018-03-20 13:24:20 +01001624void PeerConnection::GetStats(
1625 rtc::scoped_refptr<RtpSenderInterface> selector,
1626 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1627 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1628 RTC_DCHECK(callback);
1629 RTC_DCHECK(stats_collector_);
1630 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1631 if (selector) {
1632 for (const auto& proxy_transceiver : transceivers_) {
1633 for (const auto& proxy_sender :
1634 proxy_transceiver->internal()->senders()) {
1635 if (proxy_sender == selector) {
1636 internal_sender = proxy_sender->internal();
1637 break;
1638 }
1639 }
1640 if (internal_sender)
1641 break;
1642 }
1643 }
1644 // If there is no |internal_sender| then |selector| is either null or does not
1645 // belong to the PeerConnection (in Plan B, senders can be removed from the
1646 // PeerConnection). This means that "all the stats objects representing the
1647 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1648 // produces an empty stats report.
1649 stats_collector_->GetStatsReport(internal_sender, callback);
1650}
1651
1652void PeerConnection::GetStats(
1653 rtc::scoped_refptr<RtpReceiverInterface> selector,
1654 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1655 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1656 RTC_DCHECK(callback);
1657 RTC_DCHECK(stats_collector_);
1658 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1659 if (selector) {
1660 for (const auto& proxy_transceiver : transceivers_) {
1661 for (const auto& proxy_receiver :
1662 proxy_transceiver->internal()->receivers()) {
1663 if (proxy_receiver == selector) {
1664 internal_receiver = proxy_receiver->internal();
1665 break;
1666 }
1667 }
1668 if (internal_receiver)
1669 break;
1670 }
1671 }
1672 // If there is no |internal_receiver| then |selector| is either null or does
1673 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1674 // the PeerConnection). This means that "all the stats objects representing
1675 // the selector" is an empty set. Invoking GetStatsReport() with a null
1676 // selector produces an empty stats report.
1677 stats_collector_->GetStatsReport(internal_receiver, callback);
1678}
1679
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001680PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1681 return signaling_state_;
1682}
1683
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684PeerConnectionInterface::IceConnectionState
1685PeerConnection::ice_connection_state() {
1686 return ice_connection_state_;
1687}
1688
1689PeerConnectionInterface::IceGatheringState
1690PeerConnection::ice_gathering_state() {
1691 return ice_gathering_state_;
1692}
1693
Yves Gerey665174f2018-06-19 15:03:05 +02001694rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695 const std::string& label,
1696 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001697 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001698
deadbeefab9b2d12015-10-14 11:33:11 -07001699 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001700
kwibergd1fe2812016-04-27 06:47:29 -07001701 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001702 if (config) {
1703 internal_config.reset(new InternalDataChannelInit(*config));
1704 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001705 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001706 InternalCreateDataChannel(label, internal_config.get()));
1707 if (!channel.get()) {
1708 return nullptr;
1709 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001710
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001711 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1712 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001713 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001714 observer_->OnRenegotiationNeeded();
1715 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001716 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001717 return DataChannelProxy::Create(signaling_thread(), channel.get());
1718}
1719
1720void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1721 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001722 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001723
zhihuang1c378ed2017-08-17 14:10:50 -07001724 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1725 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1726 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1727 // compares the mandatory fields parsed with the mandatory fields added in the
1728 // |constraints| and some downstream applications might create offers with
1729 // mandatory fields which would not be parsed in the helper method. For
1730 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1731 // |constraints| as a mandatory field but it is not parsed.
1732 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001733
zhihuang1c378ed2017-08-17 14:10:50 -07001734 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001735}
1736
1737void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1738 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001739 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001740
nisse7ce109a2017-01-31 00:57:56 -08001741 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001742 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001743 return;
1744 }
deadbeefab9b2d12015-10-14 11:33:11 -07001745
Steve Anton8d3444d2017-10-20 15:30:51 -07001746 if (IsClosed()) {
1747 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001748 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001749 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001750 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001751 return;
1752 }
1753
zhihuang1c378ed2017-08-17 14:10:50 -07001754 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001755 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001756 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001757 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001758 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001759 return;
1760 }
1761
Steve Anton22da89f2018-01-25 13:58:07 -08001762 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1763 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1764 if (IsUnifiedPlan()) {
1765 RTCError error = HandleLegacyOfferOptions(options);
1766 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001767 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001768 return;
1769 }
1770 }
1771
zhihuang1c378ed2017-08-17 14:10:50 -07001772 cricket::MediaSessionOptions session_options;
1773 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001774 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775}
1776
Steve Anton22da89f2018-01-25 13:58:07 -08001777RTCError PeerConnection::HandleLegacyOfferOptions(
1778 const RTCOfferAnswerOptions& options) {
1779 RTC_DCHECK(IsUnifiedPlan());
1780
1781 if (options.offer_to_receive_audio == 0) {
1782 RemoveRecvDirectionFromReceivingTransceiversOfType(
1783 cricket::MEDIA_TYPE_AUDIO);
1784 } else if (options.offer_to_receive_audio == 1) {
1785 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1786 } else if (options.offer_to_receive_audio > 1) {
1787 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1788 "offer_to_receive_audio > 1 is not supported.");
1789 }
1790
1791 if (options.offer_to_receive_video == 0) {
1792 RemoveRecvDirectionFromReceivingTransceiversOfType(
1793 cricket::MEDIA_TYPE_VIDEO);
1794 } else if (options.offer_to_receive_video == 1) {
1795 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1796 } else if (options.offer_to_receive_video > 1) {
1797 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1798 "offer_to_receive_video > 1 is not supported.");
1799 }
1800
1801 return RTCError::OK();
1802}
1803
1804void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1805 cricket::MediaType media_type) {
1806 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001807 RtpTransceiverDirection new_direction =
1808 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1809 if (new_direction != transceiver->direction()) {
1810 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1811 << " transceiver (MID="
1812 << transceiver->mid().value_or("<not set>") << ") from "
1813 << RtpTransceiverDirectionToString(
1814 transceiver->direction())
1815 << " to "
1816 << RtpTransceiverDirectionToString(new_direction)
1817 << " since CreateOffer specified offer_to_receive=0";
1818 transceiver->internal()->set_direction(new_direction);
1819 }
Steve Anton22da89f2018-01-25 13:58:07 -08001820 }
1821}
1822
1823void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1824 cricket::MediaType media_type) {
1825 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001826 RTC_LOG(LS_INFO)
1827 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1828 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001829 RtpTransceiverInit init;
1830 init.direction = RtpTransceiverDirection::kRecvOnly;
1831 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1832 }
1833}
1834
1835std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1836PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1837 std::vector<
1838 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1839 receiving_transceivers;
1840 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001841 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001842 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1843 receiving_transceivers.push_back(transceiver);
1844 }
1845 }
1846 return receiving_transceivers;
1847}
1848
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001849void PeerConnection::CreateAnswer(
1850 CreateSessionDescriptionObserver* observer,
1851 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001852 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001853
nisse7ce109a2017-01-31 00:57:56 -08001854 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001855 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001856 return;
1857 }
deadbeefab9b2d12015-10-14 11:33:11 -07001858
zhihuang1c378ed2017-08-17 14:10:50 -07001859 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1860 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1861 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001862 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001863 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001864 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001865 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001866 return;
1867 }
1868
Steve Anton8d3444d2017-10-20 15:30:51 -07001869 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001870}
1871
1872void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1873 const RTCOfferAnswerOptions& options) {
1874 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001875 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001876 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001877 return;
1878 }
1879
Steve Antondffead82018-02-06 10:31:29 -08001880 if (!(signaling_state_ == kHaveRemoteOffer ||
1881 signaling_state_ == kHaveLocalPrAnswer)) {
1882 std::string error =
1883 "PeerConnection cannot create an answer in a state other than "
1884 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001885 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001886 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001887 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001888 return;
1889 }
1890
Steve Antondffead82018-02-06 10:31:29 -08001891 // The remote description should be set if we're in the right state.
1892 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001893
Steve Anton22da89f2018-01-25 13:58:07 -08001894 if (IsUnifiedPlan()) {
1895 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1896 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1897 "supported with Unified Plan semantics. Use the "
1898 "RtpTransceiver API instead.";
1899 }
1900 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1901 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1902 "supported with Unified Plan semantics. Use the "
1903 "RtpTransceiver API instead.";
1904 }
1905 }
1906
htaa2a49d92016-03-04 02:51:39 -08001907 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001908 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001909
Steve Antond25da372017-11-06 14:50:29 -08001910 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001911}
1912
1913void PeerConnection::SetLocalDescription(
1914 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001915 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001916 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001917
Steve Anton80dd7b52018-02-16 17:08:42 -08001918 // The SetLocalDescription contract is that we take ownership of the session
1919 // description regardless of the outcome, so wrap it in a unique_ptr right
1920 // away. Ideally, SetLocalDescription's signature will be changed to take the
1921 // description as a unique_ptr argument to formalize this agreement.
1922 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1923
nisse7ce109a2017-01-31 00:57:56 -08001924 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001925 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001926 return;
1927 }
Steve Anton8a006912017-12-04 15:25:56 -08001928
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001929 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001930 PostSetSessionDescriptionFailure(
1931 observer,
1932 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 return;
1934 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001935
Steve Anton80dd7b52018-02-16 17:08:42 -08001936 // If a session error has occurred the PeerConnection is in a possibly
1937 // inconsistent state so fail right away.
1938 if (session_error() != SessionError::kNone) {
1939 std::string error_message = GetSessionErrorMsg();
1940 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001941 PostSetSessionDescriptionFailure(
1942 observer,
1943 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001944 return;
1945 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001946
Steve Anton80dd7b52018-02-16 17:08:42 -08001947 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1948 if (!error.ok()) {
1949 std::string error_message = GetSetDescriptionErrorMessage(
1950 cricket::CS_LOCAL, desc->GetType(), error);
1951 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001952 PostSetSessionDescriptionFailure(
1953 observer,
1954 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001955 return;
1956 }
1957
1958 // Grab the description type before moving ownership to ApplyLocalDescription,
1959 // which may destroy it before returning.
1960 const SdpType type = desc->GetType();
1961
1962 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001963 // |desc| may be destroyed at this point.
1964
1965 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001966 // If ApplyLocalDescription fails, the PeerConnection could be in an
1967 // inconsistent state, so act conservatively here and set the session error
1968 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1969 SetSessionError(SessionError::kContent, error.message());
1970 std::string error_message =
1971 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1972 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001973 PostSetSessionDescriptionFailure(
1974 observer,
1975 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001976 return;
1977 }
Steve Anton8a006912017-12-04 15:25:56 -08001978 RTC_DCHECK(local_description());
1979
1980 PostSetSessionDescriptionSuccess(observer);
1981
Steve Anton8a006912017-12-04 15:25:56 -08001982 // MaybeStartGathering needs to be called after posting
1983 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1984 // before signaling that SetLocalDescription completed.
1985 transport_controller_->MaybeStartGathering();
1986
Steve Antona3a92c22017-12-07 10:27:41 -08001987 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001988 // TODO(deadbeef): We already had to hop to the network thread for
1989 // MaybeStartGathering...
1990 network_thread()->Invoke<void>(
1991 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1992 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001993 // Make UMA notes about what was agreed to.
1994 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001995 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001996 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001997}
1998
1999RTCError PeerConnection::ApplyLocalDescription(
2000 std::unique_ptr<SessionDescriptionInterface> desc) {
2001 RTC_DCHECK_RUN_ON(signaling_thread());
2002 RTC_DCHECK(desc);
2003
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002004 // Update stats here so that we have the most recent stats for tracks and
2005 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002006 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002007
Steve Antondcc3c022017-12-22 16:02:54 -08002008 // Take a reference to the old local description since it's used below to
2009 // compare against the new local description. When setting the new local
2010 // description, grab ownership of the replaced session description in case it
2011 // is the same as |old_local_description|, to keep it alive for the duration
2012 // of the method.
2013 const SessionDescriptionInterface* old_local_description =
2014 local_description();
2015 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002016 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002017 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002018 replaced_local_description = pending_local_description_
2019 ? std::move(pending_local_description_)
2020 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002021 current_local_description_ = std::move(desc);
2022 pending_local_description_ = nullptr;
2023 current_remote_description_ = std::move(pending_remote_description_);
2024 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002025 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002026 pending_local_description_ = std::move(desc);
2027 }
2028 // The session description to apply now must be accessed by
2029 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002030 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002031
Zhi Huange830e682018-03-30 10:48:35 -07002032 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2033 if (!error.ok()) {
2034 return error;
2035 }
2036
Steve Antondcc3c022017-12-22 16:02:54 -08002037 if (IsUnifiedPlan()) {
2038 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002039 cricket::CS_LOCAL, *local_description(), old_local_description,
2040 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002041 if (!error.ok()) {
2042 return error;
2043 }
Steve Antondcc3c022017-12-22 16:02:54 -08002044 for (auto transceiver : transceivers_) {
2045 const ContentInfo* content =
2046 FindMediaSectionForTransceiver(transceiver, local_description());
2047 if (!content) {
2048 continue;
2049 }
2050 const MediaContentDescription* media_desc = content->media_description();
2051 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2052 transceiver->internal()->set_current_direction(media_desc->direction());
2053 }
2054 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002055 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2056 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002057 transceiver->Stop();
2058 }
2059 }
2060 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002061 // Media channels will be created only when offer is set. These may use new
2062 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002063 if (type == SdpType::kOffer) {
2064 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2065 // description is applied. Restore back to old description.
2066 RTCError error = CreateChannels(*local_description()->description());
2067 if (!error.ok()) {
2068 return error;
2069 }
2070 }
Steve Antondcc3c022017-12-22 16:02:54 -08002071 // Remove unused channels if MediaContentDescription is rejected.
2072 RemoveUnusedChannels(local_description()->description());
2073 }
Steve Anton8a006912017-12-04 15:25:56 -08002074
Zhi Huange830e682018-03-30 10:48:35 -07002075 error = UpdateSessionState(type, cricket::CS_LOCAL,
2076 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002077 if (!error.ok()) {
2078 return error;
2079 }
Steve Antondcc3c022017-12-22 16:02:54 -08002080
Steve Anton8a006912017-12-04 15:25:56 -08002081 if (remote_description()) {
2082 // Now that we have a local description, we can push down remote candidates.
2083 UseCandidatesInSessionDescription(remote_description());
2084 }
2085
2086 pending_ice_restarts_.clear();
2087 if (session_error() != SessionError::kNone) {
2088 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2089 }
2090
deadbeefab9b2d12015-10-14 11:33:11 -07002091 // If setting the description decided our SSL role, allocate any necessary
2092 // SCTP sids.
2093 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002094 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002095 AllocateSctpSids(role);
2096 }
2097
Steve Antond3679212018-01-17 17:41:02 -08002098 if (IsUnifiedPlan()) {
2099 for (auto transceiver : transceivers_) {
2100 const ContentInfo* content =
2101 FindMediaSectionForTransceiver(transceiver, local_description());
2102 if (!content) {
2103 continue;
2104 }
Steve Anton74255ff2018-01-24 18:32:57 -08002105 const auto& streams = content->media_description()->streams();
2106 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002107 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002108 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002109 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002110 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002111 } else {
2112 // 0 is a special value meaning "this sender has no associated send
2113 // stream". Need to call this so the sender won't attempt to configure
2114 // a no longer existing stream and run into DCHECKs in the lower
2115 // layers.
2116 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002117 }
2118 }
2119 } else {
2120 // Plan B semantics.
2121
Steve Antondcc3c022017-12-22 16:02:54 -08002122 // Update state and SSRC of local MediaStreams and DataChannels based on the
2123 // local session description.
2124 const cricket::ContentInfo* audio_content =
2125 GetFirstAudioContent(local_description()->description());
2126 if (audio_content) {
2127 if (audio_content->rejected) {
2128 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2129 } else {
2130 const cricket::AudioContentDescription* audio_desc =
2131 audio_content->media_description()->as_audio();
2132 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2133 }
deadbeeffaac4972015-11-12 15:33:07 -08002134 }
deadbeefab9b2d12015-10-14 11:33:11 -07002135
Steve Antondcc3c022017-12-22 16:02:54 -08002136 const cricket::ContentInfo* video_content =
2137 GetFirstVideoContent(local_description()->description());
2138 if (video_content) {
2139 if (video_content->rejected) {
2140 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2141 } else {
2142 const cricket::VideoContentDescription* video_desc =
2143 video_content->media_description()->as_video();
2144 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2145 }
deadbeeffaac4972015-11-12 15:33:07 -08002146 }
deadbeefab9b2d12015-10-14 11:33:11 -07002147 }
2148
2149 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002150 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002151 if (data_content) {
2152 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002153 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002154 if (rtc::starts_with(data_desc->protocol().data(),
2155 cricket::kMediaProtocolRtpPrefix)) {
2156 UpdateLocalRtpDataChannels(data_desc->streams());
2157 }
2158 }
2159
Steve Anton8a006912017-12-04 15:25:56 -08002160 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002161}
2162
2163void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002164 SetSessionDescriptionObserver* observer,
2165 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002166 SetRemoteDescription(
2167 std::unique_ptr<SessionDescriptionInterface>(desc),
2168 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2169 new SetRemoteDescriptionObserverAdapter(this, observer)));
2170}
2171
2172void PeerConnection::SetRemoteDescription(
2173 std::unique_ptr<SessionDescriptionInterface> desc,
2174 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002175 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002176
nisse7ce109a2017-01-31 00:57:56 -08002177 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002178 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002179 return;
2180 }
Steve Anton8a006912017-12-04 15:25:56 -08002181
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002182 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002183 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002184 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185 return;
2186 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002187
Steve Anton80dd7b52018-02-16 17:08:42 -08002188 // If a session error has occurred the PeerConnection is in a possibly
2189 // inconsistent state so fail right away.
2190 if (session_error() != SessionError::kNone) {
2191 std::string error_message = GetSessionErrorMsg();
2192 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2193 observer->OnSetRemoteDescriptionComplete(
2194 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2195 return;
2196 }
Steve Anton71439a62018-02-15 11:53:06 -08002197
Steve Antonba42e992018-04-09 14:10:01 -07002198 if (desc->GetType() == SdpType::kOffer) {
2199 // Report to UMA the format of the received offer.
2200 ReportSdpFormatReceived(*desc);
2201 }
2202
Steve Anton80dd7b52018-02-16 17:08:42 -08002203 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002204 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002205 std::string error_message = GetSetDescriptionErrorMessage(
2206 cricket::CS_REMOTE, desc->GetType(), error);
2207 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002208 observer->OnSetRemoteDescriptionComplete(
2209 RTCError(error.type(), std::move(error_message)));
2210 return;
2211 }
Steve Anton71439a62018-02-15 11:53:06 -08002212
Steve Anton80dd7b52018-02-16 17:08:42 -08002213 // Grab the description type before moving ownership to
2214 // ApplyRemoteDescription, which may destroy it before returning.
2215 const SdpType type = desc->GetType();
2216
2217 error = ApplyRemoteDescription(std::move(desc));
2218 // |desc| may be destroyed at this point.
2219
2220 if (!error.ok()) {
2221 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2222 // inconsistent state, so act conservatively here and set the session error
2223 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2224 SetSessionError(SessionError::kContent, error.message());
2225 std::string error_message =
2226 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2227 RTC_LOG(LS_ERROR) << error_message;
2228 observer->OnSetRemoteDescriptionComplete(
2229 RTCError(error.type(), std::move(error_message)));
2230 return;
2231 }
2232 RTC_DCHECK(remote_description());
2233
2234 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002235 // TODO(deadbeef): We already had to hop to the network thread for
2236 // MaybeStartGathering...
2237 network_thread()->Invoke<void>(
2238 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2239 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002240 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002241 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002242 }
2243
2244 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002245 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002246}
2247
2248RTCError PeerConnection::ApplyRemoteDescription(
2249 std::unique_ptr<SessionDescriptionInterface> desc) {
2250 RTC_DCHECK_RUN_ON(signaling_thread());
2251 RTC_DCHECK(desc);
2252
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253 // Update stats here so that we have the most recent stats for tracks and
2254 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002255 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002256
Steve Antondcc3c022017-12-22 16:02:54 -08002257 // Take a reference to the old remote description since it's used below to
2258 // compare against the new remote description. When setting the new remote
2259 // description, grab ownership of the replaced session description in case it
2260 // is the same as |old_remote_description|, to keep it alive for the duration
2261 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002262 const SessionDescriptionInterface* old_remote_description =
2263 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002264 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002265 SdpType type = desc->GetType();
2266 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002267 replaced_remote_description = pending_remote_description_
2268 ? std::move(pending_remote_description_)
2269 : std::move(current_remote_description_);
2270 current_remote_description_ = std::move(desc);
2271 pending_remote_description_ = nullptr;
2272 current_local_description_ = std::move(pending_local_description_);
2273 } else {
2274 replaced_remote_description = std::move(pending_remote_description_);
2275 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276 }
Steve Anton8a006912017-12-04 15:25:56 -08002277 // The session description to apply now must be accessed by
2278 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002279 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002280
Zhi Huange830e682018-03-30 10:48:35 -07002281 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2282 if (!error.ok()) {
2283 return error;
2284 }
Steve Anton8a006912017-12-04 15:25:56 -08002285 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002286 if (IsUnifiedPlan()) {
2287 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002288 cricket::CS_REMOTE, *remote_description(), local_description(),
2289 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002290 if (!error.ok()) {
2291 return error;
2292 }
Steve Antondcc3c022017-12-22 16:02:54 -08002293 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002294 // Media channels will be created only when offer is set. These may use new
2295 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002296 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002297 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002298 // description is applied. Restore back to old description.
2299 RTCError error = CreateChannels(*remote_description()->description());
2300 if (!error.ok()) {
2301 return error;
2302 }
2303 }
Steve Antondcc3c022017-12-22 16:02:54 -08002304 // Remove unused channels if MediaContentDescription is rejected.
2305 RemoveUnusedChannels(remote_description()->description());
2306 }
Steve Anton8a006912017-12-04 15:25:56 -08002307
Zhi Huange830e682018-03-30 10:48:35 -07002308 // NOTE: Candidates allocation will be initiated only when
2309 // SetLocalDescription is called.
2310 error = UpdateSessionState(type, cricket::CS_REMOTE,
2311 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002312 if (!error.ok()) {
2313 return error;
2314 }
2315
2316 if (local_description() &&
2317 !UseCandidatesInSessionDescription(remote_description())) {
2318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2319 }
2320
2321 if (old_remote_description) {
2322 for (const cricket::ContentInfo& content :
2323 old_remote_description->description()->contents()) {
2324 // Check if this new SessionDescription contains new ICE ufrag and
2325 // password that indicates the remote peer requests an ICE restart.
2326 // TODO(deadbeef): When we start storing both the current and pending
2327 // remote description, this should reset pending_ice_restarts and compare
2328 // against the current description.
2329 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2330 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002331 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002332 pending_ice_restarts_.insert(content.name);
2333 }
2334 } else {
2335 // We retain all received candidates only if ICE is not restarted.
2336 // When ICE is restarted, all previous candidates belong to an old
2337 // generation and should not be kept.
2338 // TODO(deadbeef): This goes against the W3C spec which says the remote
2339 // description should only contain candidates from the last set remote
2340 // description plus any candidates added since then. We should remove
2341 // this once we're sure it won't break anything.
2342 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2343 old_remote_description, content.name, mutable_remote_description());
2344 }
2345 }
2346 }
2347
2348 if (session_error() != SessionError::kNone) {
2349 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2350 }
2351
2352 // Set the the ICE connection state to connecting since the connection may
2353 // become writable with peer reflexive candidates before any remote candidate
2354 // is signaled.
2355 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2356 // is to have a new signal the indicates a change in checking state from the
2357 // transport and expose a new checking() member from transport that can be
2358 // read to determine the current checking state. The existing SignalConnecting
2359 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002360 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002361 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002362 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2363 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2364 }
2365
deadbeefab9b2d12015-10-14 11:33:11 -07002366 // If setting the description decided our SSL role, allocate any necessary
2367 // SCTP sids.
2368 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002369 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002370 AllocateSctpSids(role);
2371 }
2372
Steve Antondcc3c022017-12-22 16:02:54 -08002373 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002374 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002375 now_receiving_transceivers;
2376 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2377 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002378 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002379 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002380 for (auto transceiver : transceivers_) {
2381 const ContentInfo* content =
2382 FindMediaSectionForTransceiver(transceiver, remote_description());
2383 if (!content) {
2384 continue;
2385 }
2386 const MediaContentDescription* media_desc = content->media_description();
2387 RtpTransceiverDirection local_direction =
2388 RtpTransceiverDirectionReversed(media_desc->direction());
2389 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2390 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2391 // transceiver's current direction is neither sendrecv nor recvonly,
2392 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002393 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002394 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002395 // The remote description has signaled the stream IDs.
2396 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002397 }
Steve Antondcc3c022017-12-22 16:02:54 -08002398 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2399 (!transceiver->current_direction() ||
2400 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002401 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002402 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002403 << content->name << " (added to "
2404 << GetStreamIdsString(stream_ids) << ").";
2405
2406 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2407 for (const std::string& stream_id : stream_ids) {
2408 rtc::scoped_refptr<MediaStreamInterface> stream =
2409 remote_streams_->find(stream_id);
2410 if (!stream) {
2411 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2412 MediaStream::Create(stream_id));
2413 remote_streams_->AddStream(stream);
2414 added_streams.push_back(stream);
2415 }
2416 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002417 }
Steve Anton3172c032018-05-03 15:30:18 -07002418 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002419 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002420 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002421 }
2422 // If direction is sendonly or inactive, and transceiver's current
2423 // direction is neither sendonly nor inactive, process the removal of a
2424 // remote track for the media description.
2425 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002426 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002427 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002428 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2429 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002430 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2431 transceiver->internal()->receiver_internal()->streams();
2432 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002433 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002434 no_longer_receiving_transceivers.push_back(transceiver);
2435 // Remove any streams that no longer have tracks.
2436 for (auto stream : media_streams) {
2437 if (stream->GetAudioTracks().empty() &&
2438 stream->GetVideoTracks().empty()) {
2439 remote_streams_->RemoveStream(stream);
2440 removed_streams.push_back(stream);
2441 }
2442 }
Steve Antondcc3c022017-12-22 16:02:54 -08002443 }
2444 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2445 transceiver->internal()->set_current_direction(local_direction);
2446 }
2447 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002448 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2449 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002450 transceiver->Stop();
2451 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002452 if (!content->rejected &&
2453 RtpTransceiverDirectionHasRecv(local_direction)) {
2454 // Set ssrc to 0 in the case of an unsignalled ssrc.
2455 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002456 if (!media_desc->streams().empty() &&
2457 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002458 ssrc = media_desc->streams()[0].first_ssrc();
2459 }
2460 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002461 }
Steve Antondcc3c022017-12-22 16:02:54 -08002462 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002463 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002464 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002465 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002466 observer_->OnTrack(transceiver);
2467 observer_->OnAddTrack(transceiver->receiver(),
2468 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002469 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002470 for (auto stream : added_streams) {
2471 observer_->OnAddStream(stream);
2472 }
Steve Anton3172c032018-05-03 15:30:18 -07002473 for (auto transceiver : no_longer_receiving_transceivers) {
2474 observer_->OnRemoveTrack(transceiver->receiver());
2475 }
2476 for (auto stream : removed_streams) {
2477 observer_->OnRemoveStream(stream);
2478 }
Steve Antondcc3c022017-12-22 16:02:54 -08002479 }
2480
Henrik Boströmfdb92012017-11-09 19:55:44 +01002481 const cricket::ContentInfo* audio_content =
2482 GetFirstAudioContent(remote_description()->description());
2483 const cricket::ContentInfo* video_content =
2484 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002485 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002486 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002487 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002488 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002489 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002490 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002491
2492 // Check if the descriptions include streams, just in case the peer supports
2493 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002494 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002495 (audio_desc && !audio_desc->streams().empty()) ||
2496 (video_desc && !video_desc->streams().empty())) {
2497 remote_peer_supports_msid_ = true;
2498 }
deadbeefab9b2d12015-10-14 11:33:11 -07002499
2500 // We wait to signal new streams until we finish processing the description,
2501 // since only at that point will new streams have all their tracks.
2502 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2503
Steve Antondcc3c022017-12-22 16:02:54 -08002504 if (!IsUnifiedPlan()) {
2505 // TODO(steveanton): When removing RTP senders/receivers in response to a
2506 // rejected media section, there is some cleanup logic that expects the
2507 // voice/ video channel to still be set. But in this method the voice/video
2508 // channel would have been destroyed by the SetRemoteDescription caller
2509 // above so the cleanup that relies on them fails to run. The RemoveSenders
2510 // calls should be moved to right before the DestroyChannel calls to fix
2511 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002512
Steve Antondcc3c022017-12-22 16:02:54 -08002513 // Find all audio rtp streams and create corresponding remote AudioTracks
2514 // and MediaStreams.
2515 if (audio_content) {
2516 if (audio_content->rejected) {
2517 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2518 } else {
2519 bool default_audio_track_needed =
2520 !remote_peer_supports_msid_ &&
2521 RtpTransceiverDirectionHasSend(audio_desc->direction());
2522 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2523 default_audio_track_needed, audio_desc->type(),
2524 new_streams);
2525 }
deadbeeffaac4972015-11-12 15:33:07 -08002526 }
deadbeefab9b2d12015-10-14 11:33:11 -07002527
Steve Antondcc3c022017-12-22 16:02:54 -08002528 // Find all video rtp streams and create corresponding remote VideoTracks
2529 // and MediaStreams.
2530 if (video_content) {
2531 if (video_content->rejected) {
2532 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2533 } else {
2534 bool default_video_track_needed =
2535 !remote_peer_supports_msid_ &&
2536 RtpTransceiverDirectionHasSend(video_desc->direction());
2537 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2538 default_video_track_needed, video_desc->type(),
2539 new_streams);
2540 }
deadbeeffaac4972015-11-12 15:33:07 -08002541 }
deadbeefab9b2d12015-10-14 11:33:11 -07002542
Steve Antondcc3c022017-12-22 16:02:54 -08002543 // Update the DataChannels with the information from the remote peer.
2544 if (data_desc) {
2545 if (rtc::starts_with(data_desc->protocol().data(),
2546 cricket::kMediaProtocolRtpPrefix)) {
2547 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2548 }
deadbeefab9b2d12015-10-14 11:33:11 -07002549 }
deadbeefab9b2d12015-10-14 11:33:11 -07002550
Steve Antondcc3c022017-12-22 16:02:54 -08002551 // Iterate new_streams and notify the observer about new MediaStreams.
2552 for (size_t i = 0; i < new_streams->count(); ++i) {
2553 MediaStreamInterface* new_stream = new_streams->at(i);
2554 stats_->AddStream(new_stream);
2555 observer_->OnAddStream(
2556 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2557 }
deadbeefab9b2d12015-10-14 11:33:11 -07002558
Steve Antondcc3c022017-12-22 16:02:54 -08002559 UpdateEndedRemoteMediaStreams();
2560 }
deadbeefab9b2d12015-10-14 11:33:11 -07002561
Steve Anton8a006912017-12-04 15:25:56 -08002562 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002563}
2564
Steve Antondcc3c022017-12-22 16:02:54 -08002565RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2566 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002567 const SessionDescriptionInterface& new_session,
2568 const SessionDescriptionInterface* old_local_description,
2569 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002570 RTC_DCHECK(IsUnifiedPlan());
2571
Steve Anton7464fca2018-01-19 11:10:37 -08002572 const cricket::ContentGroup* bundle_group = nullptr;
2573 if (new_session.GetType() == SdpType::kOffer) {
2574 auto bundle_group_or_error =
2575 GetEarlyBundleGroup(*new_session.description());
2576 if (!bundle_group_or_error.ok()) {
2577 return bundle_group_or_error.MoveError();
2578 }
2579 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002580 }
Steve Antondcc3c022017-12-22 16:02:54 -08002581
Steve Antondcc3c022017-12-22 16:02:54 -08002582 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002583 for (size_t i = 0; i < new_contents.size(); ++i) {
2584 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002585 cricket::MediaType media_type = new_content.media_description()->type();
2586 seen_mids_.insert(new_content.name);
2587 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2588 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002589 const cricket::ContentInfo* old_local_content = nullptr;
2590 if (old_local_description &&
2591 i < old_local_description->description()->contents().size()) {
2592 old_local_content =
2593 &old_local_description->description()->contents()[i];
2594 }
2595 const cricket::ContentInfo* old_remote_content = nullptr;
2596 if (old_remote_description &&
2597 i < old_remote_description->description()->contents().size()) {
2598 old_remote_content =
2599 &old_remote_description->description()->contents()[i];
2600 }
Steve Antondcc3c022017-12-22 16:02:54 -08002601 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002602 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2603 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002604 if (!transceiver_or_error.ok()) {
2605 return transceiver_or_error.MoveError();
2606 }
2607 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002608 RTCError error =
2609 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2610 if (!error.ok()) {
2611 return error;
2612 }
2613 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002614 if (GetDataMid() && new_content.name != *GetDataMid()) {
2615 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002616 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2617 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002618 continue;
2619 }
2620 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2621 if (!error.ok()) {
2622 return error;
2623 }
Steve Antondcc3c022017-12-22 16:02:54 -08002624 } else {
2625 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2626 "Unknown section type.");
2627 }
2628 }
2629
2630 return RTCError::OK();
2631}
2632
2633RTCError PeerConnection::UpdateTransceiverChannel(
2634 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2635 transceiver,
2636 const cricket::ContentInfo& content,
2637 const cricket::ContentGroup* bundle_group) {
2638 RTC_DCHECK(IsUnifiedPlan());
2639 RTC_DCHECK(transceiver);
2640 cricket::BaseChannel* channel = transceiver->internal()->channel();
2641 if (content.rejected) {
2642 if (channel) {
2643 transceiver->internal()->SetChannel(nullptr);
2644 DestroyBaseChannel(channel);
2645 }
2646 } else {
2647 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002648 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002649 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002650 } else {
Steve Anton69470252018-02-09 11:43:08 -08002651 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002652 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002653 }
2654 if (!channel) {
2655 LOG_AND_RETURN_ERROR(
2656 RTCErrorType::INTERNAL_ERROR,
2657 "Failed to create channel for mid=" + content.name);
2658 }
2659 transceiver->internal()->SetChannel(channel);
2660 }
2661 }
2662 return RTCError::OK();
2663}
2664
Steve Antonfa2260d2017-12-28 16:38:23 -08002665RTCError PeerConnection::UpdateDataChannel(
2666 cricket::ContentSource source,
2667 const cricket::ContentInfo& content,
2668 const cricket::ContentGroup* bundle_group) {
2669 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002670 // If data channels are disabled, ignore this media section. CreateAnswer
2671 // will take care of rejecting it.
2672 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002673 }
2674 if (content.rejected) {
2675 DestroyDataChannel();
2676 } else {
2677 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002678 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002679 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2680 "Failed to create data channel.");
2681 }
2682 }
2683 if (source == cricket::CS_REMOTE) {
2684 const MediaContentDescription* data_desc = content.media_description();
2685 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2686 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2687 }
2688 }
2689 }
2690 return RTCError::OK();
2691}
2692
Steve Antondcc3c022017-12-22 16:02:54 -08002693RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2694PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002695 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002696 size_t mline_index,
2697 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002698 const ContentInfo* old_local_content,
2699 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002700 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002701 // If this is an offer then the m= section might be recycled. If the m=
2702 // section is being recycled (defined as: rejected in the current local or
2703 // remote description and not rejected in new description), dissociate the
2704 // currently associated RtpTransceiver by setting its mid property to null,
2705 // and discard the mapping between the transceiver and its m= section index.
2706 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2707 old_remote_content)) {
2708 // We want to dissociate the transceiver that has the rejected mid.
2709 const std::string& old_mid =
2710 (old_local_content && old_local_content->rejected)
2711 ? old_local_content->name
2712 : old_remote_content->name;
2713 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002714 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002715 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2716 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002717 old_transceiver->internal()->set_mid(absl::nullopt);
2718 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002719 }
2720 }
2721 const MediaContentDescription* media_desc = content.media_description();
2722 auto transceiver = GetAssociatedTransceiver(content.name);
2723 if (source == cricket::CS_LOCAL) {
2724 // Find the RtpTransceiver that corresponds to this m= section, using the
2725 // mapping between transceivers and m= section indices established when
2726 // creating the offer.
2727 if (!transceiver) {
2728 transceiver = GetTransceiverByMLineIndex(mline_index);
2729 }
2730 if (!transceiver) {
2731 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2732 "Unknown transceiver");
2733 }
2734 } else {
2735 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2736 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2737 // of the same type...
2738 if (!transceiver &&
2739 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2740 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2741 }
2742 // If no RtpTransceiver was found in the previous step, create one with a
2743 // recvonly direction.
2744 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002745 RTC_LOG(LS_INFO) << "Adding "
2746 << cricket::MediaTypeToString(media_desc->type())
2747 << " transceiver for MID=" << content.name
2748 << " at i=" << mline_index
2749 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002750 auto sender =
2751 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002752 std::string receiver_id;
2753 if (!media_desc->streams().empty()) {
2754 receiver_id = media_desc->streams()[0].id;
2755 } else {
2756 receiver_id = rtc::CreateRandomUuid();
2757 }
2758 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002759 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002760 transceiver->internal()->set_direction(
2761 RtpTransceiverDirection::kRecvOnly);
2762 }
2763 }
2764 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002765 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002766 LOG_AND_RETURN_ERROR(
2767 RTCErrorType::INVALID_PARAMETER,
2768 "Transceiver type does not match media description type.");
2769 }
2770 // Associate the found or created RtpTransceiver with the m= section by
2771 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2772 // section, and establish a mapping between the transceiver and the index of
2773 // the m= section.
2774 transceiver->internal()->set_mid(content.name);
2775 transceiver->internal()->set_mline_index(mline_index);
2776 return std::move(transceiver);
2777}
2778
2779rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2780PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2781 RTC_DCHECK(IsUnifiedPlan());
2782 for (auto transceiver : transceivers_) {
2783 if (transceiver->mid() == mid) {
2784 return transceiver;
2785 }
2786 }
2787 return nullptr;
2788}
2789
2790rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2791PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2792 RTC_DCHECK(IsUnifiedPlan());
2793 for (auto transceiver : transceivers_) {
2794 if (transceiver->internal()->mline_index() == mline_index) {
2795 return transceiver;
2796 }
2797 }
2798 return nullptr;
2799}
2800
2801rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2802PeerConnection::FindAvailableTransceiverToReceive(
2803 cricket::MediaType media_type) const {
2804 RTC_DCHECK(IsUnifiedPlan());
2805 // From JSEP section 5.10 (Applying a Remote Description):
2806 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2807 // the same type that were added to the PeerConnection by addTrack and are not
2808 // associated with any m= section and are not stopped, find the first such
2809 // RtpTransceiver.
2810 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002811 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002812 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2813 !transceiver->stopped()) {
2814 return transceiver;
2815 }
2816 }
2817 return nullptr;
2818}
2819
Steve Antoned10bd92017-12-05 10:52:59 -08002820const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2821 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2822 transceiver,
2823 const SessionDescriptionInterface* sdesc) const {
2824 RTC_DCHECK(transceiver);
2825 RTC_DCHECK(sdesc);
2826 if (IsUnifiedPlan()) {
2827 if (!transceiver->internal()->mid()) {
2828 // This transceiver is not associated with a media section yet.
2829 return nullptr;
2830 }
2831 return sdesc->description()->GetContentByName(
2832 *transceiver->internal()->mid());
2833 } else {
2834 // Plan B only allows at most one audio and one video section, so use the
2835 // first media section of that type.
2836 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002837 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002838 }
2839}
2840
deadbeef46c73892016-11-16 19:42:04 -08002841PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2842 return configuration_;
2843}
2844
deadbeef293e9262017-01-11 12:28:30 -08002845bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2846 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002847 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002848 if (IsClosed()) {
2849 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2850 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2851 }
2852
Qingsi Wanga2d60672018-04-11 16:57:45 -07002853 // According to JSEP, after setLocalDescription, changing the candidate pool
2854 // size is not allowed, and changing the set of ICE servers will not result
2855 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002856 if (local_description() && configuration.ice_candidate_pool_size !=
2857 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002858 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2859 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002860 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002861 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002862
deadbeef293e9262017-01-11 12:28:30 -08002863 // The simplest (and most future-compatible) way to tell if the config was
2864 // modified in an invalid way is to copy each property we do support
2865 // modifying, then use operator==. There are far more properties we don't
2866 // support modifying than those we do, and more could be added.
2867 RTCConfiguration modified_config = configuration_;
2868 modified_config.servers = configuration.servers;
2869 modified_config.type = configuration.type;
2870 modified_config.ice_candidate_pool_size =
2871 configuration.ice_candidate_pool_size;
2872 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002873 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002874 modified_config.ice_check_interval_strong_connectivity =
2875 configuration.ice_check_interval_strong_connectivity;
2876 modified_config.ice_check_interval_weak_connectivity =
2877 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002878 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2879 modified_config.ice_unwritable_min_checks =
2880 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002881 modified_config.stun_candidate_keepalive_interval =
2882 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002883 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002884 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002885 modified_config.active_reset_srtp_params =
2886 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002887 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002888 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002889 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2890 }
2891
Steve Anton038834f2017-07-14 15:59:59 -07002892 // Validate the modified configuration.
2893 RTCError validate_error = ValidateConfiguration(modified_config);
2894 if (!validate_error.ok()) {
2895 return SafeSetError(std::move(validate_error), error);
2896 }
2897
deadbeef293e9262017-01-11 12:28:30 -08002898 // Note that this isn't possible through chromium, since it's an unsigned
2899 // short in WebIDL.
2900 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002901 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002902 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2903 }
2904
2905 // Parse ICE servers before hopping to network thread.
2906 cricket::ServerAddresses stun_servers;
2907 std::vector<cricket::RelayServerConfig> turn_servers;
2908 RTCErrorType parse_error =
2909 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2910 if (parse_error != RTCErrorType::NONE) {
2911 return SafeSetError(parse_error, error);
2912 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002913 // Note if STUN or TURN servers were supplied.
2914 if (!stun_servers.empty()) {
2915 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2916 }
2917 if (!turn_servers.empty()) {
2918 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2919 }
deadbeef293e9262017-01-11 12:28:30 -08002920
2921 // In theory this shouldn't fail.
2922 if (!network_thread()->Invoke<bool>(
2923 RTC_FROM_HERE,
2924 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2925 stun_servers, turn_servers, modified_config.type,
2926 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002927 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002928 modified_config.turn_customizer,
2929 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002930 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002931 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2932 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002933
deadbeefd1a38b52016-12-10 13:15:33 -08002934 // As described in JSEP, calling setConfiguration with new ICE servers or
2935 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2936 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002937 if (modified_config.servers != configuration_.servers ||
2938 modified_config.type != configuration_.type ||
2939 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002940 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002941 }
skvladd1f5fda2017-02-03 16:54:05 -08002942
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002943 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002944
Zhi Huangb57e1692018-06-12 11:41:11 -07002945 if (configuration_.active_reset_srtp_params !=
2946 modified_config.active_reset_srtp_params) {
2947 transport_controller_->SetActiveResetSrtpParams(
2948 modified_config.active_reset_srtp_params);
2949 }
2950
deadbeef293e9262017-01-11 12:28:30 -08002951 configuration_ = modified_config;
2952 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002953}
2954
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002955bool PeerConnection::AddIceCandidate(
2956 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002957 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002958 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002959 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002960 return false;
2961 }
Steve Antond25da372017-11-06 14:50:29 -08002962
2963 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002964 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002965 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002966 return false;
2967 }
2968
2969 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002970 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002971 return false;
2972 }
2973
2974 bool valid = false;
2975 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2976 if (!valid) {
2977 return false;
2978 }
2979
2980 // Add this candidate to the remote session description.
2981 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002982 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002983 return false;
2984 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002985 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002986
2987 if (ready) {
2988 return UseCandidate(ice_candidate);
2989 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002990 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002991 return true;
2992 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002993}
2994
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002995bool PeerConnection::RemoveIceCandidates(
2996 const std::vector<cricket::Candidate>& candidates) {
2997 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002998 if (IsClosed()) {
2999 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3000 return false;
3001 }
3002
Steve Antond25da372017-11-06 14:50:29 -08003003 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003004 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3005 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003006 return false;
3007 }
3008
3009 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003010 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003011 return false;
3012 }
3013
3014 size_t number_removed =
3015 mutable_remote_description()->RemoveCandidates(candidates);
3016 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003017 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003018 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003019 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003020 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003021 }
3022
3023 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003024 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3025 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003026 RTC_LOG(LS_ERROR)
3027 << "RemoveIceCandidates: Error when removing remote candidates: "
3028 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003029 }
3030 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003031}
3032
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003033void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003034 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003035 network_thread()->Invoke<void>(
3036 RTC_FROM_HERE,
3037 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3038 // Send information about IPv4/IPv6 status.
3039 if (uma_observer_) {
3040 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3041 uma_observer_->IncrementEnumCounter(
3042 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3043 kPeerConnectionAddressFamilyCounter_Max);
3044 } else {
3045 uma_observer_->IncrementEnumCounter(
3046 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3047 kPeerConnectionAddressFamilyCounter_Max);
3048 }
3049 }
3050}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003051
Qingsi Wanga2d60672018-04-11 16:57:45 -07003052void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3053 RTC_DCHECK(network_thread()->IsCurrent());
3054 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003055 if (transport_controller_) {
3056 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003057 }
3058
3059 for (auto transceiver : transceivers_) {
3060 auto* channel = transceiver->internal()->channel();
3061 if (channel) {
3062 channel->SetMetricsObserver(uma_observer_);
3063 }
3064 }
3065
deadbeef293e9262017-01-11 12:28:30 -08003066 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003067 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003068 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003069}
3070
Niels Möller0c4f7be2018-05-07 14:01:37 +02003071RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003072 if (!worker_thread()->IsCurrent()) {
3073 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003074 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003075 }
3076
Niels Möller0c4f7be2018-05-07 14:01:37 +02003077 const bool has_min = bitrate.min_bitrate_bps.has_value();
3078 const bool has_start = bitrate.start_bitrate_bps.has_value();
3079 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003080 if (has_min && *bitrate.min_bitrate_bps < 0) {
3081 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3082 "min_bitrate_bps <= 0");
3083 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003084 if (has_start) {
3085 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003086 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003087 "start_bitrate_bps < min_bitrate_bps");
3088 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003089 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3090 "curent_bitrate_bps < 0");
3091 }
3092 }
3093 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003094 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003095 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003096 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003097 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3098 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3099 "max_bitrate_bps < min_bitrate_bps");
3100 } else if (*bitrate.max_bitrate_bps < 0) {
3101 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3102 "max_bitrate_bps < 0");
3103 }
3104 }
3105
zstein4b979802017-06-02 14:37:37 -07003106 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003107 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003108
3109 return RTCError::OK();
3110}
3111
Alex Narest78609d52017-10-20 10:37:47 +02003112void PeerConnection::SetBitrateAllocationStrategy(
3113 std::unique_ptr<rtc::BitrateAllocationStrategy>
3114 bitrate_allocation_strategy) {
3115 rtc::Thread* worker_thread = factory_->worker_thread();
3116 if (!worker_thread->IsCurrent()) {
3117 rtc::BitrateAllocationStrategy* strategy_raw =
3118 bitrate_allocation_strategy.release();
3119 auto functor = [this, strategy_raw]() {
3120 call_->SetBitrateAllocationStrategy(
3121 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3122 };
3123 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3124 return;
3125 }
3126 RTC_DCHECK(call_.get());
3127 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3128}
3129
henrika5f6bf242017-11-01 11:06:56 +01003130void PeerConnection::SetAudioPlayout(bool playout) {
3131 if (!worker_thread()->IsCurrent()) {
3132 worker_thread()->Invoke<void>(
3133 RTC_FROM_HERE,
3134 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3135 return;
3136 }
3137 auto audio_state =
3138 factory_->channel_manager()->media_engine()->GetAudioState();
3139 audio_state->SetPlayout(playout);
3140}
3141
3142void PeerConnection::SetAudioRecording(bool recording) {
3143 if (!worker_thread()->IsCurrent()) {
3144 worker_thread()->Invoke<void>(
3145 RTC_FROM_HERE,
3146 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3147 return;
3148 }
3149 auto audio_state =
3150 factory_->channel_manager()->media_engine()->GetAudioState();
3151 audio_state->SetRecording(recording);
3152}
3153
Steve Anton8c0f7a72017-10-03 10:03:10 -07003154std::unique_ptr<rtc::SSLCertificate>
3155PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003156 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3157 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003158 return nullptr;
3159 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003160 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003161}
3162
Zhi Huang70b820f2018-01-27 14:16:15 -08003163std::unique_ptr<rtc::SSLCertChain>
3164PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003165 auto audio_transceiver = GetFirstAudioTransceiver();
3166 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003167 return nullptr;
3168 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003169 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003170 audio_transceiver->internal()->channel()->transport_name());
3171}
3172
3173rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3174PeerConnection::GetFirstAudioTransceiver() const {
3175 for (auto transceiver : transceivers_) {
3176 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3177 return transceiver;
3178 }
3179 }
3180 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003181}
3182
ivoc14d5dbe2016-07-04 07:06:55 -07003183bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3184 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003185 // TODO(eladalon): It would be better to not allow negative values into PC.
3186 const size_t max_size = (max_size_bytes < 0)
3187 ? RtcEventLog::kUnlimitedOutput
3188 : rtc::saturated_cast<size_t>(max_size_bytes);
3189 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003190 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3191 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003192}
3193
Bjorn Tereliusde939432017-11-20 17:38:14 +01003194bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3195 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003196 // TODO(eladalon): In C++14, this can be done with a lambda.
3197 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003198 bool operator()() {
3199 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3200 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003201 PeerConnection* const pc;
3202 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003203 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003204 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003205 return worker_thread()->Invoke<bool>(
3206 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003207}
3208
3209void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003210 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003211 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3212}
3213
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003214const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003215 return pending_local_description_ ? pending_local_description_.get()
3216 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217}
3218
3219const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003220 return pending_remote_description_ ? pending_remote_description_.get()
3221 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003222}
3223
deadbeeffe4a8a42016-12-20 17:56:17 -08003224const SessionDescriptionInterface* PeerConnection::current_local_description()
3225 const {
Steve Anton75737c02017-11-06 10:37:17 -08003226 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003227}
3228
3229const SessionDescriptionInterface* PeerConnection::current_remote_description()
3230 const {
Steve Anton75737c02017-11-06 10:37:17 -08003231 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003232}
3233
3234const SessionDescriptionInterface* PeerConnection::pending_local_description()
3235 const {
Steve Anton75737c02017-11-06 10:37:17 -08003236 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003237}
3238
3239const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3240 const {
Steve Anton75737c02017-11-06 10:37:17 -08003241 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003242}
3243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003245 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 // Update stats here so that we have the most recent stats for tracks and
3247 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003248 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003249
Steve Anton75737c02017-11-06 10:37:17 -08003250 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003251 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003252
Steve Anton8af21862017-12-15 11:20:13 -08003253 for (auto transceiver : transceivers_) {
3254 transceiver->Stop();
3255 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003256
3257 // Ensure that all asynchronous stats requests are completed before destroying
3258 // the transport controller below.
3259 if (stats_collector_) {
3260 stats_collector_->WaitForPendingRequest();
3261 }
3262
3263 // Don't destroy BaseChannels until after stats has been cleaned up so that
3264 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003265 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003266
Qingsi Wang93a84392018-01-30 17:13:09 -08003267 // The event log is used in the transport controller, which must be outlived
3268 // by the former. CreateOffer by the peer connection is implemented
3269 // asynchronously and if the peer connection is closed without resetting the
3270 // WebRTC session description factory, the session description factory would
3271 // call the transport controller.
3272 webrtc_session_desc_factory_.reset();
3273 transport_controller_.reset();
3274
deadbeef42a42632017-03-10 15:18:00 -08003275 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003276 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3277 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003278
Steve Anton978b8762017-09-29 12:15:02 -07003279 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003280 call_.reset();
3281 // The event log must outlive call (and any other object that uses it).
3282 event_log_.reset();
3283 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003284 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003285}
3286
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003287void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003288 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003289 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3290 SetSessionDescriptionMsg* param =
3291 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3292 param->observer->OnSuccess();
3293 delete param;
3294 break;
3295 }
3296 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3297 SetSessionDescriptionMsg* param =
3298 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003299 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003300 delete param;
3301 break;
3302 }
deadbeefab9b2d12015-10-14 11:33:11 -07003303 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3304 CreateSessionDescriptionMsg* param =
3305 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003306 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003307 delete param;
3308 break;
3309 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003310 case MSG_GETSTATS: {
3311 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003312 StatsReports reports;
3313 stats_->GetStats(param->track, &reports);
3314 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315 delete param;
3316 break;
3317 }
deadbeefbd292462015-12-14 18:15:29 -08003318 case MSG_FREE_DATACHANNELS: {
3319 sctp_data_channels_to_free_.clear();
3320 break;
3321 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003322 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003323 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003324 break;
3325 }
3326}
3327
Steve Antonafb0bb72018-02-20 11:35:37 -08003328cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3329 RTC_DCHECK(!IsUnifiedPlan());
3330 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3331 GetAudioTransceiver()->internal()->channel());
3332 if (voice_channel) {
3333 return voice_channel->media_channel();
3334 } else {
3335 return nullptr;
3336 }
3337}
3338
3339cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3340 RTC_DCHECK(!IsUnifiedPlan());
3341 auto* video_channel = static_cast<cricket::VideoChannel*>(
3342 GetVideoTransceiver()->internal()->channel());
3343 if (video_channel) {
3344 return video_channel->media_channel();
3345 } else {
3346 return nullptr;
3347 }
3348}
3349
Steve Anton4171afb2017-11-20 10:20:22 -08003350void PeerConnection::CreateAudioReceiver(
3351 MediaStreamInterface* stream,
3352 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003353 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3354 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003355 auto* audio_receiver = new AudioRtpReceiver(
3356 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003357 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003358 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3359 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3360 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003361 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003362 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003363 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003364}
3365
Steve Anton4171afb2017-11-20 10:20:22 -08003366void PeerConnection::CreateVideoReceiver(
3367 MediaStreamInterface* stream,
3368 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003369 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3370 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003371 auto* video_receiver = new VideoRtpReceiver(
3372 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003373 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003374 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3375 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3376 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003377 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003378 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003379 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003380}
3381
deadbeef70ab1a12015-09-28 16:53:55 -07003382// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3383// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003384rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003385 const RtpSenderInfo& remote_sender_info) {
3386 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3387 if (!receiver) {
3388 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3389 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003390 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003391 }
Steve Anton4171afb2017-11-20 10:20:22 -08003392 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3393 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3394 } else {
3395 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3396 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003397 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003398}
3399
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003400void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3401 MediaStreamInterface* stream) {
3402 RTC_DCHECK(!IsClosed());
3403 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003404 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003405 // We already have a sender for this track, so just change the stream_id
3406 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003407 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003408 return;
3409 }
3410
3411 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003412 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003413 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003414 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003415 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003416 // If the sender has already been configured in SDP, we call SetSsrc,
3417 // which will connect the sender to the underlying transport. This can
3418 // occur if a local session description that contains the ID of the sender
3419 // is set before AddStream is called. It can also occur if the local
3420 // session description is not changed and RemoveStream is called, and
3421 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003422 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003423 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003424 if (sender_info) {
3425 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003426 }
3427}
3428
3429// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3430// indefinitely, when we have unified plan SDP.
3431void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3432 MediaStreamInterface* stream) {
3433 RTC_DCHECK(!IsClosed());
3434 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003435 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003436 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3437 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003438 return;
3439 }
Steve Anton4171afb2017-11-20 10:20:22 -08003440 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003441}
3442
3443void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3444 MediaStreamInterface* stream) {
3445 RTC_DCHECK(!IsClosed());
3446 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003447 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003448 // We already have a sender for this track, so just change the stream_id
3449 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003450 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003451 return;
3452 }
3453
3454 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003455 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003456 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003457 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003458 GetVideoTransceiver()->internal()->AddSender(new_sender);
3459 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003460 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003461 if (sender_info) {
3462 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003463 }
3464}
3465
3466void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3467 MediaStreamInterface* stream) {
3468 RTC_DCHECK(!IsClosed());
3469 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003470 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003471 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3472 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003473 return;
3474 }
Steve Anton4171afb2017-11-20 10:20:22 -08003475 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003476}
3477
Steve Antonba818672017-11-06 10:21:57 -08003478void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003479 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003480 if (ice_connection_state_ == new_state) {
3481 return;
3482 }
3483
deadbeefcbecd352015-09-23 11:50:27 -07003484 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003485 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003486 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003487 return;
3488 }
Steve Antonba818672017-11-06 10:21:57 -08003489
Mirko Bonadei675513b2017-11-09 11:09:25 +01003490 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3491 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003492 RTC_DCHECK(ice_connection_state_ !=
3493 PeerConnectionInterface::kIceConnectionClosed);
3494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003496 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497}
3498
3499void PeerConnection::OnIceGatheringChange(
3500 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003501 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003502 if (IsClosed()) {
3503 return;
3504 }
3505 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003506 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003507}
3508
jbauch81bf7b02017-03-25 08:31:12 -07003509void PeerConnection::OnIceCandidate(
3510 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003511 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003512 if (IsClosed()) {
3513 return;
3514 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003515 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003516 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517}
3518
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003519void PeerConnection::OnIceCandidatesRemoved(
3520 const std::vector<cricket::Candidate>& candidates) {
3521 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003522 if (IsClosed()) {
3523 return;
3524 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003525 observer_->OnIceCandidatesRemoved(candidates);
3526}
3527
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003528void PeerConnection::ChangeSignalingState(
3529 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003530 RTC_DCHECK(signaling_thread()->IsCurrent());
3531 if (signaling_state_ == signaling_state) {
3532 return;
3533 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003534 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3535 << GetSignalingStateString(signaling_state_)
3536 << " New state: "
3537 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538 signaling_state_ = signaling_state;
3539 if (signaling_state == kClosed) {
3540 ice_connection_state_ = kIceConnectionClosed;
3541 observer_->OnIceConnectionChange(ice_connection_state_);
3542 if (ice_gathering_state_ != kIceGatheringComplete) {
3543 ice_gathering_state_ = kIceGatheringComplete;
3544 observer_->OnIceGatheringChange(ice_gathering_state_);
3545 }
3546 }
3547 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003548}
3549
deadbeefeb459812015-12-15 19:24:43 -08003550void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3551 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003552 if (IsClosed()) {
3553 return;
3554 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003555 AddAudioTrack(track, stream);
3556 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003557}
3558
deadbeefeb459812015-12-15 19:24:43 -08003559void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3560 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003561 if (IsClosed()) {
3562 return;
3563 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003564 RemoveAudioTrack(track, stream);
3565 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003566}
3567
3568void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3569 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003570 if (IsClosed()) {
3571 return;
3572 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003573 AddVideoTrack(track, stream);
3574 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003575}
3576
3577void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3578 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003579 if (IsClosed()) {
3580 return;
3581 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003582 RemoveVideoTrack(track, stream);
3583 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003584}
3585
Henrik Boström31638672017-11-23 17:48:32 +01003586void PeerConnection::PostSetSessionDescriptionSuccess(
3587 SetSessionDescriptionObserver* observer) {
3588 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3589 signaling_thread()->Post(RTC_FROM_HERE, this,
3590 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3591}
3592
deadbeefab9b2d12015-10-14 11:33:11 -07003593void PeerConnection::PostSetSessionDescriptionFailure(
3594 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003595 RTCError&& error) {
3596 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003597 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003598 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003599 signaling_thread()->Post(RTC_FROM_HERE, this,
3600 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003601}
3602
3603void PeerConnection::PostCreateSessionDescriptionFailure(
3604 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003605 RTCError error) {
3606 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003607 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003608 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003609 signaling_thread()->Post(RTC_FROM_HERE, this,
3610 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003611}
3612
zhihuang1c378ed2017-08-17 14:10:50 -07003613void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003614 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003615 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003616 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003617
Steve Antondcc3c022017-12-22 16:02:54 -08003618 if (IsUnifiedPlan()) {
3619 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3620 } else {
3621 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3622 }
3623
Steve Antonfa2260d2017-12-28 16:38:23 -08003624 // Intentionally unset the data channel type for RTP data channel with the
3625 // second condition. Otherwise the RTP data channels would be successfully
3626 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3627 // when building with chromium. We want to leave RTP data channels broken, so
3628 // people won't try to use them.
3629 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3630 session_options->data_channel_type = data_channel_type();
3631 }
3632
Steve Antondcc3c022017-12-22 16:02:54 -08003633 // Apply ICE restart flag and renomination flag.
3634 for (auto& options : session_options->media_description_options) {
3635 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3636 options.transport_options.enable_ice_renomination =
3637 configuration_.enable_ice_renomination;
3638 }
3639
3640 session_options->rtcp_cname = rtcp_cname_;
3641 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003642 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003643}
3644
3645void PeerConnection::GetOptionsForPlanBOffer(
3646 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3647 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003648 // Figure out transceiver directional preferences.
3649 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3650 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3651
3652 // By default, generate sendrecv/recvonly m= sections.
3653 bool recv_audio = true;
3654 bool recv_video = true;
3655
3656 // By default, only offer a new m= section if we have media to send with it.
3657 bool offer_new_audio_description = send_audio;
3658 bool offer_new_video_description = send_video;
3659 bool offer_new_data_description = HasDataChannels();
3660
3661 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003662 if (offer_answer_options.offer_to_receive_audio !=
3663 RTCOfferAnswerOptions::kUndefined) {
3664 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003665 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003666 offer_new_audio_description ||
3667 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003668 }
Steve Antondcc3c022017-12-22 16:02:54 -08003669 if (offer_answer_options.offer_to_receive_video !=
3670 RTCOfferAnswerOptions::kUndefined) {
3671 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003672 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003673 offer_new_video_description ||
3674 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003675 }
3676
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003677 absl::optional<size_t> audio_index;
3678 absl::optional<size_t> video_index;
3679 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003680 // If a current description exists, generate m= sections in the same order,
3681 // using the first audio/video/data section that appears and rejecting
3682 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003683 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003684 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003685 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003686 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3687 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3688 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003689 }
3690
zhihuang1c378ed2017-08-17 14:10:50 -07003691 // Add audio/video/data m= sections to the end if needed.
3692 if (!audio_index && offer_new_audio_description) {
3693 session_options->media_description_options.push_back(
3694 cricket::MediaDescriptionOptions(
3695 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003696 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3697 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003698 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003699 }
zhihuang1c378ed2017-08-17 14:10:50 -07003700 if (!video_index && offer_new_video_description) {
3701 session_options->media_description_options.push_back(
3702 cricket::MediaDescriptionOptions(
3703 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003704 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3705 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003706 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003707 }
zhihuang1c378ed2017-08-17 14:10:50 -07003708 if (!data_index && offer_new_data_description) {
3709 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003710 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003711 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003712 }
3713
3714 cricket::MediaDescriptionOptions* audio_media_description_options =
3715 !audio_index ? nullptr
3716 : &session_options->media_description_options[*audio_index];
3717 cricket::MediaDescriptionOptions* video_media_description_options =
3718 !video_index ? nullptr
3719 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003720
Steve Anton4171afb2017-11-20 10:20:22 -08003721 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003722 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003723}
3724
3725// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3726// and return a reference to it.
3727// Generated MIDs should be no more than 3 bytes long to take up less space in
3728// the RTP packet.
3729static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3730 RTC_DCHECK(used_mids);
3731 // We're boring: just generate MIDs 0, 1, 2, ...
3732 size_t i = 0;
3733 std::set<std::string>::iterator it;
3734 bool inserted;
3735 do {
3736 std::string mid = rtc::ToString(i++);
3737 auto insert_result = used_mids->insert(mid);
3738 it = insert_result.first;
3739 inserted = insert_result.second;
3740 } while (!inserted);
3741 return *it;
3742}
3743
3744static cricket::MediaDescriptionOptions
3745GetMediaDescriptionOptionsForTransceiver(
3746 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3747 transceiver,
3748 const std::string& mid) {
3749 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003750 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003751 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003752 // This behavior is specified in JSEP. The gist is that:
3753 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3754 // sendrecv.
3755 // 2. If the MSID is included, then it must be included in any subsequent
3756 // offer/answer exactly the same until the RtpTransceiver is stopped.
3757 if (!transceiver->stopped() &&
3758 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3759 transceiver->internal()->has_ever_been_used_to_send())) {
3760 cricket::SenderOptions sender_options;
3761 sender_options.track_id = transceiver->sender()->id();
3762 sender_options.stream_ids = transceiver->sender()->stream_ids();
3763 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3764 // set in the RTP parameters when the transceiver was added.
3765 sender_options.num_sim_layers = 1;
3766 media_description_options.sender_options.push_back(sender_options);
3767 }
Steve Antondcc3c022017-12-22 16:02:54 -08003768 return media_description_options;
3769}
3770
3771void PeerConnection::GetOptionsForUnifiedPlanOffer(
3772 const RTCOfferAnswerOptions& offer_answer_options,
3773 cricket::MediaSessionOptions* session_options) {
3774 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3775 // Offers) and 5.2.2 (Subsequent Offers).
3776 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3777 const ContentInfos& local_contents =
3778 (local_description() ? local_description()->description()->contents()
3779 : ContentInfos());
3780 const ContentInfos& remote_contents =
3781 (remote_description() ? remote_description()->description()->contents()
3782 : ContentInfos());
3783 // The mline indices that can be recycled. New transceivers should reuse these
3784 // slots first.
3785 std::queue<size_t> recycleable_mline_indices;
3786 // Track the MIDs used in previous offer/answer exchanges and the current
3787 // offer so that new, unique MIDs are generated.
3788 std::set<std::string> used_mids = seen_mids_;
3789 // First, go through each media section that exists in either the local or
3790 // remote description and generate a media section in this offer for the
3791 // associated transceiver. If a media section can be recycled, generate a
3792 // default, rejected media section here that can be later overwritten.
3793 for (size_t i = 0;
3794 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3795 // Either |local_content| or |remote_content| is non-null.
3796 const ContentInfo* local_content =
3797 (i < local_contents.size() ? &local_contents[i] : nullptr);
3798 const ContentInfo* remote_content =
3799 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3800 bool had_been_rejected = (local_content && local_content->rejected) ||
3801 (remote_content && remote_content->rejected);
3802 const std::string& mid =
3803 (local_content ? local_content->name : remote_content->name);
3804 cricket::MediaType media_type =
3805 (local_content ? local_content->media_description()->type()
3806 : remote_content->media_description()->type());
3807 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3808 media_type == cricket::MEDIA_TYPE_VIDEO) {
3809 auto transceiver = GetAssociatedTransceiver(mid);
3810 RTC_CHECK(transceiver);
3811 // A media section is considered eligible for recycling if it is marked as
3812 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003813 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003814 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003815 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3816 RtpTransceiverDirection::kInactive,
3817 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003818 recycleable_mline_indices.push(i);
3819 } else {
3820 session_options->media_description_options.push_back(
3821 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3822 // CreateOffer shouldn't really cause any state changes in
3823 // PeerConnection, but we need a way to match new transceivers to new
3824 // media sections in SetLocalDescription and JSEP specifies this is done
3825 // by recording the index of the media section generated for the
3826 // transceiver in the offer.
3827 transceiver->internal()->set_mline_index(i);
3828 }
3829 } else {
3830 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003831 RTC_CHECK(GetDataMid());
3832 if (had_been_rejected || mid != *GetDataMid()) {
3833 session_options->media_description_options.push_back(
3834 GetMediaDescriptionOptionsForRejectedData(mid));
3835 } else {
3836 session_options->media_description_options.push_back(
3837 GetMediaDescriptionOptionsForActiveData(mid));
3838 }
Steve Antondcc3c022017-12-22 16:02:54 -08003839 }
3840 }
3841 // Next, look for transceivers that are newly added (that is, are not stopped
3842 // and not associated). Reuse media sections marked as recyclable first,
3843 // otherwise append to the end of the offer. New media sections should be
3844 // added in the order they were added to the PeerConnection.
3845 for (auto transceiver : transceivers_) {
3846 if (transceiver->mid() || transceiver->stopped()) {
3847 continue;
3848 }
3849 size_t mline_index;
3850 if (!recycleable_mline_indices.empty()) {
3851 mline_index = recycleable_mline_indices.front();
3852 recycleable_mline_indices.pop();
3853 session_options->media_description_options[mline_index] =
3854 GetMediaDescriptionOptionsForTransceiver(transceiver,
3855 AllocateMid(&used_mids));
3856 } else {
3857 mline_index = session_options->media_description_options.size();
3858 session_options->media_description_options.push_back(
3859 GetMediaDescriptionOptionsForTransceiver(transceiver,
3860 AllocateMid(&used_mids)));
3861 }
3862 // See comment above for why CreateOffer changes the transceiver's state.
3863 transceiver->internal()->set_mline_index(mline_index);
3864 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003865 // Lastly, add a m-section if we have local data channels and an m section
3866 // does not already exist.
3867 if (!GetDataMid() && HasDataChannels()) {
3868 session_options->media_description_options.push_back(
3869 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3870 }
Steve Antondcc3c022017-12-22 16:02:54 -08003871}
3872
3873void PeerConnection::GetOptionsForAnswer(
3874 const RTCOfferAnswerOptions& offer_answer_options,
3875 cricket::MediaSessionOptions* session_options) {
3876 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3877
3878 if (IsUnifiedPlan()) {
3879 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3880 } else {
3881 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3882 }
3883
Steve Antonfa2260d2017-12-28 16:38:23 -08003884 // Intentionally unset the data channel type for RTP data channel. Otherwise
3885 // the RTP data channels would be successfully negotiated by default and the
3886 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3887 // We want to leave RTP data channels broken, so people won't try to use them.
3888 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3889 session_options->data_channel_type = data_channel_type();
3890 }
3891
Steve Antondcc3c022017-12-22 16:02:54 -08003892 // Apply ICE renomination flag.
3893 for (auto& options : session_options->media_description_options) {
3894 options.transport_options.enable_ice_renomination =
3895 configuration_.enable_ice_renomination;
3896 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003897
3898 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003899 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003900 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003901}
3902
Steve Antondcc3c022017-12-22 16:02:54 -08003903void PeerConnection::GetOptionsForPlanBAnswer(
3904 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003905 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003906 // Figure out transceiver directional preferences.
3907 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3908 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3909
3910 // By default, generate sendrecv/recvonly m= sections. The direction is also
3911 // restricted by the direction in the offer.
3912 bool recv_audio = true;
3913 bool recv_video = true;
3914
3915 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003916 if (offer_answer_options.offer_to_receive_audio !=
3917 RTCOfferAnswerOptions::kUndefined) {
3918 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003919 }
Steve Antondcc3c022017-12-22 16:02:54 -08003920 if (offer_answer_options.offer_to_receive_video !=
3921 RTCOfferAnswerOptions::kUndefined) {
3922 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003923 }
3924
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003925 absl::optional<size_t> audio_index;
3926 absl::optional<size_t> video_index;
3927 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003928
3929 // Generate m= sections that match those in the offer.
3930 // Note that mediasession.cc will handle intersection our preferred
3931 // direction with the offered direction.
3932 GenerateMediaDescriptionOptions(
3933 remote_description(),
3934 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3935 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3936 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003937
3938 cricket::MediaDescriptionOptions* audio_media_description_options =
3939 !audio_index ? nullptr
3940 : &session_options->media_description_options[*audio_index];
3941 cricket::MediaDescriptionOptions* video_media_description_options =
3942 !video_index ? nullptr
3943 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003944
Steve Anton4171afb2017-11-20 10:20:22 -08003945 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003946 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003947}
zhihuangaf388472016-11-02 16:49:48 -07003948
Steve Antondcc3c022017-12-22 16:02:54 -08003949void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3950 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3951 cricket::MediaSessionOptions* session_options) {
3952 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3953 // Answers) and 5.3.2 (Subsequent Answers).
3954 RTC_DCHECK(remote_description());
3955 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3956 for (const ContentInfo& content :
3957 remote_description()->description()->contents()) {
3958 cricket::MediaType media_type = content.media_description()->type();
3959 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3960 media_type == cricket::MEDIA_TYPE_VIDEO) {
3961 auto transceiver = GetAssociatedTransceiver(content.name);
3962 RTC_CHECK(transceiver);
3963 session_options->media_description_options.push_back(
3964 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3965 } else {
3966 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003967 // Reject all data sections if data channels are disabled.
3968 // Reject a data section if it has already been rejected.
3969 // Reject all data sections except for the first one.
3970 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3971 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003972 session_options->media_description_options.push_back(
3973 GetMediaDescriptionOptionsForRejectedData(content.name));
3974 } else {
3975 session_options->media_description_options.push_back(
3976 GetMediaDescriptionOptionsForActiveData(content.name));
3977 }
Steve Antondcc3c022017-12-22 16:02:54 -08003978 }
3979 }
htaa2a49d92016-03-04 02:51:39 -08003980}
3981
zhihuang1c378ed2017-08-17 14:10:50 -07003982void PeerConnection::GenerateMediaDescriptionOptions(
3983 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003984 RtpTransceiverDirection audio_direction,
3985 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003986 absl::optional<size_t>* audio_index,
3987 absl::optional<size_t>* video_index,
3988 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003989 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003990 for (const cricket::ContentInfo& content :
3991 session_desc->description()->contents()) {
3992 if (IsAudioContent(&content)) {
3993 // If we already have an audio m= section, reject this extra one.
3994 if (*audio_index) {
3995 session_options->media_description_options.push_back(
3996 cricket::MediaDescriptionOptions(
3997 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003998 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003999 } else {
4000 session_options->media_description_options.push_back(
4001 cricket::MediaDescriptionOptions(
4002 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004003 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004004 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004005 }
4006 } else if (IsVideoContent(&content)) {
4007 // If we already have an video m= section, reject this extra one.
4008 if (*video_index) {
4009 session_options->media_description_options.push_back(
4010 cricket::MediaDescriptionOptions(
4011 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004012 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004013 } else {
4014 session_options->media_description_options.push_back(
4015 cricket::MediaDescriptionOptions(
4016 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004017 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004018 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004019 }
4020 } else {
4021 RTC_DCHECK(IsDataContent(&content));
4022 // If we already have an data m= section, reject this extra one.
4023 if (*data_index) {
4024 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004025 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004026 } else {
4027 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004028 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004029 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004030 }
4031 }
htaa2a49d92016-03-04 02:51:39 -08004032 }
deadbeefab9b2d12015-10-14 11:33:11 -07004033}
4034
Steve Antonfa2260d2017-12-28 16:38:23 -08004035cricket::MediaDescriptionOptions
4036PeerConnection::GetMediaDescriptionOptionsForActiveData(
4037 const std::string& mid) const {
4038 // Direction for data sections is meaningless, but legacy endpoints might
4039 // expect sendrecv.
4040 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4041 RtpTransceiverDirection::kSendRecv,
4042 /*stopped=*/false);
4043 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4044 return options;
4045}
4046
4047cricket::MediaDescriptionOptions
4048PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4049 const std::string& mid) const {
4050 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4051 RtpTransceiverDirection::kInactive,
4052 /*stopped=*/true);
4053 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4054 return options;
4055}
4056
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004057absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004058 switch (data_channel_type_) {
4059 case cricket::DCT_RTP:
4060 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004061 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004062 }
4063 return rtp_data_channel_->content_name();
4064 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004065 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004066 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004067 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004068 }
4069}
4070
Steve Anton4171afb2017-11-20 10:20:22 -08004071void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4072 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4073 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004074 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004075}
4076
Steve Anton4171afb2017-11-20 10:20:22 -08004077void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004078 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004079 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004080 cricket::MediaType media_type,
4081 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004082 RTC_DCHECK(!IsUnifiedPlan());
4083
Steve Anton4171afb2017-11-20 10:20:22 -08004084 std::vector<RtpSenderInfo>* current_senders =
4085 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004086
Steve Anton4171afb2017-11-20 10:20:22 -08004087 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004088 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004089 for (auto sender_it = current_senders->begin();
4090 sender_it != current_senders->end();
4091 /* incremented manually */) {
4092 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004093 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004094 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004095 std::string params_stream_id;
4096 if (params) {
4097 params_stream_id =
4098 (!params->first_stream_id().empty() ? params->first_stream_id()
4099 : kDefaultStreamId);
4100 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004101 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004102 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004103 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004104 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004105 sender_exists) {
4106 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004107 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004108 OnRemoteSenderRemoved(info, media_type);
4109 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004110 }
4111 }
4112
Steve Anton4171afb2017-11-20 10:20:22 -08004113 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004114 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004115 if (!params.has_ssrcs()) {
4116 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4117 // sender, this means it is coming from a Unified Plan endpoint,so we just
4118 // create a default.
4119 default_sender_needed = true;
4120 break;
4121 }
4122
Seth Hampson845e8782018-03-02 11:34:10 -08004123 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004124 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004125 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4126 // not supported in Plan B, we just take the first here and create the
4127 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004128 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004129 (!params.first_stream_id().empty() ? params.first_stream_id()
4130 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004131 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004132 uint32_t ssrc = params.first_ssrc();
4133
4134 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004135 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004136 if (!stream) {
4137 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004138 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004139 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004140 remote_streams_->AddStream(stream);
4141 new_streams->AddStream(stream);
4142 }
4143
Steve Anton4171afb2017-11-20 10:20:22 -08004144 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004145 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004146 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004147 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004148 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004149 }
4150 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004151
Steve Anton4171afb2017-11-20 10:20:22 -08004152 // Add default sender if necessary.
4153 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004154 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004155 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004156 if (!default_stream) {
4157 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004158 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004159 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004160 remote_streams_->AddStream(default_stream);
4161 new_streams->AddStream(default_stream);
4162 }
Steve Anton4171afb2017-11-20 10:20:22 -08004163 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4164 ? kDefaultAudioSenderId
4165 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004166 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004167 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004168 if (!default_sender_info) {
4169 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004170 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004171 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004172 }
4173 }
deadbeefab9b2d12015-10-14 11:33:11 -07004174}
4175
Steve Anton4171afb2017-11-20 10:20:22 -08004176void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4177 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004178 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4179 << " receiver for track_id=" << sender_info.sender_id
4180 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004181
Steve Anton3d954a62018-04-02 11:27:23 -07004182 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004183 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004184 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004185 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004186 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004187 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004188 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004189 }
4190}
4191
Steve Anton4171afb2017-11-20 10:20:22 -08004192void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4193 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004194 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4195 << " receiver for track_id=" << sender_info.sender_id
4196 << " and stream_id=" << sender_info.stream_id;
4197
Seth Hampson845e8782018-03-02 11:34:10 -08004198 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004199
Henrik Boström933d8b02017-10-10 10:05:16 -07004200 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004201 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004202 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4203 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004204 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004205 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004206 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004207 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004208 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004209 }
4210 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004211 // Stopping or destroying a VideoRtpReceiver will end the
4212 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004213 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004214 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004215 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004216 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004217 // There's no guarantee the track is still available, e.g. the track may
4218 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004219 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004220 }
4221 } else {
nisseede5da42017-01-12 05:15:36 -08004222 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004223 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004224 if (receiver) {
4225 observer_->OnRemoveTrack(receiver);
4226 }
deadbeefab9b2d12015-10-14 11:33:11 -07004227}
4228
4229void PeerConnection::UpdateEndedRemoteMediaStreams() {
4230 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4231 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4232 MediaStreamInterface* stream = remote_streams_->at(i);
4233 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4234 streams_to_remove.push_back(stream);
4235 }
4236 }
4237
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004238 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004239 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004240 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004241 }
4242}
4243
Steve Anton4171afb2017-11-20 10:20:22 -08004244void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004245 const std::vector<cricket::StreamParams>& streams,
4246 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004247 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004248
Seth Hampson845e8782018-03-02 11:34:10 -08004249 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004250 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004251 for (auto sender_it = current_senders->begin();
4252 sender_it != current_senders->end();
4253 /* incremented manually */) {
4254 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004255 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004256 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4257 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004258 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004259 OnLocalSenderRemoved(info, media_type);
4260 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004261 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004262 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004263 }
4264 }
4265
Steve Anton4171afb2017-11-20 10:20:22 -08004266 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004267 for (const cricket::StreamParams& params : streams) {
4268 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004269 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004270 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004271 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004272 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004273 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004274 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004275 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004276 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004277 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004278 }
4279 }
4280}
4281
Steve Anton4171afb2017-11-20 10:20:22 -08004282void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4283 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004284 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004285 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004286 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004287 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4288 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004289 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004290 return;
4291 }
4292
deadbeeffac06552015-11-25 11:26:01 -08004293 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004294 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004295 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004296 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004297 }
deadbeeffac06552015-11-25 11:26:01 -08004298
Seth Hampson5b4f0752018-04-02 16:31:36 -07004299 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004300 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004301}
4302
Steve Anton4171afb2017-11-20 10:20:22 -08004303void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4304 cricket::MediaType media_type) {
4305 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004306 if (!sender) {
4307 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004308 // SessionDescriptions has been renegotiated.
4309 return;
4310 }
deadbeeffac06552015-11-25 11:26:01 -08004311
4312 // A sender has been removed from the SessionDescription but it's still
4313 // associated with the PeerConnection. This only occurs if the SDP doesn't
4314 // match with the calls to CreateSender, AddStream and RemoveStream.
4315 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004316 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004317 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004318 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004319 }
deadbeeffac06552015-11-25 11:26:01 -08004320
Steve Anton4171afb2017-11-20 10:20:22 -08004321 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004322}
4323
4324void PeerConnection::UpdateLocalRtpDataChannels(
4325 const cricket::StreamParamsVec& streams) {
4326 std::vector<std::string> existing_channels;
4327
4328 // Find new and active data channels.
4329 for (const cricket::StreamParams& params : streams) {
4330 // |it->sync_label| is actually the data channel label. The reason is that
4331 // we use the same naming of data channels as we do for
4332 // MediaStreams and Tracks.
4333 // For MediaStreams, the sync_label is the MediaStream label and the
4334 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004335 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004336 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004337 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004338 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004339 continue;
4340 }
4341 // Set the SSRC the data channel should use for sending.
4342 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4343 existing_channels.push_back(data_channel_it->first);
4344 }
4345
4346 UpdateClosingRtpDataChannels(existing_channels, true);
4347}
4348
4349void PeerConnection::UpdateRemoteRtpDataChannels(
4350 const cricket::StreamParamsVec& streams) {
4351 std::vector<std::string> existing_channels;
4352
4353 // Find new and active data channels.
4354 for (const cricket::StreamParams& params : streams) {
4355 // The data channel label is either the mslabel or the SSRC if the mslabel
4356 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004357 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004358 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004359 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004360 auto data_channel_it = rtp_data_channels_.find(label);
4361 if (data_channel_it == rtp_data_channels_.end()) {
4362 // This is a new data channel.
4363 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4364 } else {
4365 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4366 }
4367 existing_channels.push_back(label);
4368 }
4369
4370 UpdateClosingRtpDataChannels(existing_channels, false);
4371}
4372
4373void PeerConnection::UpdateClosingRtpDataChannels(
4374 const std::vector<std::string>& active_channels,
4375 bool is_local_update) {
4376 auto it = rtp_data_channels_.begin();
4377 while (it != rtp_data_channels_.end()) {
4378 DataChannel* data_channel = it->second;
4379 if (std::find(active_channels.begin(), active_channels.end(),
4380 data_channel->label()) != active_channels.end()) {
4381 ++it;
4382 continue;
4383 }
4384
4385 if (is_local_update) {
4386 data_channel->SetSendSsrc(0);
4387 } else {
4388 data_channel->RemotePeerRequestClose();
4389 }
4390
4391 if (data_channel->state() == DataChannel::kClosed) {
4392 rtp_data_channels_.erase(it);
4393 it = rtp_data_channels_.begin();
4394 } else {
4395 ++it;
4396 }
4397 }
4398}
4399
4400void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4401 uint32_t remote_ssrc) {
4402 rtc::scoped_refptr<DataChannel> channel(
4403 InternalCreateDataChannel(label, nullptr));
4404 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004405 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004406 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004407 return;
4408 }
4409 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004410 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4411 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004412 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004413}
4414
4415rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4416 const std::string& label,
4417 const InternalDataChannelInit* config) {
4418 if (IsClosed()) {
4419 return nullptr;
4420 }
Steve Anton75737c02017-11-06 10:37:17 -08004421 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004422 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004423 << "InternalCreateDataChannel: Data is not supported in this call.";
4424 return nullptr;
4425 }
4426 InternalDataChannelInit new_config =
4427 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004428 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004429 if (new_config.id < 0) {
4430 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004431 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004432 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004433 RTC_LOG(LS_ERROR)
4434 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004435 return nullptr;
4436 }
4437 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004438 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004439 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004440 return nullptr;
4441 }
4442 }
4443
Steve Anton75737c02017-11-06 10:37:17 -08004444 rtc::scoped_refptr<DataChannel> channel(
4445 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004446 if (!channel) {
4447 sid_allocator_.ReleaseSid(new_config.id);
4448 return nullptr;
4449 }
4450
4451 if (channel->data_channel_type() == cricket::DCT_RTP) {
4452 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004453 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4454 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004455 return nullptr;
4456 }
4457 rtp_data_channels_[channel->label()] = channel;
4458 } else {
4459 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4460 sctp_data_channels_.push_back(channel);
4461 channel->SignalClosed.connect(this,
4462 &PeerConnection::OnSctpDataChannelClosed);
4463 }
4464
Steve Anton2d8609c2018-01-23 16:38:46 -08004465 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004466 return channel;
4467}
4468
4469bool PeerConnection::HasDataChannels() const {
4470 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4471}
4472
4473void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4474 for (const auto& channel : sctp_data_channels_) {
4475 if (channel->id() < 0) {
4476 int sid;
4477 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004478 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004479 continue;
4480 }
4481 channel->SetSctpSid(sid);
4482 }
4483 }
4484}
4485
4486void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004487 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004488 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4489 ++it) {
4490 if (it->get() == channel) {
4491 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004492 // After the closing procedure is done, it's safe to use this ID for
4493 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004494 sid_allocator_.ReleaseSid(channel->id());
4495 }
deadbeefbd292462015-12-14 18:15:29 -08004496 // Since this method is triggered by a signal from the DataChannel,
4497 // we can't free it directly here; we need to free it asynchronously.
4498 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004499 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004500 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4501 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004502 return;
4503 }
4504 }
4505}
4506
deadbeefab9b2d12015-10-14 11:33:11 -07004507void PeerConnection::OnDataChannelDestroyed() {
4508 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4509 // DataChannel may callback to us and try to modify the list.
4510 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4511 temp_rtp_dcs.swap(rtp_data_channels_);
4512 for (const auto& kv : temp_rtp_dcs) {
4513 kv.second->OnTransportChannelDestroyed();
4514 }
4515
4516 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4517 temp_sctp_dcs.swap(sctp_data_channels_);
4518 for (const auto& channel : temp_sctp_dcs) {
4519 channel->OnTransportChannelDestroyed();
4520 }
4521}
4522
4523void PeerConnection::OnDataChannelOpenMessage(
4524 const std::string& label,
4525 const InternalDataChannelInit& config) {
4526 rtc::scoped_refptr<DataChannel> channel(
4527 InternalCreateDataChannel(label, &config));
4528 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004529 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004530 return;
4531 }
4532
deadbeefa601f5c2016-06-06 14:27:39 -07004533 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4534 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004535 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004536}
4537
Steve Anton4171afb2017-11-20 10:20:22 -08004538rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4539PeerConnection::GetAudioTransceiver() const {
4540 // This method only works with Plan B SDP, where there is a single
4541 // audio/video transceiver.
4542 RTC_DCHECK(!IsUnifiedPlan());
4543 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004544 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004545 return transceiver;
4546 }
4547 }
4548 RTC_NOTREACHED();
4549 return nullptr;
4550}
4551
4552rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4553PeerConnection::GetVideoTransceiver() const {
4554 // This method only works with Plan B SDP, where there is a single
4555 // audio/video transceiver.
4556 RTC_DCHECK(!IsUnifiedPlan());
4557 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004558 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004559 return transceiver;
4560 }
4561 }
4562 RTC_NOTREACHED();
4563 return nullptr;
4564}
4565
4566// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4567// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004568bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004569 switch (type) {
4570 case cricket::MEDIA_TYPE_AUDIO:
4571 return !GetAudioTransceiver()->internal()->senders().empty();
4572 case cricket::MEDIA_TYPE_VIDEO:
4573 return !GetVideoTransceiver()->internal()->senders().empty();
4574 case cricket::MEDIA_TYPE_DATA:
4575 return false;
4576 }
4577 RTC_NOTREACHED();
4578 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004579}
4580
Steve Anton4171afb2017-11-20 10:20:22 -08004581rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4582PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4583 for (auto transceiver : transceivers_) {
4584 for (auto sender : transceiver->internal()->senders()) {
4585 if (sender->track() == track) {
4586 return sender;
4587 }
4588 }
4589 }
4590 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004591}
4592
Steve Anton4171afb2017-11-20 10:20:22 -08004593rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4594PeerConnection::FindSenderById(const std::string& sender_id) const {
4595 for (auto transceiver : transceivers_) {
4596 for (auto sender : transceiver->internal()->senders()) {
4597 if (sender->id() == sender_id) {
4598 return sender;
4599 }
4600 }
4601 }
4602 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004603}
4604
Steve Anton4171afb2017-11-20 10:20:22 -08004605rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4606PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4607 for (auto transceiver : transceivers_) {
4608 for (auto receiver : transceiver->internal()->receivers()) {
4609 if (receiver->id() == receiver_id) {
4610 return receiver;
4611 }
4612 }
4613 }
4614 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004615}
4616
Steve Anton4171afb2017-11-20 10:20:22 -08004617std::vector<PeerConnection::RtpSenderInfo>*
4618PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4619 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4620 media_type == cricket::MEDIA_TYPE_VIDEO);
4621 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4622 ? &remote_audio_sender_infos_
4623 : &remote_video_sender_infos_;
4624}
4625
4626std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004627 cricket::MediaType media_type) {
4628 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4629 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004630 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4631 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004632}
4633
Steve Anton4171afb2017-11-20 10:20:22 -08004634const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4635 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004636 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004637 const std::string sender_id) const {
4638 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004639 if (sender_info.stream_id == stream_id &&
4640 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004641 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004642 }
4643 }
4644 return nullptr;
4645}
4646
4647DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4648 for (const auto& channel : sctp_data_channels_) {
4649 if (channel->id() == sid) {
4650 return channel;
4651 }
4652 }
4653 return nullptr;
4654}
4655
deadbeef91dd5672016-05-18 16:55:30 -07004656bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004657 const RTCConfiguration& configuration) {
4658 cricket::ServerAddresses stun_servers;
4659 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004660 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4661 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004662 return false;
4663 }
4664
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004665 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004666 // To handle both internal and externally created port allocator, we will
4667 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004668 port_allocator_flags_ = port_allocator_->flags();
4669 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4670 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4671 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004672 // If the disable-IPv6 flag was specified, we'll not override it
4673 // by experiment.
4674 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004675 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004676 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4677 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004678 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004679 }
4680
zhihuangb09b3f92017-03-07 14:40:51 -08004681 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004682 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004683 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004684 }
4685
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004686 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004687 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004688 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004689 }
4690
honghaiz60347052016-05-31 18:29:12 -07004691 if (configuration.candidate_network_policy ==
4692 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004693 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004694 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004695 }
4696
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004697 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004698 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004699 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4700 }
4701
Qingsi Wanga2d60672018-04-11 16:57:45 -07004702 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004703 // No step delay is used while allocating ports.
4704 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4705 port_allocator_->set_candidate_filter(
4706 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004707 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004708
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004709 if (tls_cert_verifier_ != nullptr) {
4710 for (auto& turn_server : turn_servers) {
4711 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4712 }
4713 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004714 // Call this last since it may create pooled allocator sessions using the
4715 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004716 port_allocator_->SetConfiguration(
4717 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4718 configuration.prune_turn_ports, configuration.turn_customizer,
4719 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004720 return true;
4721}
4722
deadbeef91dd5672016-05-18 16:55:30 -07004723bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004724 const cricket::ServerAddresses& stun_servers,
4725 const std::vector<cricket::RelayServerConfig>& turn_servers,
4726 IceTransportsType type,
4727 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004728 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004729 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004730 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004731 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004732 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004733 // According to JSEP, after setLocalDescription, changing the candidate pool
4734 // size is not allowed, and changing the set of ICE servers will not result
4735 // in new candidates being gathered.
4736 if (local_description()) {
4737 port_allocator_->FreezeCandidatePool();
4738 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004739 // Call this last since it may create pooled allocator sessions using the
4740 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004741 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004742 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004743 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004744}
4745
Steve Antonba818672017-11-06 10:21:57 -08004746cricket::ChannelManager* PeerConnection::channel_manager() const {
4747 return factory_->channel_manager();
4748}
4749
4750MetricsObserverInterface* PeerConnection::metrics_observer() const {
4751 return uma_observer_;
4752}
4753
Elad Alon99c3fe52017-10-13 16:29:40 +02004754bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004755 std::unique_ptr<RtcEventLogOutput> output,
4756 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004757 if (!event_log_) {
4758 return false;
4759 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004760 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004761}
4762
4763void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004764 if (event_log_) {
4765 event_log_->StopLogging();
4766 }
ivoc14d5dbe2016-07-04 07:06:55 -07004767}
nisseeaabdf62017-05-05 02:23:02 -07004768
Steve Anton75737c02017-11-06 10:37:17 -08004769cricket::BaseChannel* PeerConnection::GetChannel(
4770 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004771 for (auto transceiver : transceivers_) {
4772 cricket::BaseChannel* channel = transceiver->internal()->channel();
4773 if (channel && channel->content_name() == content_name) {
4774 return channel;
4775 }
Steve Anton75737c02017-11-06 10:37:17 -08004776 }
4777 if (rtp_data_channel() &&
4778 rtp_data_channel()->content_name() == content_name) {
4779 return rtp_data_channel();
4780 }
4781 return nullptr;
4782}
4783
4784bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4785 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004786 RTC_LOG(LS_INFO)
4787 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004788 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004789 return false;
4790 }
4791 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004792 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004793 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004794 return false;
4795 }
4796
Zhi Huange830e682018-03-30 10:48:35 -07004797 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4798 if (dtls_role) {
4799 *role = *dtls_role;
4800 return true;
4801 }
4802 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004803}
4804
4805bool PeerConnection::GetSslRole(const std::string& content_name,
4806 rtc::SSLRole* role) {
4807 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004808 RTC_LOG(LS_INFO)
4809 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004810 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004811 return false;
4812 }
4813
Zhi Huange830e682018-03-30 10:48:35 -07004814 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4815 if (dtls_role) {
4816 *role = *dtls_role;
4817 return true;
4818 }
4819 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004820}
4821
Steve Antonf8470812017-12-04 10:46:21 -08004822void PeerConnection::SetSessionError(SessionError error,
4823 const std::string& error_desc) {
4824 RTC_DCHECK_RUN_ON(signaling_thread());
4825 if (error != session_error_) {
4826 session_error_ = error;
4827 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004828 }
4829}
4830
Zhi Huange830e682018-03-30 10:48:35 -07004831RTCError PeerConnection::UpdateSessionState(
4832 SdpType type,
4833 cricket::ContentSource source,
4834 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004835 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004836
4837 // If there's already a pending error then no state transition should happen.
4838 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004839 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004840
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004841 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004842 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004843 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004844 }
4845
4846 // Update the signaling state according to the specified state machine (see
4847 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004848 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004849 ChangeSignalingState(source == cricket::CS_LOCAL
4850 ? PeerConnectionInterface::kHaveLocalOffer
4851 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004852 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004853 ChangeSignalingState(source == cricket::CS_LOCAL
4854 ? PeerConnectionInterface::kHaveLocalPrAnswer
4855 : PeerConnectionInterface::kHaveRemotePrAnswer);
4856 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004857 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004858 ChangeSignalingState(PeerConnectionInterface::kStable);
4859 }
4860
4861 // Update internal objects according to the session description's media
4862 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004863 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004864 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004865 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004866 }
4867
Steve Anton8a006912017-12-04 15:25:56 -08004868 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004869}
4870
Steve Anton8a006912017-12-04 15:25:56 -08004871RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004872 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004873 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004874 const SessionDescriptionInterface* sdesc =
4875 (source == cricket::CS_LOCAL ? local_description()
4876 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004877 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004878
4879 // Push down the new SDP media section for each audio/video transceiver.
4880 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004881 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004882 FindMediaSectionForTransceiver(transceiver, sdesc);
4883 cricket::BaseChannel* channel = transceiver->internal()->channel();
4884 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004885 continue;
4886 }
4887 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004888 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004889 if (!content_desc) {
4890 continue;
4891 }
4892 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004893 bool success = (source == cricket::CS_LOCAL)
4894 ? channel->SetLocalContent(content_desc, type, &error)
4895 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004896 if (!success) {
4897 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4898 }
4899 }
4900
4901 // If using the RtpDataChannel, push down the new SDP section for it too.
4902 if (rtp_data_channel_) {
4903 const ContentInfo* data_content =
4904 cricket::GetFirstDataContent(sdesc->description());
4905 if (data_content && !data_content->rejected) {
4906 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004907 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004908 if (data_desc) {
4909 std::string error;
4910 bool success =
4911 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004912 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004913 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004914 if (!success) {
4915 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4916 std::move(error));
4917 }
Steve Anton75737c02017-11-06 10:37:17 -08004918 }
4919 }
4920 }
Steve Antoned10bd92017-12-05 10:52:59 -08004921
Steve Anton75737c02017-11-06 10:37:17 -08004922 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4923 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4924 if (sctp_transport_ && local_description() && remote_description() &&
4925 cricket::GetFirstDataContent(local_description()->description()) &&
4926 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004927 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004928 RTC_FROM_HERE,
4929 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004930 if (!success) {
4931 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4932 "Failed to push down SCTP parameters.");
4933 }
Steve Anton75737c02017-11-06 10:37:17 -08004934 }
Steve Antoned10bd92017-12-05 10:52:59 -08004935
Steve Anton8a006912017-12-04 15:25:56 -08004936 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004937}
4938
4939bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4940 RTC_DCHECK(network_thread()->IsCurrent());
4941 RTC_DCHECK(local_description());
4942 RTC_DCHECK(remote_description());
4943 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4944 // When we support "max-message-size", that would also be pushed down here.
4945 return sctp_transport_->Start(
4946 GetSctpPort(local_description()->description()),
4947 GetSctpPort(remote_description()->description()));
4948}
4949
Steve Anton8a006912017-12-04 15:25:56 -08004950RTCError PeerConnection::PushdownTransportDescription(
4951 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004952 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004953 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004954
Zhi Huange830e682018-03-30 10:48:35 -07004955 if (source == cricket::CS_LOCAL) {
4956 const SessionDescriptionInterface* sdesc = local_description();
4957 RTC_DCHECK(sdesc);
4958 return transport_controller_->SetLocalDescription(type,
4959 sdesc->description());
4960 } else {
4961 const SessionDescriptionInterface* sdesc = remote_description();
4962 RTC_DCHECK(sdesc);
4963 return transport_controller_->SetRemoteDescription(type,
4964 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004965 }
Steve Anton75737c02017-11-06 10:37:17 -08004966}
4967
4968bool PeerConnection::GetTransportDescription(
4969 const SessionDescription* description,
4970 const std::string& content_name,
4971 cricket::TransportDescription* tdesc) {
4972 if (!description || !tdesc) {
4973 return false;
4974 }
4975 const TransportInfo* transport_info =
4976 description->GetTransportInfoByName(content_name);
4977 if (!transport_info) {
4978 return false;
4979 }
4980 *tdesc = transport_info->description;
4981 return true;
4982}
4983
Steve Anton75737c02017-11-06 10:37:17 -08004984cricket::IceConfig PeerConnection::ParseIceConfig(
4985 const PeerConnectionInterface::RTCConfiguration& config) const {
4986 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004987 switch (config.continual_gathering_policy) {
4988 case PeerConnectionInterface::GATHER_ONCE:
4989 gathering_policy = cricket::GATHER_ONCE;
4990 break;
4991 case PeerConnectionInterface::GATHER_CONTINUALLY:
4992 gathering_policy = cricket::GATHER_CONTINUALLY;
4993 break;
4994 default:
4995 RTC_NOTREACHED();
4996 gathering_policy = cricket::GATHER_ONCE;
4997 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004998
Steve Anton75737c02017-11-06 10:37:17 -08004999 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005000 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5001 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005002 ice_config.prioritize_most_likely_candidate_pairs =
5003 config.prioritize_most_likely_ice_candidate_pairs;
5004 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005005 RTCConfigurationToIceConfigOptionalInt(
5006 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005007 ice_config.continual_gathering_policy = gathering_policy;
5008 ice_config.presume_writable_when_fully_relayed =
5009 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005010 ice_config.ice_check_interval_strong_connectivity =
5011 config.ice_check_interval_strong_connectivity;
5012 ice_config.ice_check_interval_weak_connectivity =
5013 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005014 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005015 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005016 ice_config.regather_all_networks_interval_range =
5017 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005018 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005019 return ice_config;
5020}
5021
Steve Anton75737c02017-11-06 10:37:17 -08005022bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5023 std::string* track_id) {
5024 if (!local_description()) {
5025 return false;
5026 }
5027 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5028 track_id);
5029}
5030
5031bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5032 std::string* track_id) {
5033 if (!remote_description()) {
5034 return false;
5035 }
5036 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5037 track_id);
5038}
5039
5040bool PeerConnection::SendData(const cricket::SendDataParams& params,
5041 const rtc::CopyOnWriteBuffer& payload,
5042 cricket::SendDataResult* result) {
5043 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005044 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005045 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005046 return false;
5047 }
5048 return rtp_data_channel_
5049 ? rtp_data_channel_->SendData(params, payload, result)
5050 : network_thread()->Invoke<bool>(
5051 RTC_FROM_HERE,
5052 Bind(&cricket::SctpTransportInternal::SendData,
5053 sctp_transport_.get(), params, payload, result));
5054}
5055
5056bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5057 if (!rtp_data_channel_ && !sctp_transport_) {
5058 // Don't log an error here, because DataChannels are expected to call
5059 // ConnectDataChannel in this state. It's the only way to initially tell
5060 // whether or not the underlying transport is ready.
5061 return false;
5062 }
5063 if (rtp_data_channel_) {
5064 rtp_data_channel_->SignalReadyToSendData.connect(
5065 webrtc_data_channel, &DataChannel::OnChannelReady);
5066 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5067 &DataChannel::OnDataReceived);
5068 } else {
5069 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5070 &DataChannel::OnChannelReady);
5071 SignalSctpDataReceived.connect(webrtc_data_channel,
5072 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005073 SignalSctpClosingProcedureStartedRemotely.connect(
5074 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5075 SignalSctpClosingProcedureComplete.connect(
5076 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005077 }
5078 return true;
5079}
5080
5081void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5082 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005083 RTC_LOG(LS_ERROR)
5084 << "DisconnectDataChannel called when rtp_data_channel_ and "
5085 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005086 return;
5087 }
5088 if (rtp_data_channel_) {
5089 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5090 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5091 } else {
5092 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5093 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005094 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5095 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005096 }
5097}
5098
5099void PeerConnection::AddSctpDataStream(int sid) {
5100 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005101 RTC_LOG(LS_ERROR)
5102 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005103 return;
5104 }
5105 network_thread()->Invoke<void>(
5106 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5107 sctp_transport_.get(), sid));
5108}
5109
5110void PeerConnection::RemoveSctpDataStream(int sid) {
5111 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005112 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005113 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005114 return;
5115 }
5116 network_thread()->Invoke<void>(
5117 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5118 sctp_transport_.get(), sid));
5119}
5120
5121bool PeerConnection::ReadyToSendData() const {
5122 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5123 sctp_ready_to_send_data_;
5124}
5125
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005126absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005127 if (sctp_mid_ && transport_controller_) {
5128 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5129 if (dtls_transport) {
5130 return dtls_transport->transport_name();
5131 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005132 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005133 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005134 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005135}
5136
Qingsi Wang72a43a12018-02-20 16:03:18 -08005137cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5138 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005139 network_thread()->Invoke<void>(
5140 RTC_FROM_HERE,
5141 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5142 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005143 return candidate_states_list;
5144}
5145
Steve Anton5dfde182018-02-06 10:34:40 -08005146std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5147 const {
5148 std::map<std::string, std::string> transport_names_by_mid;
5149 for (auto transceiver : transceivers_) {
5150 cricket::BaseChannel* channel = transceiver->internal()->channel();
5151 if (channel) {
5152 transport_names_by_mid[channel->content_name()] =
5153 channel->transport_name();
5154 }
Steve Anton75737c02017-11-06 10:37:17 -08005155 }
Steve Anton5dfde182018-02-06 10:34:40 -08005156 if (rtp_data_channel_) {
5157 transport_names_by_mid[rtp_data_channel_->content_name()] =
5158 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005159 }
5160 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005161 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005162 RTC_DCHECK(transport_name);
5163 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005164 }
Steve Anton5dfde182018-02-06 10:34:40 -08005165 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005166}
5167
Steve Anton5dfde182018-02-06 10:34:40 -08005168std::map<std::string, cricket::TransportStats>
5169PeerConnection::GetTransportStatsByNames(
5170 const std::set<std::string>& transport_names) {
5171 if (!network_thread()->IsCurrent()) {
5172 return network_thread()
5173 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5174 RTC_FROM_HERE,
5175 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005176 }
Steve Anton5dfde182018-02-06 10:34:40 -08005177 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5178 for (const std::string& transport_name : transport_names) {
5179 cricket::TransportStats transport_stats;
5180 bool success =
5181 transport_controller_->GetStats(transport_name, &transport_stats);
5182 if (success) {
5183 transport_stats_by_name[transport_name] = std::move(transport_stats);
5184 } else {
5185 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5186 << transport_name;
5187 }
5188 }
5189 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005190}
5191
5192bool PeerConnection::GetLocalCertificate(
5193 const std::string& transport_name,
5194 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005195 if (!certificate) {
5196 return false;
5197 }
5198 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5199 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005200}
5201
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005202std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005203 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005204 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005205}
5206
5207cricket::DataChannelType PeerConnection::data_channel_type() const {
5208 return data_channel_type_;
5209}
5210
5211bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5212 return pending_ice_restarts_.find(content_name) !=
5213 pending_ice_restarts_.end();
5214}
5215
Steve Anton75737c02017-11-06 10:37:17 -08005216bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5217 return transport_controller_->NeedsIceRestart(content_name);
5218}
5219
5220void PeerConnection::OnCertificateReady(
5221 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5222 transport_controller_->SetLocalCertificate(certificate);
5223}
5224
5225void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005226 SetSessionError(SessionError::kTransport,
5227 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005228}
5229
5230void PeerConnection::OnTransportControllerConnectionState(
5231 cricket::IceConnectionState state) {
5232 switch (state) {
5233 case cricket::kIceConnectionConnecting:
5234 // If the current state is Connected or Completed, then there were
5235 // writable channels but now there are not, so the next state must
5236 // be Disconnected.
5237 // kIceConnectionConnecting is currently used as the default,
5238 // un-connected state by the TransportController, so its only use is
5239 // detecting disconnections.
5240 if (ice_connection_state_ ==
5241 PeerConnectionInterface::kIceConnectionConnected ||
5242 ice_connection_state_ ==
5243 PeerConnectionInterface::kIceConnectionCompleted) {
5244 SetIceConnectionState(
5245 PeerConnectionInterface::kIceConnectionDisconnected);
5246 }
5247 break;
5248 case cricket::kIceConnectionFailed:
5249 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5250 break;
5251 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005252 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005253 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005254 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005255 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005256 break;
5257 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005258 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005259 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005260 if (ice_connection_state_ !=
5261 PeerConnectionInterface::kIceConnectionConnected) {
5262 // If jumping directly from "checking" to "connected",
5263 // signal "connected" first.
5264 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5265 }
5266 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005267 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005268 if (metrics_observer()) {
5269 ReportTransportStats();
5270 }
5271 break;
5272 default:
5273 RTC_NOTREACHED();
5274 }
5275}
5276
5277void PeerConnection::OnTransportControllerCandidatesGathered(
5278 const std::string& transport_name,
5279 const cricket::Candidates& candidates) {
5280 RTC_DCHECK(signaling_thread()->IsCurrent());
5281 int sdp_mline_index;
5282 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005283 RTC_LOG(LS_ERROR)
5284 << "OnTransportControllerCandidatesGathered: content name "
5285 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005286 return;
5287 }
5288
5289 for (cricket::Candidates::const_iterator citer = candidates.begin();
5290 citer != candidates.end(); ++citer) {
5291 // Use transport_name as the candidate media id.
5292 std::unique_ptr<JsepIceCandidate> candidate(
5293 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5294 if (local_description()) {
5295 mutable_local_description()->AddCandidate(candidate.get());
5296 }
5297 OnIceCandidate(std::move(candidate));
5298 }
5299}
5300
5301void PeerConnection::OnTransportControllerCandidatesRemoved(
5302 const std::vector<cricket::Candidate>& candidates) {
5303 RTC_DCHECK(signaling_thread()->IsCurrent());
5304 // Sanity check.
5305 for (const cricket::Candidate& candidate : candidates) {
5306 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005307 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005308 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005309 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005310 return;
5311 }
5312 }
5313
5314 if (local_description()) {
5315 mutable_local_description()->RemoveCandidates(candidates);
5316 }
5317 OnIceCandidatesRemoved(candidates);
5318}
5319
5320void PeerConnection::OnTransportControllerDtlsHandshakeError(
5321 rtc::SSLHandshakeError error) {
5322 if (metrics_observer()) {
5323 metrics_observer()->IncrementEnumCounter(
5324 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5325 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5326 }
5327}
5328
Steve Antoned10bd92017-12-05 10:52:59 -08005329void PeerConnection::EnableSending() {
5330 for (auto transceiver : transceivers_) {
5331 cricket::BaseChannel* channel = transceiver->internal()->channel();
5332 if (channel && !channel->enabled()) {
5333 channel->Enable(true);
5334 }
Steve Anton75737c02017-11-06 10:37:17 -08005335 }
5336
Steve Anton4171afb2017-11-20 10:20:22 -08005337 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005338 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005339 }
Steve Anton75737c02017-11-06 10:37:17 -08005340}
5341
5342// Returns the media index for a local ice candidate given the content name.
5343bool PeerConnection::GetLocalCandidateMediaIndex(
5344 const std::string& content_name,
5345 int* sdp_mline_index) {
5346 if (!local_description() || !sdp_mline_index) {
5347 return false;
5348 }
5349
5350 bool content_found = false;
5351 const ContentInfos& contents = local_description()->description()->contents();
5352 for (size_t index = 0; index < contents.size(); ++index) {
5353 if (contents[index].name == content_name) {
5354 *sdp_mline_index = static_cast<int>(index);
5355 content_found = true;
5356 break;
5357 }
5358 }
5359 return content_found;
5360}
5361
5362bool PeerConnection::UseCandidatesInSessionDescription(
5363 const SessionDescriptionInterface* remote_desc) {
5364 if (!remote_desc) {
5365 return true;
5366 }
5367 bool ret = true;
5368
5369 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5370 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5371 for (size_t n = 0; n < candidates->count(); ++n) {
5372 const IceCandidateInterface* candidate = candidates->at(n);
5373 bool valid = false;
5374 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5375 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005376 RTC_LOG(LS_INFO)
5377 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005378 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005379 }
5380 continue;
5381 }
5382 ret = UseCandidate(candidate);
5383 if (!ret) {
5384 break;
5385 }
5386 }
5387 }
5388 return ret;
5389}
5390
5391bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5392 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5393 size_t remote_content_size =
5394 remote_description()->description()->contents().size();
5395 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005396 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005397 return false;
5398 }
5399
5400 cricket::ContentInfo content =
5401 remote_description()->description()->contents()[mediacontent_index];
5402 std::vector<cricket::Candidate> candidates;
5403 candidates.push_back(candidate->candidate());
5404 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005405 RTCError error =
5406 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005407 if (error.ok()) {
5408 // Candidates successfully submitted for checking.
5409 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5410 ice_connection_state_ ==
5411 PeerConnectionInterface::kIceConnectionDisconnected) {
5412 // If state is New, then the session has just gotten its first remote ICE
5413 // candidates, so go to Checking.
5414 // If state is Disconnected, the session is re-using old candidates or
5415 // receiving additional ones, so go to Checking.
5416 // If state is Connected, stay Connected.
5417 // TODO(bemasc): If state is Connected, and the new candidates are for a
5418 // newly added transport, then the state actually _should_ move to
5419 // checking. Add a way to distinguish that case.
5420 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5421 }
5422 // TODO(bemasc): If state is Completed, go back to Connected.
5423 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005424 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005425 }
5426 return true;
5427}
5428
5429void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005430 // Destroy video channel first since it may have a pointer to the
5431 // voice channel.
5432 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005433 if (!video_info || video_info->rejected) {
5434 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005435 }
5436
Steve Anton6fec8802017-12-04 10:37:29 -08005437 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5438 if (!audio_info || audio_info->rejected) {
5439 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005440 }
5441
5442 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5443 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005444 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005445 }
5446}
5447
Steve Antondcc3c022017-12-22 16:02:54 -08005448RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5449 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005450 const cricket::ContentGroup* bundle_group = nullptr;
5451 if (configuration_.bundle_policy ==
5452 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005453 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005454 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005455 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5456 "max-bundle configured but session description "
5457 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005458 }
5459 }
Steve Antondcc3c022017-12-22 16:02:54 -08005460 return std::move(bundle_group);
5461}
5462
5463RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005464 // Creating the media channels. Transports should already have been created
5465 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005466 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005467 if (voice && !voice->rejected &&
5468 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005469 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005470 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005471 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5472 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005473 }
5474 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5475 }
5476
Steve Antondcc3c022017-12-22 16:02:54 -08005477 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005478 if (video && !video->rejected &&
5479 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005480 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005481 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005482 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5483 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005484 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005485 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005486 }
5487
Steve Antondcc3c022017-12-22 16:02:54 -08005488 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005489 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5490 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005491 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005492 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5493 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005494 }
5495 }
5496
Steve Anton8a006912017-12-04 15:25:56 -08005497 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005498}
5499
Steve Anton4171afb2017-11-20 10:20:22 -08005500// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005501cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005502 const std::string& mid) {
5503 RtpTransportInternal* rtp_transport =
5504 transport_controller_->GetRtpTransport(mid);
5505 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005506 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005507 call_.get(), configuration_.media_config, rtp_transport,
5508 signaling_thread(), mid, SrtpRequired(),
5509 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005510 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005511 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005512 }
Steve Anton75737c02017-11-06 10:37:17 -08005513 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5514 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005515 voice_channel->SignalSentPacket.connect(this,
5516 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005517 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005518 if (uma_observer_) {
5519 voice_channel->SetMetricsObserver(uma_observer_);
5520 }
Steve Anton4171afb2017-11-20 10:20:22 -08005521
Steve Antoneda6ccd2017-12-04 10:21:55 -08005522 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005523}
5524
Steve Anton4171afb2017-11-20 10:20:22 -08005525// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005526cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005527 const std::string& mid) {
5528 RtpTransportInternal* rtp_transport =
5529 transport_controller_->GetRtpTransport(mid);
5530 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005531 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005532 call_.get(), configuration_.media_config, rtp_transport,
5533 signaling_thread(), mid, SrtpRequired(),
5534 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005535 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005536 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005537 }
Steve Anton75737c02017-11-06 10:37:17 -08005538 video_channel->SignalDtlsSrtpSetupFailure.connect(
5539 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005540 video_channel->SignalSentPacket.connect(this,
5541 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005542 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005543 if (uma_observer_) {
5544 video_channel->SetMetricsObserver(uma_observer_);
5545 }
Steve Anton4171afb2017-11-20 10:20:22 -08005546
Steve Antoneda6ccd2017-12-04 10:21:55 -08005547 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005548}
5549
Zhi Huange830e682018-03-30 10:48:35 -07005550bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005551 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5552 if (sctp) {
5553 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005554 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005555 << "Trying to create SCTP transport, but didn't compile with "
5556 "SCTP support (HAVE_SCTP)";
5557 return false;
5558 }
5559 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005560 RTC_FROM_HERE,
5561 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005562 return false;
5563 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005564 for (const auto& channel : sctp_data_channels_) {
5565 channel->OnTransportChannelCreated();
5566 }
Steve Anton75737c02017-11-06 10:37:17 -08005567 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005568 RtpTransportInternal* rtp_transport =
5569 transport_controller_->GetRtpTransport(mid);
5570 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005571 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005572 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5573 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005574 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005575 return false;
5576 }
Steve Anton75737c02017-11-06 10:37:17 -08005577 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5578 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5579 rtp_data_channel_->SignalSentPacket.connect(
5580 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005581 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005582 if (uma_observer_) {
5583 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5584 }
Steve Anton75737c02017-11-06 10:37:17 -08005585 }
5586
Steve Anton75737c02017-11-06 10:37:17 -08005587 return true;
5588}
5589
5590Call::Stats PeerConnection::GetCallStats() {
5591 if (!worker_thread()->IsCurrent()) {
5592 return worker_thread()->Invoke<Call::Stats>(
5593 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5594 }
5595 if (call_) {
5596 return call_->GetStats();
5597 } else {
5598 return Call::Stats();
5599 }
5600}
5601
Zhi Huange830e682018-03-30 10:48:35 -07005602bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005603 RTC_DCHECK(network_thread()->IsCurrent());
5604 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005605 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005606 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005607 RTC_DCHECK(dtls_transport);
5608 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005609 RTC_DCHECK(sctp_transport_);
5610 sctp_invoker_.reset(new rtc::AsyncInvoker());
5611 sctp_transport_->SignalReadyToSendData.connect(
5612 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5613 sctp_transport_->SignalDataReceived.connect(
5614 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005615 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5616 // another thread. Would be nice if there was a helper class similar to
5617 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5618 // code.
5619 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5620 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5621 sctp_transport_->SignalClosingProcedureComplete.connect(
5622 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005623 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005624 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005625 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005626}
5627
5628void PeerConnection::DestroySctpTransport_n() {
5629 RTC_DCHECK(network_thread()->IsCurrent());
5630 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005631 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005632 sctp_invoker_.reset(nullptr);
5633 sctp_ready_to_send_data_ = false;
5634}
5635
5636void PeerConnection::OnSctpTransportReadyToSendData_n() {
5637 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5638 RTC_DCHECK(network_thread()->IsCurrent());
5639 // Note: Cannot use rtc::Bind here because it will grab a reference to
5640 // PeerConnection and potentially cause PeerConnection to live longer than
5641 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5642 // be destroyed before PeerConnection is destroyed, and at that point all
5643 // pending tasks will be cleared.
5644 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5645 OnSctpTransportReadyToSendData_s(true);
5646 });
5647}
5648
5649void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5650 RTC_DCHECK(signaling_thread()->IsCurrent());
5651 sctp_ready_to_send_data_ = ready;
5652 SignalSctpReadyToSendData(ready);
5653}
5654
5655void PeerConnection::OnSctpTransportDataReceived_n(
5656 const cricket::ReceiveDataParams& params,
5657 const rtc::CopyOnWriteBuffer& payload) {
5658 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5659 RTC_DCHECK(network_thread()->IsCurrent());
5660 // Note: Cannot use rtc::Bind here because it will grab a reference to
5661 // PeerConnection and potentially cause PeerConnection to live longer than
5662 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5663 // be destroyed before PeerConnection is destroyed, and at that point all
5664 // pending tasks will be cleared.
5665 sctp_invoker_->AsyncInvoke<void>(
5666 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5667 OnSctpTransportDataReceived_s(params, payload);
5668 });
5669}
5670
5671void PeerConnection::OnSctpTransportDataReceived_s(
5672 const cricket::ReceiveDataParams& params,
5673 const rtc::CopyOnWriteBuffer& payload) {
5674 RTC_DCHECK(signaling_thread()->IsCurrent());
5675 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5676 // Received OPEN message; parse and signal that a new data channel should
5677 // be created.
5678 std::string label;
5679 InternalDataChannelInit config;
5680 config.id = params.ssrc;
5681 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005682 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5683 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005684 return;
5685 }
5686 config.open_handshake_role = InternalDataChannelInit::kAcker;
5687 OnDataChannelOpenMessage(label, config);
5688 } else {
5689 // Otherwise just forward the signal.
5690 SignalSctpDataReceived(params, payload);
5691 }
5692}
5693
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005694void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005695 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5696 RTC_DCHECK(network_thread()->IsCurrent());
5697 sctp_invoker_->AsyncInvoke<void>(
5698 RTC_FROM_HERE, signaling_thread(),
5699 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005700 &SignalSctpClosingProcedureStartedRemotely, sid));
5701}
5702
5703void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5704 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5705 RTC_DCHECK(network_thread()->IsCurrent());
5706 sctp_invoker_->AsyncInvoke<void>(
5707 RTC_FROM_HERE, signaling_thread(),
5708 rtc::Bind(&sigslot::signal1<int>::operator(),
5709 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005710}
5711
5712// Returns false if bundle is enabled and rtcp_mux is disabled.
5713bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5714 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5715 if (!bundle_enabled)
5716 return true;
5717
5718 const cricket::ContentGroup* bundle_group =
5719 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5720 RTC_DCHECK(bundle_group != NULL);
5721
5722 const cricket::ContentInfos& contents = desc->contents();
5723 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5724 citer != contents.end(); ++citer) {
5725 const cricket::ContentInfo* content = (&*citer);
5726 RTC_DCHECK(content != NULL);
5727 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005728 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005729 if (!HasRtcpMuxEnabled(content))
5730 return false;
5731 }
5732 }
5733 // RTCP-MUX is enabled in all the contents.
5734 return true;
5735}
5736
5737bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005738 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005739}
5740
Steve Anton8a006912017-12-04 15:25:56 -08005741RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005742 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005743 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005744 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005745 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005746 }
5747
5748 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005749 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
5751
Steve Anton3828c062017-12-06 10:34:51 -08005752 SdpType type = sdesc->GetType();
5753 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5754 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005755 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005756 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005757 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005758 }
5759
5760 // Verify crypto settings.
5761 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005762 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5763 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005764 RTCError crypto_error =
5765 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005766 if (!crypto_error.ok()) {
5767 return crypto_error;
5768 }
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
5770
5771 // Verify ice-ufrag and ice-pwd.
5772 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005773 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5774 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
5776
5777 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005778 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5779 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005780 }
5781
5782 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5783 // m-lines that do not rtcp-mux enabled.
5784
5785 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005786 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005787 // With an answer we want to compare the new answer session description with
5788 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005789 const cricket::SessionDescription* offer_desc =
5790 (source == cricket::CS_LOCAL) ? remote_description()->description()
5791 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005792 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5793 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5794 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005795 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5796 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005797 }
5798 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005799 // The re-offers should respect the order of m= sections in current
5800 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005801 // With a re-offer, either the current local or current remote descriptions
5802 // could be the most up to date, so we would like to check against both of
5803 // them if they exist. It could be the case that one of them has a 0 port
5804 // for a media section, but the other does not. This is important to check
5805 // against in the case that we are recycling an m= section.
5806 const cricket::SessionDescription* current_desc = nullptr;
5807 const cricket::SessionDescription* secondary_current_desc = nullptr;
5808 if (local_description()) {
5809 current_desc = local_description()->description();
5810 if (remote_description()) {
5811 secondary_current_desc = remote_description()->description();
5812 }
5813 } else if (remote_description()) {
5814 current_desc = remote_description()->description();
5815 }
Steve Anton75737c02017-11-06 10:37:17 -08005816 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005817 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5818 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005819 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5820 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005821 }
5822 }
5823
Steve Antonba42e992018-04-09 14:10:01 -07005824 if (IsUnifiedPlan()) {
5825 // Ensure that each audio and video media section has at most one
5826 // "StreamParams". This will return an error if receiving a session
5827 // description from a "Plan B" endpoint which adds multiple tracks of the
5828 // same type. With Unified Plan, there can only be at most one track per
5829 // media section.
5830 for (const ContentInfo& content : sdesc->description()->contents()) {
5831 const MediaContentDescription& desc = *content.description;
5832 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5833 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5834 desc.streams().size() > 1u) {
5835 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5836 "Media section has more than one track specified "
5837 "with a=ssrc lines which is not supported with "
5838 "Unified Plan.");
5839 }
5840 }
5841 }
5842
Steve Anton8a006912017-12-04 15:25:56 -08005843 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005844}
5845
Steve Anton3828c062017-12-06 10:34:51 -08005846bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005847 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005848 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005849 return (state == PeerConnectionInterface::kStable) ||
5850 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005851 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005852 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005853 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5854 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5855 }
5856}
5857
Steve Anton3828c062017-12-06 10:34:51 -08005858bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005859 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005860 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005861 return (state == PeerConnectionInterface::kStable) ||
5862 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005863 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005864 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005865 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5866 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5867 }
5868}
5869
Steve Antonf8470812017-12-04 10:46:21 -08005870const char* PeerConnection::SessionErrorToString(SessionError error) const {
5871 switch (error) {
5872 case SessionError::kNone:
5873 return "ERROR_NONE";
5874 case SessionError::kContent:
5875 return "ERROR_CONTENT";
5876 case SessionError::kTransport:
5877 return "ERROR_TRANSPORT";
5878 }
5879 RTC_NOTREACHED();
5880 return "";
5881}
5882
Steve Anton75737c02017-11-06 10:37:17 -08005883std::string PeerConnection::GetSessionErrorMsg() {
5884 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005885 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5886 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005887 return desc.str();
5888}
5889
Steve Anton8e20f172018-03-06 10:55:04 -08005890void PeerConnection::ReportSdpFormatReceived(
5891 const SessionDescriptionInterface& remote_offer) {
5892 if (!uma_observer_) {
5893 return;
5894 }
5895 int num_audio_mlines = 0;
5896 int num_video_mlines = 0;
5897 int num_audio_tracks = 0;
5898 int num_video_tracks = 0;
5899 for (const ContentInfo& content : remote_offer.description()->contents()) {
5900 cricket::MediaType media_type = content.media_description()->type();
5901 int num_tracks = std::max(
5902 1, static_cast<int>(content.media_description()->streams().size()));
5903 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5904 num_audio_mlines += 1;
5905 num_audio_tracks += num_tracks;
5906 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5907 num_video_mlines += 1;
5908 num_video_tracks += num_tracks;
5909 }
5910 }
5911 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5912 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5913 format = kSdpFormatReceivedComplexUnifiedPlan;
5914 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5915 format = kSdpFormatReceivedComplexPlanB;
5916 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5917 format = kSdpFormatReceivedSimple;
5918 }
5919 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5920 kSdpFormatReceivedMax);
5921}
5922
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005923void PeerConnection::NoteUsageEvent(UsageEvent event) {
5924 RTC_DCHECK_RUN_ON(signaling_thread());
5925 usage_event_accumulator_ |= static_cast<int>(event);
5926}
5927
5928void PeerConnection::ReportUsagePattern() const {
5929 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5930 if (uma_observer_) {
5931 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5932 usage_event_accumulator_);
5933 }
5934}
5935
Steve Anton0ffaaa22018-02-23 10:31:30 -08005936void PeerConnection::ReportNegotiatedSdpSemantics(
5937 const SessionDescriptionInterface& answer) {
5938 if (!uma_observer_) {
5939 return;
5940 }
5941 switch (answer.description()->msid_signaling()) {
5942 case 0:
5943 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5944 kSdpSemanticNegotiatedNone,
5945 kSdpSemanticNegotiatedMax);
5946 break;
5947 case cricket::kMsidSignalingMediaSection:
5948 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5949 kSdpSemanticNegotiatedUnifiedPlan,
5950 kSdpSemanticNegotiatedMax);
5951 break;
5952 case cricket::kMsidSignalingSsrcAttribute:
5953 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5954 kSdpSemanticNegotiatedPlanB,
5955 kSdpSemanticNegotiatedMax);
5956 break;
5957 case cricket::kMsidSignalingMediaSection |
5958 cricket::kMsidSignalingSsrcAttribute:
5959 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5960 kSdpSemanticNegotiatedMixed,
5961 kSdpSemanticNegotiatedMax);
5962 break;
5963 default:
5964 RTC_NOTREACHED();
5965 }
5966}
5967
Steve Anton75737c02017-11-06 10:37:17 -08005968// We need to check the local/remote description for the Transport instead of
5969// the session, because a new Transport added during renegotiation may have
5970// them unset while the session has them set from the previous negotiation.
5971// Not doing so may trigger the auto generation of transport description and
5972// mess up DTLS identity information, ICE credential, etc.
5973bool PeerConnection::ReadyToUseRemoteCandidate(
5974 const IceCandidateInterface* candidate,
5975 const SessionDescriptionInterface* remote_desc,
5976 bool* valid) {
5977 *valid = true;
5978
5979 const SessionDescriptionInterface* current_remote_desc =
5980 remote_desc ? remote_desc : remote_description();
5981
5982 if (!current_remote_desc) {
5983 return false;
5984 }
5985
5986 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5987 size_t remote_content_size =
5988 current_remote_desc->description()->contents().size();
5989 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005990 RTC_LOG(LS_ERROR)
5991 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5992 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005993
5994 *valid = false;
5995 return false;
5996 }
5997
5998 cricket::ContentInfo content =
5999 current_remote_desc->description()->contents()[mediacontent_index];
6000
6001 const std::string transport_name = GetTransportName(content.name);
6002 if (transport_name.empty()) {
6003 return false;
6004 }
Zhi Huange830e682018-03-30 10:48:35 -07006005 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006006}
6007
6008bool PeerConnection::SrtpRequired() const {
6009 return dtls_enabled_ ||
6010 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6011}
6012
6013void PeerConnection::OnTransportControllerGatheringState(
6014 cricket::IceGatheringState state) {
6015 RTC_DCHECK(signaling_thread()->IsCurrent());
6016 if (state == cricket::kIceGatheringGathering) {
6017 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6018 } else if (state == cricket::kIceGatheringComplete) {
6019 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6020 }
6021}
6022
6023void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006024 std::map<std::string, std::set<cricket::MediaType>>
6025 media_types_by_transport_name;
6026 for (auto transceiver : transceivers_) {
6027 if (transceiver->internal()->channel()) {
6028 const std::string& transport_name =
6029 transceiver->internal()->channel()->transport_name();
6030 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006031 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006032 }
Steve Anton75737c02017-11-06 10:37:17 -08006033 }
6034 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006035 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6036 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006037 }
Zhi Huange830e682018-03-30 10:48:35 -07006038
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006039 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006040 if (transport_name) {
6041 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006042 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006043 }
Zhi Huange830e682018-03-30 10:48:35 -07006044
Steve Antonc7b964c2018-02-01 14:39:45 -08006045 for (const auto& entry : media_types_by_transport_name) {
6046 const std::string& transport_name = entry.first;
6047 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006048 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006049 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006050 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006051 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006052 }
6053 }
6054}
6055// Walk through the ConnectionInfos to gather best connection usage
6056// for IPv4 and IPv6.
6057void PeerConnection::ReportBestConnectionState(
6058 const cricket::TransportStats& stats) {
6059 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006060 for (const cricket::TransportChannelStats& channel_stats :
6061 stats.channel_stats) {
6062 for (const cricket::ConnectionInfo& connection_info :
6063 channel_stats.connection_infos) {
6064 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006065 continue;
6066 }
6067
6068 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006069 const cricket::Candidate& local = connection_info.local_candidate;
6070 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006071
6072 // Increment the counter for IceCandidatePairType.
6073 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6074 (local.type() == RELAY_PORT_TYPE &&
6075 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6076 type = kEnumCounterIceCandidatePairTypeTcp;
6077 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6078 type = kEnumCounterIceCandidatePairTypeUdp;
6079 } else {
6080 RTC_CHECK(0);
6081 }
6082 metrics_observer()->IncrementEnumCounter(
6083 type, GetIceCandidatePairCounter(local, remote),
6084 kIceCandidatePairMax);
6085
6086 // Increment the counter for IP type.
6087 if (local.address().family() == AF_INET) {
6088 metrics_observer()->IncrementEnumCounter(
6089 kEnumCounterAddressFamily, kBestConnections_IPv4,
6090 kPeerConnectionAddressFamilyCounter_Max);
6091
6092 } else if (local.address().family() == AF_INET6) {
6093 metrics_observer()->IncrementEnumCounter(
6094 kEnumCounterAddressFamily, kBestConnections_IPv6,
6095 kPeerConnectionAddressFamilyCounter_Max);
6096 } else {
6097 RTC_CHECK(0);
6098 }
6099
6100 return;
6101 }
6102 }
6103}
6104
6105void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006106 const cricket::TransportStats& stats,
6107 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006108 RTC_DCHECK(metrics_observer());
6109 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6110 return;
6111 }
6112
6113 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6114 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6115 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6116 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6117 return;
6118 }
6119
Steve Antonc7b964c2018-02-01 14:39:45 -08006120 for (cricket::MediaType media_type : media_types) {
6121 PeerConnectionEnumCounterType srtp_counter_type;
6122 PeerConnectionEnumCounterType ssl_counter_type;
6123 switch (media_type) {
6124 case cricket::MEDIA_TYPE_AUDIO:
6125 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6126 ssl_counter_type = kEnumCounterAudioSslCipher;
6127 break;
6128 case cricket::MEDIA_TYPE_VIDEO:
6129 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6130 ssl_counter_type = kEnumCounterVideoSslCipher;
6131 break;
6132 case cricket::MEDIA_TYPE_DATA:
6133 srtp_counter_type = kEnumCounterDataSrtpCipher;
6134 ssl_counter_type = kEnumCounterDataSslCipher;
6135 break;
6136 default:
6137 RTC_NOTREACHED();
6138 continue;
6139 }
6140 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6141 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6142 srtp_crypto_suite);
6143 }
6144 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6145 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6146 ssl_cipher_suite);
6147 }
Steve Anton75737c02017-11-06 10:37:17 -08006148 }
6149}
6150
6151void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6152 RTC_DCHECK(worker_thread()->IsCurrent());
6153 RTC_DCHECK(call_);
6154 call_->OnSentPacket(sent_packet);
6155}
6156
6157const std::string PeerConnection::GetTransportName(
6158 const std::string& content_name) {
6159 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006160 if (channel) {
6161 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006162 }
Steve Anton6fec8802017-12-04 10:37:29 -08006163 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006164 RTC_DCHECK(sctp_mid_);
6165 if (content_name == *sctp_mid_) {
6166 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006167 }
6168 }
6169 // Return an empty string if failed to retrieve the transport name.
6170 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006171}
6172
Steve Anton6fec8802017-12-04 10:37:29 -08006173void PeerConnection::DestroyTransceiverChannel(
6174 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6175 transceiver) {
6176 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006177
Steve Anton6fec8802017-12-04 10:37:29 -08006178 cricket::BaseChannel* channel = transceiver->internal()->channel();
6179 if (channel) {
6180 transceiver->internal()->SetChannel(nullptr);
6181 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006182 }
6183}
6184
6185void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006186 if (rtp_data_channel_) {
6187 OnDataChannelDestroyed();
6188 DestroyBaseChannel(rtp_data_channel_);
6189 rtp_data_channel_ = nullptr;
6190 }
6191
6192 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6193 // grab a reference to this PeerConnection. If this is called from the
6194 // PeerConnection destructor, the RefCountedObject vtable will have already
6195 // been destroyed (since it is a subclass of PeerConnection) and using
6196 // rtc::Bind will cause "Pure virtual function called" error to appear.
6197
6198 if (sctp_transport_) {
6199 OnDataChannelDestroyed();
6200 network_thread()->Invoke<void>(RTC_FROM_HERE,
6201 [this] { DestroySctpTransport_n(); });
6202 }
6203}
6204
6205void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6206 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006207 switch (channel->media_type()) {
6208 case cricket::MEDIA_TYPE_AUDIO:
6209 channel_manager()->DestroyVoiceChannel(
6210 static_cast<cricket::VoiceChannel*>(channel));
6211 break;
6212 case cricket::MEDIA_TYPE_VIDEO:
6213 channel_manager()->DestroyVideoChannel(
6214 static_cast<cricket::VideoChannel*>(channel));
6215 break;
6216 case cricket::MEDIA_TYPE_DATA:
6217 channel_manager()->DestroyRtpDataChannel(
6218 static_cast<cricket::RtpDataChannel*>(channel));
6219 break;
6220 default:
6221 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6222 break;
6223 }
Zhi Huange830e682018-03-30 10:48:35 -07006224}
Steve Anton6fec8802017-12-04 10:37:29 -08006225
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006226bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006227 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006228 RtpTransportInternal* rtp_transport,
6229 cricket::DtlsTransportInternal* dtls_transport) {
6230 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006231 auto base_channel = GetChannel(mid);
6232 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006233 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006234 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006235 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006236 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006237 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006238 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006239}
6240
Harald Alvestrand89061872018-01-02 14:08:34 +01006241void PeerConnection::ClearStatsCache() {
6242 if (stats_collector_) {
6243 stats_collector_->ClearCachedStatsReport();
6244 }
6245}
6246
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006247} // namespace webrtc