blob: 0a984a703f8c92a4de78b40f3d79b5a177e51b93 [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)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100127 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700145 if (current_streams->find(new_stream->id()) != nullptr) {
146 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100385void NoteKeyProtocolAndMedia(
386 KeyExchangeProtocolType protocol_type,
387 cricket::MediaType media_type,
388 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
389 if (!uma_observer)
390 return;
391 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
392 protocol_type,
393 webrtc::kEnumCounterKeyProtocolMax);
394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
412 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
413 it->second,
414 kEnumCounterKeyProtocolMediaTypeMax);
415 }
416}
417
Steve Anton75737c02017-11-06 10:37:17 -0800418// Checks that each non-rejected content has SDES crypto keys or a DTLS
419// fingerprint, unless it's in a BUNDLE group, in which case only the
420// BUNDLE-tag section (first media section/description in the BUNDLE group)
421// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
422// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
423// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100424RTCError VerifyCrypto(const SessionDescription* desc,
425 bool dtls_enabled,
426 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800431 continue;
432 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Seth Hampson5b4f0752018-04-02 16:31:36 -0700603std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
604 std::string output = "streams=[";
605 const char* separator = "";
606 for (const auto& stream_id : stream_ids) {
607 output.append(separator).append(stream_id);
608 separator = ", ";
609 }
610 output.append("]");
611 return output;
612}
613
Qingsi Wang866e08d2018-03-22 17:54:23 -0700614rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
618 return rtc::nullopt;
619 }
620 return rtc_configuration_parameter;
621}
622
Steve Anton75737c02017-11-06 10:37:17 -0800623} // namespace
624
Henrik Boström31638672017-11-23 17:48:32 +0100625// Upon completion, posts a task to execute the callback of the
626// SetSessionDescriptionObserver asynchronously on the same thread. At this
627// point, the state of the peer connection might no longer reflect the effects
628// of the SetRemoteDescription operation, as the peer connection could have been
629// modified during the post.
630// TODO(hbos): Remove this class once we remove the version of
631// PeerConnectionInterface::SetRemoteDescription() that takes a
632// SetSessionDescriptionObserver as an argument.
633class PeerConnection::SetRemoteDescriptionObserverAdapter
634 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
635 public:
636 SetRemoteDescriptionObserverAdapter(
637 rtc::scoped_refptr<PeerConnection> pc,
638 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
639 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
640
641 // SetRemoteDescriptionObserverInterface implementation.
642 void OnSetRemoteDescriptionComplete(RTCError error) override {
643 if (error.ok())
644 pc_->PostSetSessionDescriptionSuccess(wrapper_);
645 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100646 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100647 }
648
649 private:
650 rtc::scoped_refptr<PeerConnection> pc_;
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
652};
653
deadbeef293e9262017-01-11 12:28:30 -0800654bool PeerConnectionInterface::RTCConfiguration::operator==(
655 const PeerConnectionInterface::RTCConfiguration& o) const {
656 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700657 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800658 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000659 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700660 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800661 BundlePolicy bundle_policy;
662 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700663 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
664 int ice_candidate_pool_size;
665 bool disable_ipv6;
666 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700667 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100668 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700669 bool enable_rtp_data_channel;
670 rtc::Optional<int> screencast_min_bitrate;
671 rtc::Optional<bool> combined_audio_video_bwe;
672 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800673 TcpCandidatePolicy tcp_candidate_policy;
674 CandidateNetworkPolicy candidate_network_policy;
675 int audio_jitter_buffer_max_packets;
676 bool audio_jitter_buffer_fast_accelerate;
677 int ice_connection_receiving_timeout;
678 int ice_backup_candidate_pair_ping_interval;
679 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800680 bool prioritize_most_likely_ice_candidate_pairs;
681 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800682 bool prune_turn_ports;
683 bool presume_writable_when_fully_relayed;
684 bool enable_ice_renomination;
685 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800686 rtc::Optional<int> ice_check_interval_strong_connectivity;
687 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800688 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700689 rtc::Optional<int> ice_unwritable_timeout;
690 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800691 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700692 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200693 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800694 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800695 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800696 };
697 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
698 "Did you add something to RTCConfiguration and forget to "
699 "update operator==?");
700 return type == o.type && servers == o.servers &&
701 bundle_policy == o.bundle_policy &&
702 rtcp_mux_policy == o.rtcp_mux_policy &&
703 tcp_candidate_policy == o.tcp_candidate_policy &&
704 candidate_network_policy == o.candidate_network_policy &&
705 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
706 audio_jitter_buffer_fast_accelerate ==
707 o.audio_jitter_buffer_fast_accelerate &&
708 ice_connection_receiving_timeout ==
709 o.ice_connection_receiving_timeout &&
710 ice_backup_candidate_pair_ping_interval ==
711 o.ice_backup_candidate_pair_ping_interval &&
712 continual_gathering_policy == o.continual_gathering_policy &&
713 certificates == o.certificates &&
714 prioritize_most_likely_ice_candidate_pairs ==
715 o.prioritize_most_likely_ice_candidate_pairs &&
716 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800717 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700718 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100719 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800720 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800721 screencast_min_bitrate == o.screencast_min_bitrate &&
722 combined_audio_video_bwe == o.combined_audio_video_bwe &&
723 enable_dtls_srtp == o.enable_dtls_srtp &&
724 ice_candidate_pool_size == o.ice_candidate_pool_size &&
725 prune_turn_ports == o.prune_turn_ports &&
726 presume_writable_when_fully_relayed ==
727 o.presume_writable_when_fully_relayed &&
728 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800729 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800730 ice_check_interval_strong_connectivity ==
731 o.ice_check_interval_strong_connectivity &&
732 ice_check_interval_weak_connectivity ==
733 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700734 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700735 ice_unwritable_timeout == o.ice_unwritable_timeout &&
736 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800737 stun_candidate_keepalive_interval ==
738 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200739 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800740 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800741 sdp_semantics == o.sdp_semantics &&
742 network_preference == o.network_preference;
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;
Zhi Huange830e682018-03-30 10:48:35 -0700937#if defined(ENABLE_EXTERNAL_AUTH)
938 config.enable_external_auth = true;
939#endif
940 transport_controller_.reset(new JsepTransportController(
941 signaling_thread(), network_thread(), port_allocator_.get(), config));
942 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800943 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700944 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800945 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700946 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800947 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700948 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800949 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
950 transport_controller_->SignalDtlsHandshakeError.connect(
951 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
952
953 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700954
deadbeefab9b2d12015-10-14 11:33:11 -0700955 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700956 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957
Steve Antonba818672017-11-06 10:21:57 -0800958 configuration_ = configuration;
959
Steve Anton75737c02017-11-06 10:37:17 -0800960 // Obtain a certificate from RTCConfiguration if any were provided (optional).
961 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
962 if (!configuration.certificates.empty()) {
963 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
964 // just picking the first one. The decision should be made based on the DTLS
965 // handshake. The DTLS negotiations need to know about all certificates.
966 certificate = configuration.certificates[0];
967 }
968
Steve Antond25da372017-11-06 14:50:29 -0800969 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800970
971 if (options.disable_encryption) {
972 dtls_enabled_ = false;
973 } else {
974 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700975 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800976 // |configuration| can override the default |dtls_enabled_| value.
977 if (configuration.enable_dtls_srtp) {
978 dtls_enabled_ = *(configuration.enable_dtls_srtp);
979 }
980 }
981
982 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
983 // It takes precendence over the disable_sctp_data_channels
984 // PeerConnectionFactoryInterface::Options.
985 if (configuration.enable_rtp_data_channel) {
986 data_channel_type_ = cricket::DCT_RTP;
987 } else {
988 // DTLS has to be enabled to use SCTP.
989 if (!options.disable_sctp_data_channels && dtls_enabled_) {
990 data_channel_type_ = cricket::DCT_SCTP;
991 }
992 }
993
994 video_options_.screencast_min_bitrate_kbps =
995 configuration.screencast_min_bitrate;
996 audio_options_.combined_audio_video_bwe =
997 configuration.combined_audio_video_bwe;
998
999 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001000 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001001
1002 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001003 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001004
1005 // Whether the certificate generator/certificate is null or not determines
1006 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1007 // the right instructions by clearing the variables if needed.
1008 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001009 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001010 certificate = nullptr;
1011 } else if (certificate) {
1012 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001013 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001014 }
1015
1016 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1017 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001018 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001019 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1020 this, &PeerConnection::OnCertificateReady);
1021
1022 if (options.disable_encryption) {
1023 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1024 }
1025
1026 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1027 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028
Steve Anton4171afb2017-11-20 10:20:22 -08001029 // Add default audio/video transceivers for Plan B SDP.
1030 if (!IsUnifiedPlan()) {
1031 transceivers_.push_back(
1032 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1033 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1037 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 return true;
1039}
1040
Steve Anton038834f2017-07-14 15:59:59 -07001041RTCError PeerConnection::ValidateConfiguration(
1042 const RTCConfiguration& config) const {
1043 if (config.ice_regather_interval_range &&
1044 config.continual_gathering_policy == GATHER_ONCE) {
1045 return RTCError(RTCErrorType::INVALID_PARAMETER,
1046 "ice_regather_interval_range specified but continual "
1047 "gathering policy is GATHER_ONCE");
1048 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001049 auto result =
1050 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1051 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001052}
1053
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001054rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001055PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001056 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1057 "Plan SdpSemantics. Please use GetSenders "
1058 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001059 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060}
1061
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001062rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001064 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1065 "Plan SdpSemantics. Please use GetReceivers "
1066 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001067 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068}
1069
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001070bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001071 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1072 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001073 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001074 if (IsClosed()) {
1075 return false;
1076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 return false;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080
1081 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001082 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1083 observer->SignalAudioTrackAdded.connect(this,
1084 &PeerConnection::OnAudioTrackAdded);
1085 observer->SignalAudioTrackRemoved.connect(
1086 this, &PeerConnection::OnAudioTrackRemoved);
1087 observer->SignalVideoTrackAdded.connect(this,
1088 &PeerConnection::OnVideoTrackAdded);
1089 observer->SignalVideoTrackRemoved.connect(
1090 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001091 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001092
deadbeefab9b2d12015-10-14 11:33:11 -07001093 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001094 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001095 }
1096 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001097 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001100 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 observer_->OnRenegotiationNeeded();
1102 return true;
1103}
1104
1105void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001106 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1107 "Plan SdpSemantics. Please use RemoveTrack "
1108 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001109 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001110 if (!IsClosed()) {
1111 for (const auto& track : local_stream->GetAudioTracks()) {
1112 RemoveAudioTrack(track.get(), local_stream);
1113 }
1114 for (const auto& track : local_stream->GetVideoTracks()) {
1115 RemoveVideoTrack(track.get(), local_stream);
1116 }
deadbeefab9b2d12015-10-14 11:33:11 -07001117 }
deadbeefab9b2d12015-10-14 11:33:11 -07001118 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001119 stream_observers_.erase(
1120 std::remove_if(
1121 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001122 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001123 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001124 }),
1125 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001126
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127 if (IsClosed()) {
1128 return;
1129 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 observer_->OnRenegotiationNeeded();
1131}
1132
deadbeefe1f9d832016-01-14 15:35:42 -08001133rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1134 MediaStreamTrackInterface* track,
1135 std::vector<MediaStreamInterface*> streams) {
1136 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001137 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001138 for (auto* stream : streams) {
1139 if (!stream) {
1140 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1141 return nullptr;
1142 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001143 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001144 }
Seth Hampson845e8782018-03-02 11:34:10 -08001145 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001146 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001147 return nullptr;
1148 }
Steve Antonf9381f02017-12-14 10:23:57 -08001149 return sender_or_error.MoveValue();
1150}
1151
Steve Anton2d6c76a2018-01-05 17:10:52 -08001152RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001153 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001154 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001155 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001156 if (!track) {
1157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1158 }
1159 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1160 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1162 "Track has invalid kind: " + track->kind());
1163 }
Steve Antonf9381f02017-12-14 10:23:57 -08001164 if (IsClosed()) {
1165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1166 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001167 }
Steve Anton4171afb2017-11-20 10:20:22 -08001168 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001169 LOG_AND_RETURN_ERROR(
1170 RTCErrorType::INVALID_PARAMETER,
1171 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001172 }
Steve Antonf9381f02017-12-14 10:23:57 -08001173 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001174 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1175 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001176 if (sender_or_error.ok()) {
1177 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001178 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001179 }
1180 return sender_or_error;
1181}
deadbeefe1f9d832016-01-14 15:35:42 -08001182
Steve Antonf9381f02017-12-14 10:23:57 -08001183RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1184PeerConnection::AddTrackPlanB(
1185 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001186 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001187 if (stream_ids.size() > 1u) {
1188 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1189 "AddTrack with more than one stream is not "
1190 "supported with Plan B semantics.");
1191 }
1192 std::vector<std::string> adjusted_stream_ids = stream_ids;
1193 if (adjusted_stream_ids.empty()) {
1194 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1195 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001196 cricket::MediaType media_type =
1197 (track->kind() == MediaStreamTrackInterface::kAudioKind
1198 ? cricket::MEDIA_TYPE_AUDIO
1199 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001200 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001201 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001202 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001203 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001204 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001205 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001206 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001207 if (sender_info) {
1208 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001209 }
Steve Antonf9381f02017-12-14 10:23:57 -08001210 } else {
1211 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001212 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001213 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001214 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001215 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001216 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001217 if (sender_info) {
1218 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001219 }
deadbeefe1f9d832016-01-14 15:35:42 -08001220 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001221 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001222}
deadbeefe1f9d832016-01-14 15:35:42 -08001223
Steve Antonf9381f02017-12-14 10:23:57 -08001224RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1225PeerConnection::AddTrackUnifiedPlan(
1226 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001227 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001228 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1229 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001230 RTC_LOG(LS_INFO) << "Reusing an existing "
1231 << cricket::MediaTypeToString(transceiver->media_type())
1232 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001233 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001234 transceiver->internal()->set_direction(
1235 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001236 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001239 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001240 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001241 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001242 } else {
1243 cricket::MediaType media_type =
1244 (track->kind() == MediaStreamTrackInterface::kAudioKind
1245 ? cricket::MEDIA_TYPE_AUDIO
1246 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001247 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1248 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001249 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001250 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1251 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001252 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001253 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001254 }
Steve Antonf9381f02017-12-14 10:23:57 -08001255 return transceiver->sender();
1256}
1257
1258rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1259PeerConnection::FindFirstTransceiverForAddedTrack(
1260 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1261 RTC_DCHECK(track);
1262 for (auto transceiver : transceivers_) {
1263 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001264 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001265 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001266 !transceiver->internal()->has_ever_been_used_to_send() &&
1267 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001268 return transceiver;
1269 }
1270 }
1271 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001272}
1273
1274bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1275 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001276 return RemoveTrackInternal(sender).ok();
1277}
1278
1279RTCError PeerConnection::RemoveTrackInternal(
1280 rtc::scoped_refptr<RtpSenderInterface> sender) {
1281 if (!sender) {
1282 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1283 }
deadbeefe1f9d832016-01-14 15:35:42 -08001284 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1286 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001287 }
Steve Antonf9381f02017-12-14 10:23:57 -08001288 if (IsUnifiedPlan()) {
1289 auto transceiver = FindTransceiverBySender(sender);
1290 if (!transceiver || !sender->track()) {
1291 return RTCError::OK();
1292 }
1293 sender->SetTrack(nullptr);
1294 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001295 transceiver->internal()->set_direction(
1296 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001297 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001300 }
Steve Anton4171afb2017-11-20 10:20:22 -08001301 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001302 bool removed;
1303 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1304 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1305 } else {
1306 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1307 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1308 }
1309 if (!removed) {
1310 LOG_AND_RETURN_ERROR(
1311 RTCErrorType::INVALID_PARAMETER,
1312 "Couldn't find sender " + sender->id() + " to remove.");
1313 }
Steve Anton4171afb2017-11-20 10:20:22 -08001314 }
deadbeefe1f9d832016-01-14 15:35:42 -08001315 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001316 return RTCError::OK();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindTransceiverBySender(
1321 rtc::scoped_refptr<RtpSenderInterface> sender) {
1322 for (auto transceiver : transceivers_) {
1323 if (transceiver->sender() == sender) {
1324 return transceiver;
1325 }
1326 }
1327 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001328}
1329
Steve Anton9158ef62017-11-27 13:01:52 -08001330RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1331PeerConnection::AddTransceiver(
1332 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1333 return AddTransceiver(track, RtpTransceiverInit());
1334}
1335
1336RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1337PeerConnection::AddTransceiver(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1339 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001340 RTC_CHECK(IsUnifiedPlan())
1341 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001342 if (!track) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1344 }
1345 cricket::MediaType media_type;
1346 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1347 media_type = cricket::MEDIA_TYPE_AUDIO;
1348 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1349 media_type = cricket::MEDIA_TYPE_VIDEO;
1350 } else {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1352 "Track kind is not audio or video");
1353 }
1354 return AddTransceiver(media_type, track, init);
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1359 return AddTransceiver(media_type, RtpTransceiverInit());
1360}
1361
1362RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1363PeerConnection::AddTransceiver(cricket::MediaType media_type,
1364 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001365 RTC_CHECK(IsUnifiedPlan())
1366 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001367 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1368 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1370 "media type is not audio or video");
1371 }
1372 return AddTransceiver(media_type, nullptr, init);
1373}
1374
1375RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1376PeerConnection::AddTransceiver(
1377 cricket::MediaType media_type,
1378 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001379 const RtpTransceiverInit& init,
1380 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001381 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1382 media_type == cricket::MEDIA_TYPE_VIDEO));
1383 if (track) {
1384 RTC_DCHECK_EQ(media_type,
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind
1386 ? cricket::MEDIA_TYPE_AUDIO
1387 : cricket::MEDIA_TYPE_VIDEO));
1388 }
1389
1390 // TODO(bugs.webrtc.org/7600): Verify init.
1391
Steve Anton3d954a62018-04-02 11:27:23 -07001392 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1393 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001394 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1396 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1397 transceiver->internal()->set_direction(init.direction);
1398
Steve Anton22da89f2018-01-25 13:58:07 -08001399 if (fire_callback) {
1400 observer_->OnRenegotiationNeeded();
1401 }
Steve Antonf9381f02017-12-14 10:23:57 -08001402
1403 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1404}
1405
Steve Anton02ee47c2018-01-10 16:26:06 -08001406rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1407PeerConnection::CreateSender(
1408 cricket::MediaType media_type,
1409 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001410 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001411 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001412 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1413 RTC_DCHECK(!track ||
1414 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1415 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1416 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001417 new AudioRtpSender(worker_thread(),
1418 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001419 stream_ids, stats_.get()));
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
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001694rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001695PeerConnection::CreateDataChannel(
1696 const std::string& label,
1697 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001698 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001699
deadbeefab9b2d12015-10-14 11:33:11 -07001700 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001701
kwibergd1fe2812016-04-27 06:47:29 -07001702 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001703 if (config) {
1704 internal_config.reset(new InternalDataChannelInit(*config));
1705 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001706 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001707 InternalCreateDataChannel(label, internal_config.get()));
1708 if (!channel.get()) {
1709 return nullptr;
1710 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001711
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001712 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1713 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001714 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001715 observer_->OnRenegotiationNeeded();
1716 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001717 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718 return DataChannelProxy::Create(signaling_thread(), channel.get());
1719}
1720
1721void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1722 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001723 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001724
zhihuang1c378ed2017-08-17 14:10:50 -07001725 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1726 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1727 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1728 // compares the mandatory fields parsed with the mandatory fields added in the
1729 // |constraints| and some downstream applications might create offers with
1730 // mandatory fields which would not be parsed in the helper method. For
1731 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1732 // |constraints| as a mandatory field but it is not parsed.
1733 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001734
zhihuang1c378ed2017-08-17 14:10:50 -07001735 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001736}
1737
1738void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1739 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001740 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001741
nisse7ce109a2017-01-31 00:57:56 -08001742 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001743 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001744 return;
1745 }
deadbeefab9b2d12015-10-14 11:33:11 -07001746
Steve Anton8d3444d2017-10-20 15:30:51 -07001747 if (IsClosed()) {
1748 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001749 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001750 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001751 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001752 return;
1753 }
1754
zhihuang1c378ed2017-08-17 14:10:50 -07001755 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001756 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001757 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001758 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001759 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001760 return;
1761 }
1762
Steve Anton22da89f2018-01-25 13:58:07 -08001763 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1764 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1765 if (IsUnifiedPlan()) {
1766 RTCError error = HandleLegacyOfferOptions(options);
1767 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001768 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001769 return;
1770 }
1771 }
1772
zhihuang1c378ed2017-08-17 14:10:50 -07001773 cricket::MediaSessionOptions session_options;
1774 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001775 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776}
1777
Steve Anton22da89f2018-01-25 13:58:07 -08001778RTCError PeerConnection::HandleLegacyOfferOptions(
1779 const RTCOfferAnswerOptions& options) {
1780 RTC_DCHECK(IsUnifiedPlan());
1781
1782 if (options.offer_to_receive_audio == 0) {
1783 RemoveRecvDirectionFromReceivingTransceiversOfType(
1784 cricket::MEDIA_TYPE_AUDIO);
1785 } else if (options.offer_to_receive_audio == 1) {
1786 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1787 } else if (options.offer_to_receive_audio > 1) {
1788 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1789 "offer_to_receive_audio > 1 is not supported.");
1790 }
1791
1792 if (options.offer_to_receive_video == 0) {
1793 RemoveRecvDirectionFromReceivingTransceiversOfType(
1794 cricket::MEDIA_TYPE_VIDEO);
1795 } else if (options.offer_to_receive_video == 1) {
1796 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1797 } else if (options.offer_to_receive_video > 1) {
1798 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1799 "offer_to_receive_video > 1 is not supported.");
1800 }
1801
1802 return RTCError::OK();
1803}
1804
1805void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1806 cricket::MediaType media_type) {
1807 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001808 RtpTransceiverDirection new_direction =
1809 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1810 if (new_direction != transceiver->direction()) {
1811 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1812 << " transceiver (MID="
1813 << transceiver->mid().value_or("<not set>") << ") from "
1814 << RtpTransceiverDirectionToString(
1815 transceiver->direction())
1816 << " to "
1817 << RtpTransceiverDirectionToString(new_direction)
1818 << " since CreateOffer specified offer_to_receive=0";
1819 transceiver->internal()->set_direction(new_direction);
1820 }
Steve Anton22da89f2018-01-25 13:58:07 -08001821 }
1822}
1823
1824void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1825 cricket::MediaType media_type) {
1826 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001827 RTC_LOG(LS_INFO)
1828 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1829 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001830 RtpTransceiverInit init;
1831 init.direction = RtpTransceiverDirection::kRecvOnly;
1832 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1833 }
1834}
1835
1836std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1837PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1838 std::vector<
1839 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1840 receiving_transceivers;
1841 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001842 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001843 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1844 receiving_transceivers.push_back(transceiver);
1845 }
1846 }
1847 return receiving_transceivers;
1848}
1849
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850void PeerConnection::CreateAnswer(
1851 CreateSessionDescriptionObserver* observer,
1852 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001853 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001854
nisse7ce109a2017-01-31 00:57:56 -08001855 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001856 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001857 return;
1858 }
deadbeefab9b2d12015-10-14 11:33:11 -07001859
zhihuang1c378ed2017-08-17 14:10:50 -07001860 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1861 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1862 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001863 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001864 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001865 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001866 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001867 return;
1868 }
1869
Steve Anton8d3444d2017-10-20 15:30:51 -07001870 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001871}
1872
1873void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1874 const RTCOfferAnswerOptions& options) {
1875 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001876 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001877 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001878 return;
1879 }
1880
Steve Antondffead82018-02-06 10:31:29 -08001881 if (!(signaling_state_ == kHaveRemoteOffer ||
1882 signaling_state_ == kHaveLocalPrAnswer)) {
1883 std::string error =
1884 "PeerConnection cannot create an answer in a state other than "
1885 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001886 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001887 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001888 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001889 return;
1890 }
1891
Steve Antondffead82018-02-06 10:31:29 -08001892 // The remote description should be set if we're in the right state.
1893 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001894
Steve Anton22da89f2018-01-25 13:58:07 -08001895 if (IsUnifiedPlan()) {
1896 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1897 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1898 "supported with Unified Plan semantics. Use the "
1899 "RtpTransceiver API instead.";
1900 }
1901 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1902 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1903 "supported with Unified Plan semantics. Use the "
1904 "RtpTransceiver API instead.";
1905 }
1906 }
1907
htaa2a49d92016-03-04 02:51:39 -08001908 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001909 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001910
Steve Antond25da372017-11-06 14:50:29 -08001911 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001912}
1913
1914void PeerConnection::SetLocalDescription(
1915 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001916 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001917 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001918
Steve Anton80dd7b52018-02-16 17:08:42 -08001919 // The SetLocalDescription contract is that we take ownership of the session
1920 // description regardless of the outcome, so wrap it in a unique_ptr right
1921 // away. Ideally, SetLocalDescription's signature will be changed to take the
1922 // description as a unique_ptr argument to formalize this agreement.
1923 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1924
nisse7ce109a2017-01-31 00:57:56 -08001925 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001926 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001927 return;
1928 }
Steve Anton8a006912017-12-04 15:25:56 -08001929
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001931 PostSetSessionDescriptionFailure(
1932 observer,
1933 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 return;
1935 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001936
Steve Anton80dd7b52018-02-16 17:08:42 -08001937 // If a session error has occurred the PeerConnection is in a possibly
1938 // inconsistent state so fail right away.
1939 if (session_error() != SessionError::kNone) {
1940 std::string error_message = GetSessionErrorMsg();
1941 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001942 PostSetSessionDescriptionFailure(
1943 observer,
1944 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001945 return;
1946 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001947
Steve Anton80dd7b52018-02-16 17:08:42 -08001948 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1949 if (!error.ok()) {
1950 std::string error_message = GetSetDescriptionErrorMessage(
1951 cricket::CS_LOCAL, desc->GetType(), error);
1952 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001953 PostSetSessionDescriptionFailure(
1954 observer,
1955 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001956 return;
1957 }
1958
1959 // Grab the description type before moving ownership to ApplyLocalDescription,
1960 // which may destroy it before returning.
1961 const SdpType type = desc->GetType();
1962
1963 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001964 // |desc| may be destroyed at this point.
1965
1966 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001967 // If ApplyLocalDescription fails, the PeerConnection could be in an
1968 // inconsistent state, so act conservatively here and set the session error
1969 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1970 SetSessionError(SessionError::kContent, error.message());
1971 std::string error_message =
1972 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1973 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001974 PostSetSessionDescriptionFailure(
1975 observer,
1976 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001977 return;
1978 }
Steve Anton8a006912017-12-04 15:25:56 -08001979 RTC_DCHECK(local_description());
1980
1981 PostSetSessionDescriptionSuccess(observer);
1982
Steve Anton8a006912017-12-04 15:25:56 -08001983 // MaybeStartGathering needs to be called after posting
1984 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1985 // before signaling that SetLocalDescription completed.
1986 transport_controller_->MaybeStartGathering();
1987
Steve Antona3a92c22017-12-07 10:27:41 -08001988 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001989 // TODO(deadbeef): We already had to hop to the network thread for
1990 // MaybeStartGathering...
1991 network_thread()->Invoke<void>(
1992 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1993 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001994 // Make UMA notes about what was agreed to.
1995 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001996 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001997 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001998}
1999
2000RTCError PeerConnection::ApplyLocalDescription(
2001 std::unique_ptr<SessionDescriptionInterface> desc) {
2002 RTC_DCHECK_RUN_ON(signaling_thread());
2003 RTC_DCHECK(desc);
2004
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002005 // Update stats here so that we have the most recent stats for tracks and
2006 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002007 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002008
Steve Antondcc3c022017-12-22 16:02:54 -08002009 // Take a reference to the old local description since it's used below to
2010 // compare against the new local description. When setting the new local
2011 // description, grab ownership of the replaced session description in case it
2012 // is the same as |old_local_description|, to keep it alive for the duration
2013 // of the method.
2014 const SessionDescriptionInterface* old_local_description =
2015 local_description();
2016 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002017 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002018 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002019 replaced_local_description = pending_local_description_
2020 ? std::move(pending_local_description_)
2021 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002022 current_local_description_ = std::move(desc);
2023 pending_local_description_ = nullptr;
2024 current_remote_description_ = std::move(pending_remote_description_);
2025 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002026 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002027 pending_local_description_ = std::move(desc);
2028 }
2029 // The session description to apply now must be accessed by
2030 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002031 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002032
Zhi Huange830e682018-03-30 10:48:35 -07002033 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2034 if (!error.ok()) {
2035 return error;
2036 }
2037
Steve Antondcc3c022017-12-22 16:02:54 -08002038 if (IsUnifiedPlan()) {
2039 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002040 cricket::CS_LOCAL, *local_description(), old_local_description,
2041 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002042 if (!error.ok()) {
2043 return error;
2044 }
Steve Antondcc3c022017-12-22 16:02:54 -08002045 for (auto transceiver : transceivers_) {
2046 const ContentInfo* content =
2047 FindMediaSectionForTransceiver(transceiver, local_description());
2048 if (!content) {
2049 continue;
2050 }
2051 const MediaContentDescription* media_desc = content->media_description();
2052 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2053 transceiver->internal()->set_current_direction(media_desc->direction());
2054 }
2055 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002056 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2057 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002058 transceiver->Stop();
2059 }
2060 }
2061 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002062 // Media channels will be created only when offer is set. These may use new
2063 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002064 if (type == SdpType::kOffer) {
2065 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2066 // description is applied. Restore back to old description.
2067 RTCError error = CreateChannels(*local_description()->description());
2068 if (!error.ok()) {
2069 return error;
2070 }
2071 }
Steve Antondcc3c022017-12-22 16:02:54 -08002072 // Remove unused channels if MediaContentDescription is rejected.
2073 RemoveUnusedChannels(local_description()->description());
2074 }
Steve Anton8a006912017-12-04 15:25:56 -08002075
Zhi Huange830e682018-03-30 10:48:35 -07002076 error = UpdateSessionState(type, cricket::CS_LOCAL,
2077 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002078 if (!error.ok()) {
2079 return error;
2080 }
Steve Antondcc3c022017-12-22 16:02:54 -08002081
Steve Anton8a006912017-12-04 15:25:56 -08002082 if (remote_description()) {
2083 // Now that we have a local description, we can push down remote candidates.
2084 UseCandidatesInSessionDescription(remote_description());
2085 }
2086
2087 pending_ice_restarts_.clear();
2088 if (session_error() != SessionError::kNone) {
2089 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2090 }
2091
deadbeefab9b2d12015-10-14 11:33:11 -07002092 // If setting the description decided our SSL role, allocate any necessary
2093 // SCTP sids.
2094 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002095 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002096 AllocateSctpSids(role);
2097 }
2098
Steve Antond3679212018-01-17 17:41:02 -08002099 if (IsUnifiedPlan()) {
2100 for (auto transceiver : transceivers_) {
2101 const ContentInfo* content =
2102 FindMediaSectionForTransceiver(transceiver, local_description());
2103 if (!content) {
2104 continue;
2105 }
Steve Anton74255ff2018-01-24 18:32:57 -08002106 const auto& streams = content->media_description()->streams();
2107 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002108 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002109 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002110 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002111 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002112 }
2113 }
2114 } else {
2115 // Plan B semantics.
2116
Steve Antondcc3c022017-12-22 16:02:54 -08002117 // Update state and SSRC of local MediaStreams and DataChannels based on the
2118 // local session description.
2119 const cricket::ContentInfo* audio_content =
2120 GetFirstAudioContent(local_description()->description());
2121 if (audio_content) {
2122 if (audio_content->rejected) {
2123 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2124 } else {
2125 const cricket::AudioContentDescription* audio_desc =
2126 audio_content->media_description()->as_audio();
2127 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2128 }
deadbeeffaac4972015-11-12 15:33:07 -08002129 }
deadbeefab9b2d12015-10-14 11:33:11 -07002130
Steve Antondcc3c022017-12-22 16:02:54 -08002131 const cricket::ContentInfo* video_content =
2132 GetFirstVideoContent(local_description()->description());
2133 if (video_content) {
2134 if (video_content->rejected) {
2135 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2136 } else {
2137 const cricket::VideoContentDescription* video_desc =
2138 video_content->media_description()->as_video();
2139 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2140 }
deadbeeffaac4972015-11-12 15:33:07 -08002141 }
deadbeefab9b2d12015-10-14 11:33:11 -07002142 }
2143
2144 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002145 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002146 if (data_content) {
2147 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002148 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002149 if (rtc::starts_with(data_desc->protocol().data(),
2150 cricket::kMediaProtocolRtpPrefix)) {
2151 UpdateLocalRtpDataChannels(data_desc->streams());
2152 }
2153 }
2154
Steve Anton8a006912017-12-04 15:25:56 -08002155 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002156}
2157
2158void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002159 SetSessionDescriptionObserver* observer,
2160 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002161 SetRemoteDescription(
2162 std::unique_ptr<SessionDescriptionInterface>(desc),
2163 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2164 new SetRemoteDescriptionObserverAdapter(this, observer)));
2165}
2166
2167void PeerConnection::SetRemoteDescription(
2168 std::unique_ptr<SessionDescriptionInterface> desc,
2169 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002170 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002171
nisse7ce109a2017-01-31 00:57:56 -08002172 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002173 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002174 return;
2175 }
Steve Anton8a006912017-12-04 15:25:56 -08002176
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002177 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002178 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002179 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180 return;
2181 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002182
Steve Anton80dd7b52018-02-16 17:08:42 -08002183 // If a session error has occurred the PeerConnection is in a possibly
2184 // inconsistent state so fail right away.
2185 if (session_error() != SessionError::kNone) {
2186 std::string error_message = GetSessionErrorMsg();
2187 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2188 observer->OnSetRemoteDescriptionComplete(
2189 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2190 return;
2191 }
Steve Anton71439a62018-02-15 11:53:06 -08002192
Steve Antonba42e992018-04-09 14:10:01 -07002193 if (desc->GetType() == SdpType::kOffer) {
2194 // Report to UMA the format of the received offer.
2195 ReportSdpFormatReceived(*desc);
2196 }
2197
Steve Anton80dd7b52018-02-16 17:08:42 -08002198 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002199 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002200 std::string error_message = GetSetDescriptionErrorMessage(
2201 cricket::CS_REMOTE, desc->GetType(), error);
2202 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002203 observer->OnSetRemoteDescriptionComplete(
2204 RTCError(error.type(), std::move(error_message)));
2205 return;
2206 }
Steve Anton71439a62018-02-15 11:53:06 -08002207
Steve Anton80dd7b52018-02-16 17:08:42 -08002208 // Grab the description type before moving ownership to
2209 // ApplyRemoteDescription, which may destroy it before returning.
2210 const SdpType type = desc->GetType();
2211
2212 error = ApplyRemoteDescription(std::move(desc));
2213 // |desc| may be destroyed at this point.
2214
2215 if (!error.ok()) {
2216 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2217 // inconsistent state, so act conservatively here and set the session error
2218 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2219 SetSessionError(SessionError::kContent, error.message());
2220 std::string error_message =
2221 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2222 RTC_LOG(LS_ERROR) << error_message;
2223 observer->OnSetRemoteDescriptionComplete(
2224 RTCError(error.type(), std::move(error_message)));
2225 return;
2226 }
2227 RTC_DCHECK(remote_description());
2228
2229 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002230 // TODO(deadbeef): We already had to hop to the network thread for
2231 // MaybeStartGathering...
2232 network_thread()->Invoke<void>(
2233 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2234 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002235 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002236 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002237 }
2238
2239 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002240 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002241}
2242
2243RTCError PeerConnection::ApplyRemoteDescription(
2244 std::unique_ptr<SessionDescriptionInterface> desc) {
2245 RTC_DCHECK_RUN_ON(signaling_thread());
2246 RTC_DCHECK(desc);
2247
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 // Update stats here so that we have the most recent stats for tracks and
2249 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002250 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002251
Steve Antondcc3c022017-12-22 16:02:54 -08002252 // Take a reference to the old remote description since it's used below to
2253 // compare against the new remote description. When setting the new remote
2254 // description, grab ownership of the replaced session description in case it
2255 // is the same as |old_remote_description|, to keep it alive for the duration
2256 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002257 const SessionDescriptionInterface* old_remote_description =
2258 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002259 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002260 SdpType type = desc->GetType();
2261 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002262 replaced_remote_description = pending_remote_description_
2263 ? std::move(pending_remote_description_)
2264 : std::move(current_remote_description_);
2265 current_remote_description_ = std::move(desc);
2266 pending_remote_description_ = nullptr;
2267 current_local_description_ = std::move(pending_local_description_);
2268 } else {
2269 replaced_remote_description = std::move(pending_remote_description_);
2270 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271 }
Steve Anton8a006912017-12-04 15:25:56 -08002272 // The session description to apply now must be accessed by
2273 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002274 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275
Zhi Huange830e682018-03-30 10:48:35 -07002276 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2277 if (!error.ok()) {
2278 return error;
2279 }
Steve Anton8a006912017-12-04 15:25:56 -08002280 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002281 if (IsUnifiedPlan()) {
2282 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002283 cricket::CS_REMOTE, *remote_description(), local_description(),
2284 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002285 if (!error.ok()) {
2286 return error;
2287 }
Steve Antondcc3c022017-12-22 16:02:54 -08002288 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002289 // Media channels will be created only when offer is set. These may use new
2290 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002291 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002292 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002293 // description is applied. Restore back to old description.
2294 RTCError error = CreateChannels(*remote_description()->description());
2295 if (!error.ok()) {
2296 return error;
2297 }
2298 }
Steve Antondcc3c022017-12-22 16:02:54 -08002299 // Remove unused channels if MediaContentDescription is rejected.
2300 RemoveUnusedChannels(remote_description()->description());
2301 }
Steve Anton8a006912017-12-04 15:25:56 -08002302
Zhi Huange830e682018-03-30 10:48:35 -07002303 // NOTE: Candidates allocation will be initiated only when
2304 // SetLocalDescription is called.
2305 error = UpdateSessionState(type, cricket::CS_REMOTE,
2306 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002307 if (!error.ok()) {
2308 return error;
2309 }
2310
2311 if (local_description() &&
2312 !UseCandidatesInSessionDescription(remote_description())) {
2313 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2314 }
2315
2316 if (old_remote_description) {
2317 for (const cricket::ContentInfo& content :
2318 old_remote_description->description()->contents()) {
2319 // Check if this new SessionDescription contains new ICE ufrag and
2320 // password that indicates the remote peer requests an ICE restart.
2321 // TODO(deadbeef): When we start storing both the current and pending
2322 // remote description, this should reset pending_ice_restarts and compare
2323 // against the current description.
2324 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2325 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002326 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002327 pending_ice_restarts_.insert(content.name);
2328 }
2329 } else {
2330 // We retain all received candidates only if ICE is not restarted.
2331 // When ICE is restarted, all previous candidates belong to an old
2332 // generation and should not be kept.
2333 // TODO(deadbeef): This goes against the W3C spec which says the remote
2334 // description should only contain candidates from the last set remote
2335 // description plus any candidates added since then. We should remove
2336 // this once we're sure it won't break anything.
2337 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2338 old_remote_description, content.name, mutable_remote_description());
2339 }
2340 }
2341 }
2342
2343 if (session_error() != SessionError::kNone) {
2344 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2345 }
2346
2347 // Set the the ICE connection state to connecting since the connection may
2348 // become writable with peer reflexive candidates before any remote candidate
2349 // is signaled.
2350 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2351 // is to have a new signal the indicates a change in checking state from the
2352 // transport and expose a new checking() member from transport that can be
2353 // read to determine the current checking state. The existing SignalConnecting
2354 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002355 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002356 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002357 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2358 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2359 }
2360
deadbeefab9b2d12015-10-14 11:33:11 -07002361 // If setting the description decided our SSL role, allocate any necessary
2362 // SCTP sids.
2363 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002364 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002365 AllocateSctpSids(role);
2366 }
2367
Steve Antondcc3c022017-12-22 16:02:54 -08002368 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002369 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002370 now_receiving_transceivers;
2371 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2372 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002373 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002374 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002375 for (auto transceiver : transceivers_) {
2376 const ContentInfo* content =
2377 FindMediaSectionForTransceiver(transceiver, remote_description());
2378 if (!content) {
2379 continue;
2380 }
2381 const MediaContentDescription* media_desc = content->media_description();
2382 RtpTransceiverDirection local_direction =
2383 RtpTransceiverDirectionReversed(media_desc->direction());
2384 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2385 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2386 // transceiver's current direction is neither sendrecv nor recvonly,
2387 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002388 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002389 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002390 // The remote description has signaled the stream IDs.
2391 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002392 }
Steve Antondcc3c022017-12-22 16:02:54 -08002393 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2394 (!transceiver->current_direction() ||
2395 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002396 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002397 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002398 << content->name << " (added to "
2399 << GetStreamIdsString(stream_ids) << ").";
2400
2401 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2402 for (const std::string& stream_id : stream_ids) {
2403 rtc::scoped_refptr<MediaStreamInterface> stream =
2404 remote_streams_->find(stream_id);
2405 if (!stream) {
2406 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2407 MediaStream::Create(stream_id));
2408 remote_streams_->AddStream(stream);
2409 added_streams.push_back(stream);
2410 }
2411 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002412 }
Steve Anton3172c032018-05-03 15:30:18 -07002413 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002414 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002415 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002416 }
2417 // If direction is sendonly or inactive, and transceiver's current
2418 // direction is neither sendonly nor inactive, process the removal of a
2419 // remote track for the media description.
2420 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002421 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002422 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002423 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2424 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002425 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2426 transceiver->internal()->receiver_internal()->streams();
2427 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002428 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002429 no_longer_receiving_transceivers.push_back(transceiver);
2430 // Remove any streams that no longer have tracks.
2431 for (auto stream : media_streams) {
2432 if (stream->GetAudioTracks().empty() &&
2433 stream->GetVideoTracks().empty()) {
2434 remote_streams_->RemoveStream(stream);
2435 removed_streams.push_back(stream);
2436 }
2437 }
Steve Antondcc3c022017-12-22 16:02:54 -08002438 }
2439 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2440 transceiver->internal()->set_current_direction(local_direction);
2441 }
2442 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002443 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2444 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002445 transceiver->Stop();
2446 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002447 if (!content->rejected &&
2448 RtpTransceiverDirectionHasRecv(local_direction)) {
2449 // Set ssrc to 0 in the case of an unsignalled ssrc.
2450 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002451 if (!media_desc->streams().empty() &&
2452 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002453 ssrc = media_desc->streams()[0].first_ssrc();
2454 }
2455 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002456 }
Steve Antondcc3c022017-12-22 16:02:54 -08002457 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002458 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002459 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002460 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002461 observer_->OnTrack(transceiver);
2462 observer_->OnAddTrack(transceiver->receiver(),
2463 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002464 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002465 for (auto stream : added_streams) {
2466 observer_->OnAddStream(stream);
2467 }
Steve Anton3172c032018-05-03 15:30:18 -07002468 for (auto transceiver : no_longer_receiving_transceivers) {
2469 observer_->OnRemoveTrack(transceiver->receiver());
2470 }
2471 for (auto stream : removed_streams) {
2472 observer_->OnRemoveStream(stream);
2473 }
Steve Antondcc3c022017-12-22 16:02:54 -08002474 }
2475
Henrik Boströmfdb92012017-11-09 19:55:44 +01002476 const cricket::ContentInfo* audio_content =
2477 GetFirstAudioContent(remote_description()->description());
2478 const cricket::ContentInfo* video_content =
2479 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002480 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002481 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002482 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002483 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002484 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002485 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002486
2487 // Check if the descriptions include streams, just in case the peer supports
2488 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002489 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002490 (audio_desc && !audio_desc->streams().empty()) ||
2491 (video_desc && !video_desc->streams().empty())) {
2492 remote_peer_supports_msid_ = true;
2493 }
deadbeefab9b2d12015-10-14 11:33:11 -07002494
2495 // We wait to signal new streams until we finish processing the description,
2496 // since only at that point will new streams have all their tracks.
2497 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2498
Steve Antondcc3c022017-12-22 16:02:54 -08002499 if (!IsUnifiedPlan()) {
2500 // TODO(steveanton): When removing RTP senders/receivers in response to a
2501 // rejected media section, there is some cleanup logic that expects the
2502 // voice/ video channel to still be set. But in this method the voice/video
2503 // channel would have been destroyed by the SetRemoteDescription caller
2504 // above so the cleanup that relies on them fails to run. The RemoveSenders
2505 // calls should be moved to right before the DestroyChannel calls to fix
2506 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002507
Steve Antondcc3c022017-12-22 16:02:54 -08002508 // Find all audio rtp streams and create corresponding remote AudioTracks
2509 // and MediaStreams.
2510 if (audio_content) {
2511 if (audio_content->rejected) {
2512 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2513 } else {
2514 bool default_audio_track_needed =
2515 !remote_peer_supports_msid_ &&
2516 RtpTransceiverDirectionHasSend(audio_desc->direction());
2517 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2518 default_audio_track_needed, audio_desc->type(),
2519 new_streams);
2520 }
deadbeeffaac4972015-11-12 15:33:07 -08002521 }
deadbeefab9b2d12015-10-14 11:33:11 -07002522
Steve Antondcc3c022017-12-22 16:02:54 -08002523 // Find all video rtp streams and create corresponding remote VideoTracks
2524 // and MediaStreams.
2525 if (video_content) {
2526 if (video_content->rejected) {
2527 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2528 } else {
2529 bool default_video_track_needed =
2530 !remote_peer_supports_msid_ &&
2531 RtpTransceiverDirectionHasSend(video_desc->direction());
2532 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2533 default_video_track_needed, video_desc->type(),
2534 new_streams);
2535 }
deadbeeffaac4972015-11-12 15:33:07 -08002536 }
deadbeefab9b2d12015-10-14 11:33:11 -07002537
Steve Antondcc3c022017-12-22 16:02:54 -08002538 // Update the DataChannels with the information from the remote peer.
2539 if (data_desc) {
2540 if (rtc::starts_with(data_desc->protocol().data(),
2541 cricket::kMediaProtocolRtpPrefix)) {
2542 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2543 }
deadbeefab9b2d12015-10-14 11:33:11 -07002544 }
deadbeefab9b2d12015-10-14 11:33:11 -07002545
Steve Antondcc3c022017-12-22 16:02:54 -08002546 // Iterate new_streams and notify the observer about new MediaStreams.
2547 for (size_t i = 0; i < new_streams->count(); ++i) {
2548 MediaStreamInterface* new_stream = new_streams->at(i);
2549 stats_->AddStream(new_stream);
2550 observer_->OnAddStream(
2551 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2552 }
deadbeefab9b2d12015-10-14 11:33:11 -07002553
Steve Antondcc3c022017-12-22 16:02:54 -08002554 UpdateEndedRemoteMediaStreams();
2555 }
deadbeefab9b2d12015-10-14 11:33:11 -07002556
Steve Anton8a006912017-12-04 15:25:56 -08002557 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002558}
2559
Steve Antondcc3c022017-12-22 16:02:54 -08002560RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2561 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002562 const SessionDescriptionInterface& new_session,
2563 const SessionDescriptionInterface* old_local_description,
2564 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002565 RTC_DCHECK(IsUnifiedPlan());
2566
Steve Anton7464fca2018-01-19 11:10:37 -08002567 const cricket::ContentGroup* bundle_group = nullptr;
2568 if (new_session.GetType() == SdpType::kOffer) {
2569 auto bundle_group_or_error =
2570 GetEarlyBundleGroup(*new_session.description());
2571 if (!bundle_group_or_error.ok()) {
2572 return bundle_group_or_error.MoveError();
2573 }
2574 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002575 }
Steve Antondcc3c022017-12-22 16:02:54 -08002576
Steve Antondcc3c022017-12-22 16:02:54 -08002577 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002578 for (size_t i = 0; i < new_contents.size(); ++i) {
2579 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002580 cricket::MediaType media_type = new_content.media_description()->type();
2581 seen_mids_.insert(new_content.name);
2582 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2583 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002584 const cricket::ContentInfo* old_local_content = nullptr;
2585 if (old_local_description &&
2586 i < old_local_description->description()->contents().size()) {
2587 old_local_content =
2588 &old_local_description->description()->contents()[i];
2589 }
2590 const cricket::ContentInfo* old_remote_content = nullptr;
2591 if (old_remote_description &&
2592 i < old_remote_description->description()->contents().size()) {
2593 old_remote_content =
2594 &old_remote_description->description()->contents()[i];
2595 }
Steve Antondcc3c022017-12-22 16:02:54 -08002596 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002597 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2598 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002599 if (!transceiver_or_error.ok()) {
2600 return transceiver_or_error.MoveError();
2601 }
2602 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002603 RTCError error =
2604 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2605 if (!error.ok()) {
2606 return error;
2607 }
2608 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002609 if (GetDataMid() && new_content.name != *GetDataMid()) {
2610 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002611 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2612 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002613 continue;
2614 }
2615 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2616 if (!error.ok()) {
2617 return error;
2618 }
Steve Antondcc3c022017-12-22 16:02:54 -08002619 } else {
2620 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2621 "Unknown section type.");
2622 }
2623 }
2624
2625 return RTCError::OK();
2626}
2627
2628RTCError PeerConnection::UpdateTransceiverChannel(
2629 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2630 transceiver,
2631 const cricket::ContentInfo& content,
2632 const cricket::ContentGroup* bundle_group) {
2633 RTC_DCHECK(IsUnifiedPlan());
2634 RTC_DCHECK(transceiver);
2635 cricket::BaseChannel* channel = transceiver->internal()->channel();
2636 if (content.rejected) {
2637 if (channel) {
2638 transceiver->internal()->SetChannel(nullptr);
2639 DestroyBaseChannel(channel);
2640 }
2641 } else {
2642 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002643 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002644 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002645 } else {
Steve Anton69470252018-02-09 11:43:08 -08002646 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002647 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002648 }
2649 if (!channel) {
2650 LOG_AND_RETURN_ERROR(
2651 RTCErrorType::INTERNAL_ERROR,
2652 "Failed to create channel for mid=" + content.name);
2653 }
2654 transceiver->internal()->SetChannel(channel);
2655 }
2656 }
2657 return RTCError::OK();
2658}
2659
Steve Antonfa2260d2017-12-28 16:38:23 -08002660RTCError PeerConnection::UpdateDataChannel(
2661 cricket::ContentSource source,
2662 const cricket::ContentInfo& content,
2663 const cricket::ContentGroup* bundle_group) {
2664 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002665 // If data channels are disabled, ignore this media section. CreateAnswer
2666 // will take care of rejecting it.
2667 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002668 }
2669 if (content.rejected) {
2670 DestroyDataChannel();
2671 } else {
2672 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002673 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002674 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2675 "Failed to create data channel.");
2676 }
2677 }
2678 if (source == cricket::CS_REMOTE) {
2679 const MediaContentDescription* data_desc = content.media_description();
2680 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2681 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2682 }
2683 }
2684 }
2685 return RTCError::OK();
2686}
2687
Steve Antondcc3c022017-12-22 16:02:54 -08002688RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2689PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002690 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002691 size_t mline_index,
2692 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002693 const ContentInfo* old_local_content,
2694 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002695 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002696 // If this is an offer then the m= section might be recycled. If the m=
2697 // section is being recycled (defined as: rejected in the current local or
2698 // remote description and not rejected in new description), dissociate the
2699 // currently associated RtpTransceiver by setting its mid property to null,
2700 // and discard the mapping between the transceiver and its m= section index.
2701 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2702 old_remote_content)) {
2703 // We want to dissociate the transceiver that has the rejected mid.
2704 const std::string& old_mid =
2705 (old_local_content && old_local_content->rejected)
2706 ? old_local_content->name
2707 : old_remote_content->name;
2708 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002709 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002710 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2711 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-22 16:02:54 -08002712 old_transceiver->internal()->set_mid(rtc::nullopt);
2713 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2714 }
2715 }
2716 const MediaContentDescription* media_desc = content.media_description();
2717 auto transceiver = GetAssociatedTransceiver(content.name);
2718 if (source == cricket::CS_LOCAL) {
2719 // Find the RtpTransceiver that corresponds to this m= section, using the
2720 // mapping between transceivers and m= section indices established when
2721 // creating the offer.
2722 if (!transceiver) {
2723 transceiver = GetTransceiverByMLineIndex(mline_index);
2724 }
2725 if (!transceiver) {
2726 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2727 "Unknown transceiver");
2728 }
2729 } else {
2730 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2731 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2732 // of the same type...
2733 if (!transceiver &&
2734 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2735 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2736 }
2737 // If no RtpTransceiver was found in the previous step, create one with a
2738 // recvonly direction.
2739 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002740 RTC_LOG(LS_INFO) << "Adding "
2741 << cricket::MediaTypeToString(media_desc->type())
2742 << " transceiver for MID=" << content.name
2743 << " at i=" << mline_index
2744 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002745 auto sender =
2746 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002747 std::string receiver_id;
2748 if (!media_desc->streams().empty()) {
2749 receiver_id = media_desc->streams()[0].id;
2750 } else {
2751 receiver_id = rtc::CreateRandomUuid();
2752 }
2753 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002754 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002755 transceiver->internal()->set_direction(
2756 RtpTransceiverDirection::kRecvOnly);
2757 }
2758 }
2759 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002760 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002761 LOG_AND_RETURN_ERROR(
2762 RTCErrorType::INVALID_PARAMETER,
2763 "Transceiver type does not match media description type.");
2764 }
2765 // Associate the found or created RtpTransceiver with the m= section by
2766 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2767 // section, and establish a mapping between the transceiver and the index of
2768 // the m= section.
2769 transceiver->internal()->set_mid(content.name);
2770 transceiver->internal()->set_mline_index(mline_index);
2771 return std::move(transceiver);
2772}
2773
2774rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2775PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2776 RTC_DCHECK(IsUnifiedPlan());
2777 for (auto transceiver : transceivers_) {
2778 if (transceiver->mid() == mid) {
2779 return transceiver;
2780 }
2781 }
2782 return nullptr;
2783}
2784
2785rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2786PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2787 RTC_DCHECK(IsUnifiedPlan());
2788 for (auto transceiver : transceivers_) {
2789 if (transceiver->internal()->mline_index() == mline_index) {
2790 return transceiver;
2791 }
2792 }
2793 return nullptr;
2794}
2795
2796rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2797PeerConnection::FindAvailableTransceiverToReceive(
2798 cricket::MediaType media_type) const {
2799 RTC_DCHECK(IsUnifiedPlan());
2800 // From JSEP section 5.10 (Applying a Remote Description):
2801 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2802 // the same type that were added to the PeerConnection by addTrack and are not
2803 // associated with any m= section and are not stopped, find the first such
2804 // RtpTransceiver.
2805 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002806 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002807 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2808 !transceiver->stopped()) {
2809 return transceiver;
2810 }
2811 }
2812 return nullptr;
2813}
2814
Steve Antoned10bd92017-12-05 10:52:59 -08002815const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2816 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2817 transceiver,
2818 const SessionDescriptionInterface* sdesc) const {
2819 RTC_DCHECK(transceiver);
2820 RTC_DCHECK(sdesc);
2821 if (IsUnifiedPlan()) {
2822 if (!transceiver->internal()->mid()) {
2823 // This transceiver is not associated with a media section yet.
2824 return nullptr;
2825 }
2826 return sdesc->description()->GetContentByName(
2827 *transceiver->internal()->mid());
2828 } else {
2829 // Plan B only allows at most one audio and one video section, so use the
2830 // first media section of that type.
2831 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002832 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002833 }
2834}
2835
deadbeef46c73892016-11-16 19:42:04 -08002836PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2837 return configuration_;
2838}
2839
deadbeef293e9262017-01-11 12:28:30 -08002840bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2841 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002842 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002843
Steve Antonc79268f2018-04-24 09:54:10 -07002844 if (IsClosed()) {
2845 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2846 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2847 }
2848
Qingsi Wanga2d60672018-04-11 16:57:45 -07002849 // According to JSEP, after setLocalDescription, changing the candidate pool
2850 // size is not allowed, and changing the set of ICE servers will not result
2851 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002852 if (local_description() && configuration.ice_candidate_pool_size !=
2853 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002854 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2855 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002856 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002857 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002858
deadbeef293e9262017-01-11 12:28:30 -08002859 // The simplest (and most future-compatible) way to tell if the config was
2860 // modified in an invalid way is to copy each property we do support
2861 // modifying, then use operator==. There are far more properties we don't
2862 // support modifying than those we do, and more could be added.
2863 RTCConfiguration modified_config = configuration_;
2864 modified_config.servers = configuration.servers;
2865 modified_config.type = configuration.type;
2866 modified_config.ice_candidate_pool_size =
2867 configuration.ice_candidate_pool_size;
2868 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002869 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002870 modified_config.ice_check_interval_strong_connectivity =
2871 configuration.ice_check_interval_strong_connectivity;
2872 modified_config.ice_check_interval_weak_connectivity =
2873 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002874 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2875 modified_config.ice_unwritable_min_checks =
2876 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002877 modified_config.stun_candidate_keepalive_interval =
2878 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002879 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002880 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002881 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002882 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002883 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2884 }
2885
Steve Anton038834f2017-07-14 15:59:59 -07002886 // Validate the modified configuration.
2887 RTCError validate_error = ValidateConfiguration(modified_config);
2888 if (!validate_error.ok()) {
2889 return SafeSetError(std::move(validate_error), error);
2890 }
2891
deadbeef293e9262017-01-11 12:28:30 -08002892 // Note that this isn't possible through chromium, since it's an unsigned
2893 // short in WebIDL.
2894 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002895 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002896 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2897 }
2898
2899 // Parse ICE servers before hopping to network thread.
2900 cricket::ServerAddresses stun_servers;
2901 std::vector<cricket::RelayServerConfig> turn_servers;
2902 RTCErrorType parse_error =
2903 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2904 if (parse_error != RTCErrorType::NONE) {
2905 return SafeSetError(parse_error, error);
2906 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002907 // Note if STUN or TURN servers were supplied.
2908 if (!stun_servers.empty()) {
2909 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2910 }
2911 if (!turn_servers.empty()) {
2912 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2913 }
deadbeef293e9262017-01-11 12:28:30 -08002914
2915 // In theory this shouldn't fail.
2916 if (!network_thread()->Invoke<bool>(
2917 RTC_FROM_HERE,
2918 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2919 stun_servers, turn_servers, modified_config.type,
2920 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002921 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002922 modified_config.turn_customizer,
2923 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002924 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002925 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2926 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002927
deadbeefd1a38b52016-12-10 13:15:33 -08002928 // As described in JSEP, calling setConfiguration with new ICE servers or
2929 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2930 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002931 if (modified_config.servers != configuration_.servers ||
2932 modified_config.type != configuration_.type ||
2933 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002934 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002935 }
skvladd1f5fda2017-02-03 16:54:05 -08002936
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002937 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002938
deadbeef293e9262017-01-11 12:28:30 -08002939 configuration_ = modified_config;
2940 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002941}
2942
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002943bool PeerConnection::AddIceCandidate(
2944 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002945 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002946 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002947 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002948 return false;
2949 }
Steve Antond25da372017-11-06 14:50:29 -08002950
2951 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002952 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002953 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002954 return false;
2955 }
2956
2957 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002958 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002959 return false;
2960 }
2961
2962 bool valid = false;
2963 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2964 if (!valid) {
2965 return false;
2966 }
2967
2968 // Add this candidate to the remote session description.
2969 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002970 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002971 return false;
2972 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002973 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002974
2975 if (ready) {
2976 return UseCandidate(ice_candidate);
2977 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002978 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002979 return true;
2980 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002981}
2982
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002983bool PeerConnection::RemoveIceCandidates(
2984 const std::vector<cricket::Candidate>& candidates) {
2985 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002986 if (IsClosed()) {
2987 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2988 return false;
2989 }
2990
Steve Antond25da372017-11-06 14:50:29 -08002991 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002992 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2993 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002994 return false;
2995 }
2996
2997 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002998 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002999 return false;
3000 }
3001
3002 size_t number_removed =
3003 mutable_remote_description()->RemoveCandidates(candidates);
3004 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003005 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003006 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003007 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003008 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003009 }
3010
3011 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003012 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3013 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003014 RTC_LOG(LS_ERROR)
3015 << "RemoveIceCandidates: Error when removing remote candidates: "
3016 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003017 }
3018 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003019}
3020
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003021void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003022 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003023 network_thread()->Invoke<void>(
3024 RTC_FROM_HERE,
3025 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3026 // Send information about IPv4/IPv6 status.
3027 if (uma_observer_) {
3028 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3029 uma_observer_->IncrementEnumCounter(
3030 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3031 kPeerConnectionAddressFamilyCounter_Max);
3032 } else {
3033 uma_observer_->IncrementEnumCounter(
3034 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3035 kPeerConnectionAddressFamilyCounter_Max);
3036 }
3037 }
3038}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003039
Qingsi Wanga2d60672018-04-11 16:57:45 -07003040void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3041 RTC_DCHECK(network_thread()->IsCurrent());
3042 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003043 if (transport_controller_) {
3044 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003045 }
3046
3047 for (auto transceiver : transceivers_) {
3048 auto* channel = transceiver->internal()->channel();
3049 if (channel) {
3050 channel->SetMetricsObserver(uma_observer_);
3051 }
3052 }
3053
deadbeef293e9262017-01-11 12:28:30 -08003054 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003055 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003056 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003057}
3058
Niels Möller0c4f7be2018-05-07 14:01:37 +02003059RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003060 if (!worker_thread()->IsCurrent()) {
3061 return worker_thread()->Invoke<RTCError>(
Niels Möller0c4f7be2018-05-07 14:01:37 +02003062 RTC_FROM_HERE, [&](){ return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003063 }
3064
Niels Möller0c4f7be2018-05-07 14:01:37 +02003065 const bool has_min = bitrate.min_bitrate_bps.has_value();
3066 const bool has_start = bitrate.start_bitrate_bps.has_value();
3067 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003068 if (has_min && *bitrate.min_bitrate_bps < 0) {
3069 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3070 "min_bitrate_bps <= 0");
3071 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003072 if (has_start) {
3073 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003074 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003075 "start_bitrate_bps < min_bitrate_bps");
3076 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3078 "curent_bitrate_bps < 0");
3079 }
3080 }
3081 if (has_max) {
Niels Möller0c4f7be2018-05-07 14:01:37 +02003082 if (has_start &&
3083 *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003084 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003085 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003086 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3087 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3088 "max_bitrate_bps < min_bitrate_bps");
3089 } else if (*bitrate.max_bitrate_bps < 0) {
3090 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3091 "max_bitrate_bps < 0");
3092 }
3093 }
3094
zstein4b979802017-06-02 14:37:37 -07003095 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003096 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003097
3098 return RTCError::OK();
3099}
3100
Alex Narest78609d52017-10-20 10:37:47 +02003101void PeerConnection::SetBitrateAllocationStrategy(
3102 std::unique_ptr<rtc::BitrateAllocationStrategy>
3103 bitrate_allocation_strategy) {
3104 rtc::Thread* worker_thread = factory_->worker_thread();
3105 if (!worker_thread->IsCurrent()) {
3106 rtc::BitrateAllocationStrategy* strategy_raw =
3107 bitrate_allocation_strategy.release();
3108 auto functor = [this, strategy_raw]() {
3109 call_->SetBitrateAllocationStrategy(
3110 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3111 };
3112 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3113 return;
3114 }
3115 RTC_DCHECK(call_.get());
3116 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3117}
3118
henrika5f6bf242017-11-01 11:06:56 +01003119void PeerConnection::SetAudioPlayout(bool playout) {
3120 if (!worker_thread()->IsCurrent()) {
3121 worker_thread()->Invoke<void>(
3122 RTC_FROM_HERE,
3123 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3124 return;
3125 }
3126 auto audio_state =
3127 factory_->channel_manager()->media_engine()->GetAudioState();
3128 audio_state->SetPlayout(playout);
3129}
3130
3131void PeerConnection::SetAudioRecording(bool recording) {
3132 if (!worker_thread()->IsCurrent()) {
3133 worker_thread()->Invoke<void>(
3134 RTC_FROM_HERE,
3135 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3136 return;
3137 }
3138 auto audio_state =
3139 factory_->channel_manager()->media_engine()->GetAudioState();
3140 audio_state->SetRecording(recording);
3141}
3142
Steve Anton8c0f7a72017-10-03 10:03:10 -07003143std::unique_ptr<rtc::SSLCertificate>
3144PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003145 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3146 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003147 return nullptr;
3148 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003149 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003150}
3151
Zhi Huang70b820f2018-01-27 14:16:15 -08003152std::unique_ptr<rtc::SSLCertChain>
3153PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003154 auto audio_transceiver = GetFirstAudioTransceiver();
3155 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003156 return nullptr;
3157 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003158 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003159 audio_transceiver->internal()->channel()->transport_name());
3160}
3161
3162rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3163PeerConnection::GetFirstAudioTransceiver() const {
3164 for (auto transceiver : transceivers_) {
3165 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3166 return transceiver;
3167 }
3168 }
3169 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003170}
3171
ivoc14d5dbe2016-07-04 07:06:55 -07003172bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3173 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003174 // TODO(eladalon): It would be better to not allow negative values into PC.
3175 const size_t max_size = (max_size_bytes < 0)
3176 ? RtcEventLog::kUnlimitedOutput
3177 : rtc::saturated_cast<size_t>(max_size_bytes);
3178 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003179 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3180 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003181}
3182
Bjorn Tereliusde939432017-11-20 17:38:14 +01003183bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3184 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003185 // TODO(eladalon): In C++14, this can be done with a lambda.
3186 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003187 bool operator()() {
3188 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3189 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003190 PeerConnection* const pc;
3191 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003192 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003193 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003194 return worker_thread()->Invoke<bool>(
3195 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003196}
3197
3198void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003199 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003200 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3201}
3202
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003204 return pending_local_description_ ? pending_local_description_.get()
3205 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206}
3207
3208const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003209 return pending_remote_description_ ? pending_remote_description_.get()
3210 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003211}
3212
deadbeeffe4a8a42016-12-20 17:56:17 -08003213const SessionDescriptionInterface* PeerConnection::current_local_description()
3214 const {
Steve Anton75737c02017-11-06 10:37:17 -08003215 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003216}
3217
3218const SessionDescriptionInterface* PeerConnection::current_remote_description()
3219 const {
Steve Anton75737c02017-11-06 10:37:17 -08003220 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003221}
3222
3223const SessionDescriptionInterface* PeerConnection::pending_local_description()
3224 const {
Steve Anton75737c02017-11-06 10:37:17 -08003225 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003226}
3227
3228const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3229 const {
Steve Anton75737c02017-11-06 10:37:17 -08003230 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003231}
3232
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003234 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003235 // Update stats here so that we have the most recent stats for tracks and
3236 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003237 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238
Steve Anton75737c02017-11-06 10:37:17 -08003239 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003240 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003241
Steve Anton8af21862017-12-15 11:20:13 -08003242 for (auto transceiver : transceivers_) {
3243 transceiver->Stop();
3244 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003245
3246 // Ensure that all asynchronous stats requests are completed before destroying
3247 // the transport controller below.
3248 if (stats_collector_) {
3249 stats_collector_->WaitForPendingRequest();
3250 }
3251
3252 // Don't destroy BaseChannels until after stats has been cleaned up so that
3253 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003254 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003255
Qingsi Wang93a84392018-01-30 17:13:09 -08003256 // The event log is used in the transport controller, which must be outlived
3257 // by the former. CreateOffer by the peer connection is implemented
3258 // asynchronously and if the peer connection is closed without resetting the
3259 // WebRTC session description factory, the session description factory would
3260 // call the transport controller.
3261 webrtc_session_desc_factory_.reset();
3262 transport_controller_.reset();
3263
deadbeef42a42632017-03-10 15:18:00 -08003264 network_thread()->Invoke<void>(
3265 RTC_FROM_HERE,
3266 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3267 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003268
Steve Anton978b8762017-09-29 12:15:02 -07003269 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003270 call_.reset();
3271 // The event log must outlive call (and any other object that uses it).
3272 event_log_.reset();
3273 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003274 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275}
3276
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003277void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003279 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3280 SetSessionDescriptionMsg* param =
3281 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3282 param->observer->OnSuccess();
3283 delete param;
3284 break;
3285 }
3286 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3287 SetSessionDescriptionMsg* param =
3288 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003289 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003290 delete param;
3291 break;
3292 }
deadbeefab9b2d12015-10-14 11:33:11 -07003293 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3294 CreateSessionDescriptionMsg* param =
3295 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003296 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003297 delete param;
3298 break;
3299 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003300 case MSG_GETSTATS: {
3301 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003302 StatsReports reports;
3303 stats_->GetStats(param->track, &reports);
3304 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003305 delete param;
3306 break;
3307 }
deadbeefbd292462015-12-14 18:15:29 -08003308 case MSG_FREE_DATACHANNELS: {
3309 sctp_data_channels_to_free_.clear();
3310 break;
3311 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003312 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003313 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314 break;
3315 }
3316}
3317
Steve Antonafb0bb72018-02-20 11:35:37 -08003318cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3319 RTC_DCHECK(!IsUnifiedPlan());
3320 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3321 GetAudioTransceiver()->internal()->channel());
3322 if (voice_channel) {
3323 return voice_channel->media_channel();
3324 } else {
3325 return nullptr;
3326 }
3327}
3328
3329cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3330 RTC_DCHECK(!IsUnifiedPlan());
3331 auto* video_channel = static_cast<cricket::VideoChannel*>(
3332 GetVideoTransceiver()->internal()->channel());
3333 if (video_channel) {
3334 return video_channel->media_channel();
3335 } else {
3336 return nullptr;
3337 }
3338}
3339
Steve Anton4171afb2017-11-20 10:20:22 -08003340void PeerConnection::CreateAudioReceiver(
3341 MediaStreamInterface* stream,
3342 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003343 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3344 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003345 auto* audio_receiver = new AudioRtpReceiver(
3346 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003347 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003348 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3349 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3350 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003351 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003352 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003353 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354}
3355
Steve Anton4171afb2017-11-20 10:20:22 -08003356void PeerConnection::CreateVideoReceiver(
3357 MediaStreamInterface* stream,
3358 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003359 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3360 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003361 auto* video_receiver = new VideoRtpReceiver(
3362 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003363 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003364 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3365 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3366 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003367 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003368 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003369 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370}
3371
deadbeef70ab1a12015-09-28 16:53:55 -07003372// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3373// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003374rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003375 const RtpSenderInfo& remote_sender_info) {
3376 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3377 if (!receiver) {
3378 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3379 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003380 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003381 }
Steve Anton4171afb2017-11-20 10:20:22 -08003382 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3383 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3384 } else {
3385 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3386 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003387 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003388}
3389
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003390void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3391 MediaStreamInterface* stream) {
3392 RTC_DCHECK(!IsClosed());
3393 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003394 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003395 // We already have a sender for this track, so just change the stream_id
3396 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003397 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003398 return;
3399 }
3400
3401 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003402 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003403 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003404 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003405 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003406 // If the sender has already been configured in SDP, we call SetSsrc,
3407 // which will connect the sender to the underlying transport. This can
3408 // occur if a local session description that contains the ID of the sender
3409 // is set before AddStream is called. It can also occur if the local
3410 // session description is not changed and RemoveStream is called, and
3411 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003412 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003413 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003414 if (sender_info) {
3415 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003416 }
3417}
3418
3419// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3420// indefinitely, when we have unified plan SDP.
3421void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3422 MediaStreamInterface* stream) {
3423 RTC_DCHECK(!IsClosed());
3424 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003425 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003426 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3427 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003428 return;
3429 }
Steve Anton4171afb2017-11-20 10:20:22 -08003430 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003431}
3432
3433void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3434 MediaStreamInterface* stream) {
3435 RTC_DCHECK(!IsClosed());
3436 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003437 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003438 // We already have a sender for this track, so just change the stream_id
3439 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003440 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003441 return;
3442 }
3443
3444 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003445 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003446 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003447 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003448 GetVideoTransceiver()->internal()->AddSender(new_sender);
3449 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003450 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003451 if (sender_info) {
3452 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003453 }
3454}
3455
3456void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3457 MediaStreamInterface* stream) {
3458 RTC_DCHECK(!IsClosed());
3459 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003460 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003461 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3462 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003463 return;
3464 }
Steve Anton4171afb2017-11-20 10:20:22 -08003465 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003466}
3467
Steve Antonba818672017-11-06 10:21:57 -08003468void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003469 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003470 if (ice_connection_state_ == new_state) {
3471 return;
3472 }
3473
deadbeefcbecd352015-09-23 11:50:27 -07003474 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003475 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003476 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003477 return;
3478 }
Steve Antonba818672017-11-06 10:21:57 -08003479
Mirko Bonadei675513b2017-11-09 11:09:25 +01003480 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3481 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003482 RTC_DCHECK(ice_connection_state_ !=
3483 PeerConnectionInterface::kIceConnectionClosed);
3484
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003485 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003486 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003487}
3488
3489void PeerConnection::OnIceGatheringChange(
3490 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003491 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003492 if (IsClosed()) {
3493 return;
3494 }
3495 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003496 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497}
3498
jbauch81bf7b02017-03-25 08:31:12 -07003499void PeerConnection::OnIceCandidate(
3500 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003501 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003502 if (IsClosed()) {
3503 return;
3504 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003505 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003506 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003507}
3508
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003509void PeerConnection::OnIceCandidatesRemoved(
3510 const std::vector<cricket::Candidate>& candidates) {
3511 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003512 if (IsClosed()) {
3513 return;
3514 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003515 observer_->OnIceCandidatesRemoved(candidates);
3516}
3517
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003518void PeerConnection::ChangeSignalingState(
3519 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003520 RTC_DCHECK(signaling_thread()->IsCurrent());
3521 if (signaling_state_ == signaling_state) {
3522 return;
3523 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003524 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3525 << GetSignalingStateString(signaling_state_)
3526 << " New state: "
3527 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003528 signaling_state_ = signaling_state;
3529 if (signaling_state == kClosed) {
3530 ice_connection_state_ = kIceConnectionClosed;
3531 observer_->OnIceConnectionChange(ice_connection_state_);
3532 if (ice_gathering_state_ != kIceGatheringComplete) {
3533 ice_gathering_state_ = kIceGatheringComplete;
3534 observer_->OnIceGatheringChange(ice_gathering_state_);
3535 }
3536 }
3537 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538}
3539
deadbeefeb459812015-12-15 19:24:43 -08003540void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3541 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003542 if (IsClosed()) {
3543 return;
3544 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003545 AddAudioTrack(track, stream);
3546 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003547}
3548
deadbeefeb459812015-12-15 19:24:43 -08003549void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3550 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003551 if (IsClosed()) {
3552 return;
3553 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003554 RemoveAudioTrack(track, stream);
3555 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003556}
3557
3558void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3559 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003560 if (IsClosed()) {
3561 return;
3562 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003563 AddVideoTrack(track, stream);
3564 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003565}
3566
3567void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3568 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003569 if (IsClosed()) {
3570 return;
3571 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003572 RemoveVideoTrack(track, stream);
3573 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003574}
3575
Henrik Boström31638672017-11-23 17:48:32 +01003576void PeerConnection::PostSetSessionDescriptionSuccess(
3577 SetSessionDescriptionObserver* observer) {
3578 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3579 signaling_thread()->Post(RTC_FROM_HERE, this,
3580 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3581}
3582
deadbeefab9b2d12015-10-14 11:33:11 -07003583void PeerConnection::PostSetSessionDescriptionFailure(
3584 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003585 RTCError&& error) {
3586 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003587 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003588 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003589 signaling_thread()->Post(RTC_FROM_HERE, this,
3590 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003591}
3592
3593void PeerConnection::PostCreateSessionDescriptionFailure(
3594 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003595 RTCError error) {
3596 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003597 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(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_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003601}
3602
zhihuang1c378ed2017-08-17 14:10:50 -07003603void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003604 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003605 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003606 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003607
Steve Antondcc3c022017-12-22 16:02:54 -08003608 if (IsUnifiedPlan()) {
3609 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3610 } else {
3611 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3612 }
3613
Steve Antonfa2260d2017-12-28 16:38:23 -08003614 // Intentionally unset the data channel type for RTP data channel with the
3615 // second condition. Otherwise the RTP data channels would be successfully
3616 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3617 // when building with chromium. We want to leave RTP data channels broken, so
3618 // people won't try to use them.
3619 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3620 session_options->data_channel_type = data_channel_type();
3621 }
3622
Steve Antondcc3c022017-12-22 16:02:54 -08003623 // Apply ICE restart flag and renomination flag.
3624 for (auto& options : session_options->media_description_options) {
3625 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3626 options.transport_options.enable_ice_renomination =
3627 configuration_.enable_ice_renomination;
3628 }
3629
3630 session_options->rtcp_cname = rtcp_cname_;
3631 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003632 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003633}
3634
3635void PeerConnection::GetOptionsForPlanBOffer(
3636 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3637 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003638 // Figure out transceiver directional preferences.
3639 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3640 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3641
3642 // By default, generate sendrecv/recvonly m= sections.
3643 bool recv_audio = true;
3644 bool recv_video = true;
3645
3646 // By default, only offer a new m= section if we have media to send with it.
3647 bool offer_new_audio_description = send_audio;
3648 bool offer_new_video_description = send_video;
3649 bool offer_new_data_description = HasDataChannels();
3650
3651 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003652 if (offer_answer_options.offer_to_receive_audio !=
3653 RTCOfferAnswerOptions::kUndefined) {
3654 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003655 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003656 offer_new_audio_description ||
3657 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003658 }
Steve Antondcc3c022017-12-22 16:02:54 -08003659 if (offer_answer_options.offer_to_receive_video !=
3660 RTCOfferAnswerOptions::kUndefined) {
3661 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003662 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003663 offer_new_video_description ||
3664 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003665 }
3666
3667 rtc::Optional<size_t> audio_index;
3668 rtc::Optional<size_t> video_index;
3669 rtc::Optional<size_t> data_index;
3670 // If a current description exists, generate m= sections in the same order,
3671 // using the first audio/video/data section that appears and rejecting
3672 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003673 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003674 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003675 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003676 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3677 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3678 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003679 }
3680
zhihuang1c378ed2017-08-17 14:10:50 -07003681 // Add audio/video/data m= sections to the end if needed.
3682 if (!audio_index && offer_new_audio_description) {
3683 session_options->media_description_options.push_back(
3684 cricket::MediaDescriptionOptions(
3685 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003686 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3687 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003688 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003689 }
zhihuang1c378ed2017-08-17 14:10:50 -07003690 if (!video_index && offer_new_video_description) {
3691 session_options->media_description_options.push_back(
3692 cricket::MediaDescriptionOptions(
3693 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003694 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3695 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003696 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003697 }
zhihuang1c378ed2017-08-17 14:10:50 -07003698 if (!data_index && offer_new_data_description) {
3699 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003700 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003701 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003702 }
3703
3704 cricket::MediaDescriptionOptions* audio_media_description_options =
3705 !audio_index ? nullptr
3706 : &session_options->media_description_options[*audio_index];
3707 cricket::MediaDescriptionOptions* video_media_description_options =
3708 !video_index ? nullptr
3709 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003710
Steve Anton4171afb2017-11-20 10:20:22 -08003711 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003712 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003713}
3714
3715// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3716// and return a reference to it.
3717// Generated MIDs should be no more than 3 bytes long to take up less space in
3718// the RTP packet.
3719static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3720 RTC_DCHECK(used_mids);
3721 // We're boring: just generate MIDs 0, 1, 2, ...
3722 size_t i = 0;
3723 std::set<std::string>::iterator it;
3724 bool inserted;
3725 do {
3726 std::string mid = rtc::ToString(i++);
3727 auto insert_result = used_mids->insert(mid);
3728 it = insert_result.first;
3729 inserted = insert_result.second;
3730 } while (!inserted);
3731 return *it;
3732}
3733
3734static cricket::MediaDescriptionOptions
3735GetMediaDescriptionOptionsForTransceiver(
3736 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3737 transceiver,
3738 const std::string& mid) {
3739 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003740 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003741 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003742 // This behavior is specified in JSEP. The gist is that:
3743 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3744 // sendrecv.
3745 // 2. If the MSID is included, then it must be included in any subsequent
3746 // offer/answer exactly the same until the RtpTransceiver is stopped.
3747 if (!transceiver->stopped() &&
3748 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3749 transceiver->internal()->has_ever_been_used_to_send())) {
3750 cricket::SenderOptions sender_options;
3751 sender_options.track_id = transceiver->sender()->id();
3752 sender_options.stream_ids = transceiver->sender()->stream_ids();
3753 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3754 // set in the RTP parameters when the transceiver was added.
3755 sender_options.num_sim_layers = 1;
3756 media_description_options.sender_options.push_back(sender_options);
3757 }
Steve Antondcc3c022017-12-22 16:02:54 -08003758 return media_description_options;
3759}
3760
3761void PeerConnection::GetOptionsForUnifiedPlanOffer(
3762 const RTCOfferAnswerOptions& offer_answer_options,
3763 cricket::MediaSessionOptions* session_options) {
3764 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3765 // Offers) and 5.2.2 (Subsequent Offers).
3766 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3767 const ContentInfos& local_contents =
3768 (local_description() ? local_description()->description()->contents()
3769 : ContentInfos());
3770 const ContentInfos& remote_contents =
3771 (remote_description() ? remote_description()->description()->contents()
3772 : ContentInfos());
3773 // The mline indices that can be recycled. New transceivers should reuse these
3774 // slots first.
3775 std::queue<size_t> recycleable_mline_indices;
3776 // Track the MIDs used in previous offer/answer exchanges and the current
3777 // offer so that new, unique MIDs are generated.
3778 std::set<std::string> used_mids = seen_mids_;
3779 // First, go through each media section that exists in either the local or
3780 // remote description and generate a media section in this offer for the
3781 // associated transceiver. If a media section can be recycled, generate a
3782 // default, rejected media section here that can be later overwritten.
3783 for (size_t i = 0;
3784 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3785 // Either |local_content| or |remote_content| is non-null.
3786 const ContentInfo* local_content =
3787 (i < local_contents.size() ? &local_contents[i] : nullptr);
3788 const ContentInfo* remote_content =
3789 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3790 bool had_been_rejected = (local_content && local_content->rejected) ||
3791 (remote_content && remote_content->rejected);
3792 const std::string& mid =
3793 (local_content ? local_content->name : remote_content->name);
3794 cricket::MediaType media_type =
3795 (local_content ? local_content->media_description()->type()
3796 : remote_content->media_description()->type());
3797 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3798 media_type == cricket::MEDIA_TYPE_VIDEO) {
3799 auto transceiver = GetAssociatedTransceiver(mid);
3800 RTC_CHECK(transceiver);
3801 // A media section is considered eligible for recycling if it is marked as
3802 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003803 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003804 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003805 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3806 RtpTransceiverDirection::kInactive,
3807 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003808 recycleable_mline_indices.push(i);
3809 } else {
3810 session_options->media_description_options.push_back(
3811 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3812 // CreateOffer shouldn't really cause any state changes in
3813 // PeerConnection, but we need a way to match new transceivers to new
3814 // media sections in SetLocalDescription and JSEP specifies this is done
3815 // by recording the index of the media section generated for the
3816 // transceiver in the offer.
3817 transceiver->internal()->set_mline_index(i);
3818 }
3819 } else {
3820 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003821 RTC_CHECK(GetDataMid());
3822 if (had_been_rejected || mid != *GetDataMid()) {
3823 session_options->media_description_options.push_back(
3824 GetMediaDescriptionOptionsForRejectedData(mid));
3825 } else {
3826 session_options->media_description_options.push_back(
3827 GetMediaDescriptionOptionsForActiveData(mid));
3828 }
Steve Antondcc3c022017-12-22 16:02:54 -08003829 }
3830 }
3831 // Next, look for transceivers that are newly added (that is, are not stopped
3832 // and not associated). Reuse media sections marked as recyclable first,
3833 // otherwise append to the end of the offer. New media sections should be
3834 // added in the order they were added to the PeerConnection.
3835 for (auto transceiver : transceivers_) {
3836 if (transceiver->mid() || transceiver->stopped()) {
3837 continue;
3838 }
3839 size_t mline_index;
3840 if (!recycleable_mline_indices.empty()) {
3841 mline_index = recycleable_mline_indices.front();
3842 recycleable_mline_indices.pop();
3843 session_options->media_description_options[mline_index] =
3844 GetMediaDescriptionOptionsForTransceiver(transceiver,
3845 AllocateMid(&used_mids));
3846 } else {
3847 mline_index = session_options->media_description_options.size();
3848 session_options->media_description_options.push_back(
3849 GetMediaDescriptionOptionsForTransceiver(transceiver,
3850 AllocateMid(&used_mids)));
3851 }
3852 // See comment above for why CreateOffer changes the transceiver's state.
3853 transceiver->internal()->set_mline_index(mline_index);
3854 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003855 // Lastly, add a m-section if we have local data channels and an m section
3856 // does not already exist.
3857 if (!GetDataMid() && HasDataChannels()) {
3858 session_options->media_description_options.push_back(
3859 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3860 }
Steve Antondcc3c022017-12-22 16:02:54 -08003861}
3862
3863void PeerConnection::GetOptionsForAnswer(
3864 const RTCOfferAnswerOptions& offer_answer_options,
3865 cricket::MediaSessionOptions* session_options) {
3866 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3867
3868 if (IsUnifiedPlan()) {
3869 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3870 } else {
3871 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3872 }
3873
Steve Antonfa2260d2017-12-28 16:38:23 -08003874 // Intentionally unset the data channel type for RTP data channel. Otherwise
3875 // the RTP data channels would be successfully negotiated by default and the
3876 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3877 // We want to leave RTP data channels broken, so people won't try to use them.
3878 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3879 session_options->data_channel_type = data_channel_type();
3880 }
3881
Steve Antondcc3c022017-12-22 16:02:54 -08003882 // Apply ICE renomination flag.
3883 for (auto& options : session_options->media_description_options) {
3884 options.transport_options.enable_ice_renomination =
3885 configuration_.enable_ice_renomination;
3886 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003887
3888 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003889 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003890 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003891}
3892
Steve Antondcc3c022017-12-22 16:02:54 -08003893void PeerConnection::GetOptionsForPlanBAnswer(
3894 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003895 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003896 // Figure out transceiver directional preferences.
3897 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3898 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3899
3900 // By default, generate sendrecv/recvonly m= sections. The direction is also
3901 // restricted by the direction in the offer.
3902 bool recv_audio = true;
3903 bool recv_video = true;
3904
3905 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003906 if (offer_answer_options.offer_to_receive_audio !=
3907 RTCOfferAnswerOptions::kUndefined) {
3908 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003909 }
Steve Antondcc3c022017-12-22 16:02:54 -08003910 if (offer_answer_options.offer_to_receive_video !=
3911 RTCOfferAnswerOptions::kUndefined) {
3912 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003913 }
3914
3915 rtc::Optional<size_t> audio_index;
3916 rtc::Optional<size_t> video_index;
3917 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003918
3919 // Generate m= sections that match those in the offer.
3920 // Note that mediasession.cc will handle intersection our preferred
3921 // direction with the offered direction.
3922 GenerateMediaDescriptionOptions(
3923 remote_description(),
3924 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3925 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3926 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003927
3928 cricket::MediaDescriptionOptions* audio_media_description_options =
3929 !audio_index ? nullptr
3930 : &session_options->media_description_options[*audio_index];
3931 cricket::MediaDescriptionOptions* video_media_description_options =
3932 !video_index ? nullptr
3933 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003934
Steve Anton4171afb2017-11-20 10:20:22 -08003935 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003936 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003937}
zhihuangaf388472016-11-02 16:49:48 -07003938
Steve Antondcc3c022017-12-22 16:02:54 -08003939void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3940 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3941 cricket::MediaSessionOptions* session_options) {
3942 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3943 // Answers) and 5.3.2 (Subsequent Answers).
3944 RTC_DCHECK(remote_description());
3945 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3946 for (const ContentInfo& content :
3947 remote_description()->description()->contents()) {
3948 cricket::MediaType media_type = content.media_description()->type();
3949 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3950 media_type == cricket::MEDIA_TYPE_VIDEO) {
3951 auto transceiver = GetAssociatedTransceiver(content.name);
3952 RTC_CHECK(transceiver);
3953 session_options->media_description_options.push_back(
3954 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3955 } else {
3956 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003957 // Reject all data sections if data channels are disabled.
3958 // Reject a data section if it has already been rejected.
3959 // Reject all data sections except for the first one.
3960 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3961 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003962 session_options->media_description_options.push_back(
3963 GetMediaDescriptionOptionsForRejectedData(content.name));
3964 } else {
3965 session_options->media_description_options.push_back(
3966 GetMediaDescriptionOptionsForActiveData(content.name));
3967 }
Steve Antondcc3c022017-12-22 16:02:54 -08003968 }
3969 }
htaa2a49d92016-03-04 02:51:39 -08003970}
3971
zhihuang1c378ed2017-08-17 14:10:50 -07003972void PeerConnection::GenerateMediaDescriptionOptions(
3973 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003974 RtpTransceiverDirection audio_direction,
3975 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003976 rtc::Optional<size_t>* audio_index,
3977 rtc::Optional<size_t>* video_index,
3978 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003979 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003980 for (const cricket::ContentInfo& content :
3981 session_desc->description()->contents()) {
3982 if (IsAudioContent(&content)) {
3983 // If we already have an audio m= section, reject this extra one.
3984 if (*audio_index) {
3985 session_options->media_description_options.push_back(
3986 cricket::MediaDescriptionOptions(
3987 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003988 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003989 } else {
3990 session_options->media_description_options.push_back(
3991 cricket::MediaDescriptionOptions(
3992 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003993 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003994 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003995 }
3996 } else if (IsVideoContent(&content)) {
3997 // If we already have an video m= section, reject this extra one.
3998 if (*video_index) {
3999 session_options->media_description_options.push_back(
4000 cricket::MediaDescriptionOptions(
4001 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004002 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004003 } else {
4004 session_options->media_description_options.push_back(
4005 cricket::MediaDescriptionOptions(
4006 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004007 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004008 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004009 }
4010 } else {
4011 RTC_DCHECK(IsDataContent(&content));
4012 // If we already have an data m= section, reject this extra one.
4013 if (*data_index) {
4014 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004015 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004016 } else {
4017 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004018 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004019 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004020 }
4021 }
htaa2a49d92016-03-04 02:51:39 -08004022 }
deadbeefab9b2d12015-10-14 11:33:11 -07004023}
4024
Steve Antonfa2260d2017-12-28 16:38:23 -08004025cricket::MediaDescriptionOptions
4026PeerConnection::GetMediaDescriptionOptionsForActiveData(
4027 const std::string& mid) const {
4028 // Direction for data sections is meaningless, but legacy endpoints might
4029 // expect sendrecv.
4030 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4031 RtpTransceiverDirection::kSendRecv,
4032 /*stopped=*/false);
4033 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4034 return options;
4035}
4036
4037cricket::MediaDescriptionOptions
4038PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4039 const std::string& mid) const {
4040 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4041 RtpTransceiverDirection::kInactive,
4042 /*stopped=*/true);
4043 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4044 return options;
4045}
4046
4047rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4048 switch (data_channel_type_) {
4049 case cricket::DCT_RTP:
4050 if (!rtp_data_channel_) {
4051 return rtc::nullopt;
4052 }
4053 return rtp_data_channel_->content_name();
4054 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004055 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004056 default:
4057 return rtc::nullopt;
4058 }
4059}
4060
Steve Anton4171afb2017-11-20 10:20:22 -08004061void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4062 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4063 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004064 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004065}
4066
Steve Anton4171afb2017-11-20 10:20:22 -08004067void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004068 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004069 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004070 cricket::MediaType media_type,
4071 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004072 RTC_DCHECK(!IsUnifiedPlan());
4073
Steve Anton4171afb2017-11-20 10:20:22 -08004074 std::vector<RtpSenderInfo>* current_senders =
4075 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004076
Steve Anton4171afb2017-11-20 10:20:22 -08004077 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004078 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004079 for (auto sender_it = current_senders->begin();
4080 sender_it != current_senders->end();
4081 /* incremented manually */) {
4082 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004083 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004084 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004085 std::string params_stream_id;
4086 if (params) {
4087 params_stream_id =
4088 (!params->first_stream_id().empty() ? params->first_stream_id()
4089 : kDefaultStreamId);
4090 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004091 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004092 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004093 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004094 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004095 sender_exists) {
4096 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004097 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004098 OnRemoteSenderRemoved(info, media_type);
4099 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004100 }
4101 }
4102
Steve Anton4171afb2017-11-20 10:20:22 -08004103 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004104 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004105 if (!params.has_ssrcs()) {
4106 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4107 // sender, this means it is coming from a Unified Plan endpoint,so we just
4108 // create a default.
4109 default_sender_needed = true;
4110 break;
4111 }
4112
Seth Hampson845e8782018-03-02 11:34:10 -08004113 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004114 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004115 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4116 // not supported in Plan B, we just take the first here and create the
4117 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004118 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004119 (!params.first_stream_id().empty() ? params.first_stream_id()
4120 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004121 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004122 uint32_t ssrc = params.first_ssrc();
4123
4124 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004125 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004126 if (!stream) {
4127 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004128 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004129 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004130 remote_streams_->AddStream(stream);
4131 new_streams->AddStream(stream);
4132 }
4133
Steve Anton4171afb2017-11-20 10:20:22 -08004134 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004135 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004136 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004137 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004138 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004139 }
4140 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004141
Steve Anton4171afb2017-11-20 10:20:22 -08004142 // Add default sender if necessary.
4143 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004144 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004145 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004146 if (!default_stream) {
4147 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004148 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004149 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004150 remote_streams_->AddStream(default_stream);
4151 new_streams->AddStream(default_stream);
4152 }
Steve Anton4171afb2017-11-20 10:20:22 -08004153 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4154 ? kDefaultAudioSenderId
4155 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004156 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004157 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004158 if (!default_sender_info) {
4159 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004160 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004161 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004162 }
4163 }
deadbeefab9b2d12015-10-14 11:33:11 -07004164}
4165
Steve Anton4171afb2017-11-20 10:20:22 -08004166void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4167 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004168 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4169 << " receiver for track_id=" << sender_info.sender_id
4170 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004171
Steve Anton3d954a62018-04-02 11:27:23 -07004172 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004173 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004174 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004175 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004176 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004177 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004178 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004179 }
4180}
4181
Steve Anton4171afb2017-11-20 10:20:22 -08004182void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4183 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004184 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4185 << " receiver for track_id=" << sender_info.sender_id
4186 << " and stream_id=" << sender_info.stream_id;
4187
Seth Hampson845e8782018-03-02 11:34:10 -08004188 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004189
Henrik Boström933d8b02017-10-10 10:05:16 -07004190 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004191 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004192 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4193 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004194 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004195 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004196 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004197 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004198 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004199 }
4200 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004201 // Stopping or destroying a VideoRtpReceiver will end the
4202 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004203 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004204 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004205 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004206 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004207 // There's no guarantee the track is still available, e.g. the track may
4208 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004209 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004210 }
4211 } else {
nisseede5da42017-01-12 05:15:36 -08004212 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004213 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004214 if (receiver) {
4215 observer_->OnRemoveTrack(receiver);
4216 }
deadbeefab9b2d12015-10-14 11:33:11 -07004217}
4218
4219void PeerConnection::UpdateEndedRemoteMediaStreams() {
4220 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4221 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4222 MediaStreamInterface* stream = remote_streams_->at(i);
4223 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4224 streams_to_remove.push_back(stream);
4225 }
4226 }
4227
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004228 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004229 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004230 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004231 }
4232}
4233
Steve Anton4171afb2017-11-20 10:20:22 -08004234void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004235 const std::vector<cricket::StreamParams>& streams,
4236 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004237 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004238
Seth Hampson845e8782018-03-02 11:34:10 -08004239 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004240 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004241 for (auto sender_it = current_senders->begin();
4242 sender_it != current_senders->end();
4243 /* incremented manually */) {
4244 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004245 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004246 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4247 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004248 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004249 OnLocalSenderRemoved(info, media_type);
4250 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004251 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004252 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004253 }
4254 }
4255
Steve Anton4171afb2017-11-20 10:20:22 -08004256 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004257 for (const cricket::StreamParams& params : streams) {
4258 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004259 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004260 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004261 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004262 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004263 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004264 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004265 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004266 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004267 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004268 }
4269 }
4270}
4271
Steve Anton4171afb2017-11-20 10:20:22 -08004272void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4273 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004274 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004275 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004276 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004277 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4278 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004279 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004280 return;
4281 }
4282
deadbeeffac06552015-11-25 11:26:01 -08004283 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004284 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004285 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004286 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004287 }
deadbeeffac06552015-11-25 11:26:01 -08004288
Seth Hampson5b4f0752018-04-02 16:31:36 -07004289 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004290 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004291}
4292
Steve Anton4171afb2017-11-20 10:20:22 -08004293void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4294 cricket::MediaType media_type) {
4295 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004296 if (!sender) {
4297 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004298 // SessionDescriptions has been renegotiated.
4299 return;
4300 }
deadbeeffac06552015-11-25 11:26:01 -08004301
4302 // A sender has been removed from the SessionDescription but it's still
4303 // associated with the PeerConnection. This only occurs if the SDP doesn't
4304 // match with the calls to CreateSender, AddStream and RemoveStream.
4305 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004306 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004307 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004308 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004309 }
deadbeeffac06552015-11-25 11:26:01 -08004310
Steve Anton4171afb2017-11-20 10:20:22 -08004311 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004312}
4313
4314void PeerConnection::UpdateLocalRtpDataChannels(
4315 const cricket::StreamParamsVec& streams) {
4316 std::vector<std::string> existing_channels;
4317
4318 // Find new and active data channels.
4319 for (const cricket::StreamParams& params : streams) {
4320 // |it->sync_label| is actually the data channel label. The reason is that
4321 // we use the same naming of data channels as we do for
4322 // MediaStreams and Tracks.
4323 // For MediaStreams, the sync_label is the MediaStream label and the
4324 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004325 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004326 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004327 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004328 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004329 continue;
4330 }
4331 // Set the SSRC the data channel should use for sending.
4332 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4333 existing_channels.push_back(data_channel_it->first);
4334 }
4335
4336 UpdateClosingRtpDataChannels(existing_channels, true);
4337}
4338
4339void PeerConnection::UpdateRemoteRtpDataChannels(
4340 const cricket::StreamParamsVec& streams) {
4341 std::vector<std::string> existing_channels;
4342
4343 // Find new and active data channels.
4344 for (const cricket::StreamParams& params : streams) {
4345 // The data channel label is either the mslabel or the SSRC if the mslabel
4346 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004347 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004348 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004349 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004350 auto data_channel_it = rtp_data_channels_.find(label);
4351 if (data_channel_it == rtp_data_channels_.end()) {
4352 // This is a new data channel.
4353 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4354 } else {
4355 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4356 }
4357 existing_channels.push_back(label);
4358 }
4359
4360 UpdateClosingRtpDataChannels(existing_channels, false);
4361}
4362
4363void PeerConnection::UpdateClosingRtpDataChannels(
4364 const std::vector<std::string>& active_channels,
4365 bool is_local_update) {
4366 auto it = rtp_data_channels_.begin();
4367 while (it != rtp_data_channels_.end()) {
4368 DataChannel* data_channel = it->second;
4369 if (std::find(active_channels.begin(), active_channels.end(),
4370 data_channel->label()) != active_channels.end()) {
4371 ++it;
4372 continue;
4373 }
4374
4375 if (is_local_update) {
4376 data_channel->SetSendSsrc(0);
4377 } else {
4378 data_channel->RemotePeerRequestClose();
4379 }
4380
4381 if (data_channel->state() == DataChannel::kClosed) {
4382 rtp_data_channels_.erase(it);
4383 it = rtp_data_channels_.begin();
4384 } else {
4385 ++it;
4386 }
4387 }
4388}
4389
4390void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4391 uint32_t remote_ssrc) {
4392 rtc::scoped_refptr<DataChannel> channel(
4393 InternalCreateDataChannel(label, nullptr));
4394 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004395 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004396 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004397 return;
4398 }
4399 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004400 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4401 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004402 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004403}
4404
4405rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4406 const std::string& label,
4407 const InternalDataChannelInit* config) {
4408 if (IsClosed()) {
4409 return nullptr;
4410 }
Steve Anton75737c02017-11-06 10:37:17 -08004411 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004412 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004413 << "InternalCreateDataChannel: Data is not supported in this call.";
4414 return nullptr;
4415 }
4416 InternalDataChannelInit new_config =
4417 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004418 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004419 if (new_config.id < 0) {
4420 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004421 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004422 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004423 RTC_LOG(LS_ERROR)
4424 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004425 return nullptr;
4426 }
4427 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004428 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004429 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004430 return nullptr;
4431 }
4432 }
4433
Steve Anton75737c02017-11-06 10:37:17 -08004434 rtc::scoped_refptr<DataChannel> channel(
4435 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004436 if (!channel) {
4437 sid_allocator_.ReleaseSid(new_config.id);
4438 return nullptr;
4439 }
4440
4441 if (channel->data_channel_type() == cricket::DCT_RTP) {
4442 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004443 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4444 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004445 return nullptr;
4446 }
4447 rtp_data_channels_[channel->label()] = channel;
4448 } else {
4449 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4450 sctp_data_channels_.push_back(channel);
4451 channel->SignalClosed.connect(this,
4452 &PeerConnection::OnSctpDataChannelClosed);
4453 }
4454
Steve Anton2d8609c2018-01-23 16:38:46 -08004455 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004456 return channel;
4457}
4458
4459bool PeerConnection::HasDataChannels() const {
4460 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4461}
4462
4463void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4464 for (const auto& channel : sctp_data_channels_) {
4465 if (channel->id() < 0) {
4466 int sid;
4467 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004468 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004469 continue;
4470 }
4471 channel->SetSctpSid(sid);
4472 }
4473 }
4474}
4475
4476void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004477 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004478 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4479 ++it) {
4480 if (it->get() == channel) {
4481 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004482 // After the closing procedure is done, it's safe to use this ID for
4483 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004484 sid_allocator_.ReleaseSid(channel->id());
4485 }
deadbeefbd292462015-12-14 18:15:29 -08004486 // Since this method is triggered by a signal from the DataChannel,
4487 // we can't free it directly here; we need to free it asynchronously.
4488 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004489 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004490 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4491 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004492 return;
4493 }
4494 }
4495}
4496
deadbeefab9b2d12015-10-14 11:33:11 -07004497void PeerConnection::OnDataChannelDestroyed() {
4498 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4499 // DataChannel may callback to us and try to modify the list.
4500 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4501 temp_rtp_dcs.swap(rtp_data_channels_);
4502 for (const auto& kv : temp_rtp_dcs) {
4503 kv.second->OnTransportChannelDestroyed();
4504 }
4505
4506 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4507 temp_sctp_dcs.swap(sctp_data_channels_);
4508 for (const auto& channel : temp_sctp_dcs) {
4509 channel->OnTransportChannelDestroyed();
4510 }
4511}
4512
4513void PeerConnection::OnDataChannelOpenMessage(
4514 const std::string& label,
4515 const InternalDataChannelInit& config) {
4516 rtc::scoped_refptr<DataChannel> channel(
4517 InternalCreateDataChannel(label, &config));
4518 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004519 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004520 return;
4521 }
4522
deadbeefa601f5c2016-06-06 14:27:39 -07004523 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4524 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004525 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004526}
4527
Steve Anton4171afb2017-11-20 10:20:22 -08004528rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4529PeerConnection::GetAudioTransceiver() const {
4530 // This method only works with Plan B SDP, where there is a single
4531 // audio/video transceiver.
4532 RTC_DCHECK(!IsUnifiedPlan());
4533 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004534 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004535 return transceiver;
4536 }
4537 }
4538 RTC_NOTREACHED();
4539 return nullptr;
4540}
4541
4542rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4543PeerConnection::GetVideoTransceiver() const {
4544 // This method only works with Plan B SDP, where there is a single
4545 // audio/video transceiver.
4546 RTC_DCHECK(!IsUnifiedPlan());
4547 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004548 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004549 return transceiver;
4550 }
4551 }
4552 RTC_NOTREACHED();
4553 return nullptr;
4554}
4555
4556// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4557// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004558bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004559 switch (type) {
4560 case cricket::MEDIA_TYPE_AUDIO:
4561 return !GetAudioTransceiver()->internal()->senders().empty();
4562 case cricket::MEDIA_TYPE_VIDEO:
4563 return !GetVideoTransceiver()->internal()->senders().empty();
4564 case cricket::MEDIA_TYPE_DATA:
4565 return false;
4566 }
4567 RTC_NOTREACHED();
4568 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004569}
4570
Steve Anton4171afb2017-11-20 10:20:22 -08004571rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4572PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4573 for (auto transceiver : transceivers_) {
4574 for (auto sender : transceiver->internal()->senders()) {
4575 if (sender->track() == track) {
4576 return sender;
4577 }
4578 }
4579 }
4580 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004581}
4582
Steve Anton4171afb2017-11-20 10:20:22 -08004583rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4584PeerConnection::FindSenderById(const std::string& sender_id) const {
4585 for (auto transceiver : transceivers_) {
4586 for (auto sender : transceiver->internal()->senders()) {
4587 if (sender->id() == sender_id) {
4588 return sender;
4589 }
4590 }
4591 }
4592 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004593}
4594
Steve Anton4171afb2017-11-20 10:20:22 -08004595rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4596PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4597 for (auto transceiver : transceivers_) {
4598 for (auto receiver : transceiver->internal()->receivers()) {
4599 if (receiver->id() == receiver_id) {
4600 return receiver;
4601 }
4602 }
4603 }
4604 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004605}
4606
Steve Anton4171afb2017-11-20 10:20:22 -08004607std::vector<PeerConnection::RtpSenderInfo>*
4608PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4609 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4610 media_type == cricket::MEDIA_TYPE_VIDEO);
4611 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4612 ? &remote_audio_sender_infos_
4613 : &remote_video_sender_infos_;
4614}
4615
4616std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004617 cricket::MediaType media_type) {
4618 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4619 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004620 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4621 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004622}
4623
Steve Anton4171afb2017-11-20 10:20:22 -08004624const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4625 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004626 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004627 const std::string sender_id) const {
4628 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004629 if (sender_info.stream_id == stream_id &&
4630 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004631 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004632 }
4633 }
4634 return nullptr;
4635}
4636
4637DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4638 for (const auto& channel : sctp_data_channels_) {
4639 if (channel->id() == sid) {
4640 return channel;
4641 }
4642 }
4643 return nullptr;
4644}
4645
deadbeef91dd5672016-05-18 16:55:30 -07004646bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004647 const RTCConfiguration& configuration) {
4648 cricket::ServerAddresses stun_servers;
4649 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004650 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4651 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004652 return false;
4653 }
4654
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004655 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004656 // To handle both internal and externally created port allocator, we will
4657 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004658 port_allocator_flags_ = port_allocator_->flags();
4659 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4660 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4661 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004662 // If the disable-IPv6 flag was specified, we'll not override it
4663 // by experiment.
4664 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004665 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004666 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4667 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004668 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004669 }
4670
zhihuangb09b3f92017-03-07 14:40:51 -08004671 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004672 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004673 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004674 }
4675
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004676 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004677 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004678 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004679 }
4680
honghaiz60347052016-05-31 18:29:12 -07004681 if (configuration.candidate_network_policy ==
4682 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004683 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004684 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004685 }
4686
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004687 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004688 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004689 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4690 }
4691
Qingsi Wanga2d60672018-04-11 16:57:45 -07004692 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004693 // No step delay is used while allocating ports.
4694 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4695 port_allocator_->set_candidate_filter(
4696 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004697 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004698
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004699 if (tls_cert_verifier_ != nullptr) {
4700 for (auto& turn_server : turn_servers) {
4701 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4702 }
4703 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004704 // Call this last since it may create pooled allocator sessions using the
4705 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004706 port_allocator_->SetConfiguration(
4707 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4708 configuration.prune_turn_ports, configuration.turn_customizer,
4709 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004710 return true;
4711}
4712
deadbeef91dd5672016-05-18 16:55:30 -07004713bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004714 const cricket::ServerAddresses& stun_servers,
4715 const std::vector<cricket::RelayServerConfig>& turn_servers,
4716 IceTransportsType type,
4717 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004718 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004719 webrtc::TurnCustomizer* turn_customizer,
4720 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004721 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004722 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004723 // According to JSEP, after setLocalDescription, changing the candidate pool
4724 // size is not allowed, and changing the set of ICE servers will not result
4725 // in new candidates being gathered.
4726 if (local_description()) {
4727 port_allocator_->FreezeCandidatePool();
4728 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004729 // Call this last since it may create pooled allocator sessions using the
4730 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004731 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004732 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004733 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004734}
4735
Steve Antonba818672017-11-06 10:21:57 -08004736cricket::ChannelManager* PeerConnection::channel_manager() const {
4737 return factory_->channel_manager();
4738}
4739
4740MetricsObserverInterface* PeerConnection::metrics_observer() const {
4741 return uma_observer_;
4742}
4743
Elad Alon99c3fe52017-10-13 16:29:40 +02004744bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004745 std::unique_ptr<RtcEventLogOutput> output,
4746 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004747 if (!event_log_) {
4748 return false;
4749 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004750 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004751}
4752
4753void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004754 if (event_log_) {
4755 event_log_->StopLogging();
4756 }
ivoc14d5dbe2016-07-04 07:06:55 -07004757}
nisseeaabdf62017-05-05 02:23:02 -07004758
Steve Anton75737c02017-11-06 10:37:17 -08004759cricket::BaseChannel* PeerConnection::GetChannel(
4760 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004761 for (auto transceiver : transceivers_) {
4762 cricket::BaseChannel* channel = transceiver->internal()->channel();
4763 if (channel && channel->content_name() == content_name) {
4764 return channel;
4765 }
Steve Anton75737c02017-11-06 10:37:17 -08004766 }
4767 if (rtp_data_channel() &&
4768 rtp_data_channel()->content_name() == content_name) {
4769 return rtp_data_channel();
4770 }
4771 return nullptr;
4772}
4773
4774bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4775 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004776 RTC_LOG(LS_INFO)
4777 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004778 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004779 return false;
4780 }
4781 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004782 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004783 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004784 return false;
4785 }
4786
Zhi Huange830e682018-03-30 10:48:35 -07004787 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4788 if (dtls_role) {
4789 *role = *dtls_role;
4790 return true;
4791 }
4792 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004793}
4794
4795bool PeerConnection::GetSslRole(const std::string& content_name,
4796 rtc::SSLRole* role) {
4797 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004798 RTC_LOG(LS_INFO)
4799 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004800 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004801 return false;
4802 }
4803
Zhi Huange830e682018-03-30 10:48:35 -07004804 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4805 if (dtls_role) {
4806 *role = *dtls_role;
4807 return true;
4808 }
4809 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004810}
4811
Steve Antonf8470812017-12-04 10:46:21 -08004812void PeerConnection::SetSessionError(SessionError error,
4813 const std::string& error_desc) {
4814 RTC_DCHECK_RUN_ON(signaling_thread());
4815 if (error != session_error_) {
4816 session_error_ = error;
4817 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004818 }
4819}
4820
Zhi Huange830e682018-03-30 10:48:35 -07004821RTCError PeerConnection::UpdateSessionState(
4822 SdpType type,
4823 cricket::ContentSource source,
4824 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004825 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004826
4827 // If there's already a pending error then no state transition should happen.
4828 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004829 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004830
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004831 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004832 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004833 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004834 }
4835
4836 // Update the signaling state according to the specified state machine (see
4837 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004838 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004839 ChangeSignalingState(source == cricket::CS_LOCAL
4840 ? PeerConnectionInterface::kHaveLocalOffer
4841 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004842 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004843 ChangeSignalingState(source == cricket::CS_LOCAL
4844 ? PeerConnectionInterface::kHaveLocalPrAnswer
4845 : PeerConnectionInterface::kHaveRemotePrAnswer);
4846 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004847 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004848 ChangeSignalingState(PeerConnectionInterface::kStable);
4849 }
4850
4851 // Update internal objects according to the session description's media
4852 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004853 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004854 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004855 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004856 }
4857
Steve Anton8a006912017-12-04 15:25:56 -08004858 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004859}
4860
Steve Anton8a006912017-12-04 15:25:56 -08004861RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004862 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004863 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004864 const SessionDescriptionInterface* sdesc =
4865 (source == cricket::CS_LOCAL ? local_description()
4866 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004867 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004868
4869 // Push down the new SDP media section for each audio/video transceiver.
4870 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004871 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004872 FindMediaSectionForTransceiver(transceiver, sdesc);
4873 cricket::BaseChannel* channel = transceiver->internal()->channel();
4874 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004875 continue;
4876 }
4877 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004878 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004879 if (!content_desc) {
4880 continue;
4881 }
4882 std::string error;
4883 bool success =
4884 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004885 ? channel->SetLocalContent(content_desc, type, &error)
4886 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004887 if (!success) {
4888 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4889 }
4890 }
4891
4892 // If using the RtpDataChannel, push down the new SDP section for it too.
4893 if (rtp_data_channel_) {
4894 const ContentInfo* data_content =
4895 cricket::GetFirstDataContent(sdesc->description());
4896 if (data_content && !data_content->rejected) {
4897 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004898 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004899 if (data_desc) {
4900 std::string error;
4901 bool success =
4902 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004903 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4904 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004905 &error);
4906 if (!success) {
4907 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4908 std::move(error));
4909 }
Steve Anton75737c02017-11-06 10:37:17 -08004910 }
4911 }
4912 }
Steve Antoned10bd92017-12-05 10:52:59 -08004913
Steve Anton75737c02017-11-06 10:37:17 -08004914 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4915 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4916 if (sctp_transport_ && local_description() && remote_description() &&
4917 cricket::GetFirstDataContent(local_description()->description()) &&
4918 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004919 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004920 RTC_FROM_HERE,
4921 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004922 if (!success) {
4923 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4924 "Failed to push down SCTP parameters.");
4925 }
Steve Anton75737c02017-11-06 10:37:17 -08004926 }
Steve Antoned10bd92017-12-05 10:52:59 -08004927
Steve Anton8a006912017-12-04 15:25:56 -08004928 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004929}
4930
4931bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4932 RTC_DCHECK(network_thread()->IsCurrent());
4933 RTC_DCHECK(local_description());
4934 RTC_DCHECK(remote_description());
4935 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4936 // When we support "max-message-size", that would also be pushed down here.
4937 return sctp_transport_->Start(
4938 GetSctpPort(local_description()->description()),
4939 GetSctpPort(remote_description()->description()));
4940}
4941
Steve Anton8a006912017-12-04 15:25:56 -08004942RTCError PeerConnection::PushdownTransportDescription(
4943 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004944 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004945 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004946
Zhi Huange830e682018-03-30 10:48:35 -07004947 if (source == cricket::CS_LOCAL) {
4948 const SessionDescriptionInterface* sdesc = local_description();
4949 RTC_DCHECK(sdesc);
4950 return transport_controller_->SetLocalDescription(type,
4951 sdesc->description());
4952 } else {
4953 const SessionDescriptionInterface* sdesc = remote_description();
4954 RTC_DCHECK(sdesc);
4955 return transport_controller_->SetRemoteDescription(type,
4956 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004957 }
Steve Anton75737c02017-11-06 10:37:17 -08004958}
4959
4960bool PeerConnection::GetTransportDescription(
4961 const SessionDescription* description,
4962 const std::string& content_name,
4963 cricket::TransportDescription* tdesc) {
4964 if (!description || !tdesc) {
4965 return false;
4966 }
4967 const TransportInfo* transport_info =
4968 description->GetTransportInfoByName(content_name);
4969 if (!transport_info) {
4970 return false;
4971 }
4972 *tdesc = transport_info->description;
4973 return true;
4974}
4975
Steve Anton75737c02017-11-06 10:37:17 -08004976cricket::IceConfig PeerConnection::ParseIceConfig(
4977 const PeerConnectionInterface::RTCConfiguration& config) const {
4978 cricket::ContinualGatheringPolicy gathering_policy;
4979 // TODO(honghaiz): Add the third continual gathering policy in
4980 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4981 switch (config.continual_gathering_policy) {
4982 case PeerConnectionInterface::GATHER_ONCE:
4983 gathering_policy = cricket::GATHER_ONCE;
4984 break;
4985 case PeerConnectionInterface::GATHER_CONTINUALLY:
4986 gathering_policy = cricket::GATHER_CONTINUALLY;
4987 break;
4988 default:
4989 RTC_NOTREACHED();
4990 gathering_policy = cricket::GATHER_ONCE;
4991 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004992
Steve Anton75737c02017-11-06 10:37:17 -08004993 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004994 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4995 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004996 ice_config.prioritize_most_likely_candidate_pairs =
4997 config.prioritize_most_likely_ice_candidate_pairs;
4998 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004999 RTCConfigurationToIceConfigOptionalInt(
5000 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005001 ice_config.continual_gathering_policy = gathering_policy;
5002 ice_config.presume_writable_when_fully_relayed =
5003 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005004 ice_config.ice_check_interval_strong_connectivity =
5005 config.ice_check_interval_strong_connectivity;
5006 ice_config.ice_check_interval_weak_connectivity =
5007 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005008 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005009 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005010 ice_config.regather_all_networks_interval_range =
5011 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005012 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005013 return ice_config;
5014}
5015
Steve Anton75737c02017-11-06 10:37:17 -08005016bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5017 std::string* track_id) {
5018 if (!local_description()) {
5019 return false;
5020 }
5021 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5022 track_id);
5023}
5024
5025bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5026 std::string* track_id) {
5027 if (!remote_description()) {
5028 return false;
5029 }
5030 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5031 track_id);
5032}
5033
5034bool PeerConnection::SendData(const cricket::SendDataParams& params,
5035 const rtc::CopyOnWriteBuffer& payload,
5036 cricket::SendDataResult* result) {
5037 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005038 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005039 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005040 return false;
5041 }
5042 return rtp_data_channel_
5043 ? rtp_data_channel_->SendData(params, payload, result)
5044 : network_thread()->Invoke<bool>(
5045 RTC_FROM_HERE,
5046 Bind(&cricket::SctpTransportInternal::SendData,
5047 sctp_transport_.get(), params, payload, result));
5048}
5049
5050bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5051 if (!rtp_data_channel_ && !sctp_transport_) {
5052 // Don't log an error here, because DataChannels are expected to call
5053 // ConnectDataChannel in this state. It's the only way to initially tell
5054 // whether or not the underlying transport is ready.
5055 return false;
5056 }
5057 if (rtp_data_channel_) {
5058 rtp_data_channel_->SignalReadyToSendData.connect(
5059 webrtc_data_channel, &DataChannel::OnChannelReady);
5060 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5061 &DataChannel::OnDataReceived);
5062 } else {
5063 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5064 &DataChannel::OnChannelReady);
5065 SignalSctpDataReceived.connect(webrtc_data_channel,
5066 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005067 SignalSctpClosingProcedureStartedRemotely.connect(
5068 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5069 SignalSctpClosingProcedureComplete.connect(
5070 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005071 }
5072 return true;
5073}
5074
5075void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5076 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005077 RTC_LOG(LS_ERROR)
5078 << "DisconnectDataChannel called when rtp_data_channel_ and "
5079 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005080 return;
5081 }
5082 if (rtp_data_channel_) {
5083 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5084 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5085 } else {
5086 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5087 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005088 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5089 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005090 }
5091}
5092
5093void PeerConnection::AddSctpDataStream(int sid) {
5094 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005095 RTC_LOG(LS_ERROR)
5096 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005097 return;
5098 }
5099 network_thread()->Invoke<void>(
5100 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5101 sctp_transport_.get(), sid));
5102}
5103
5104void PeerConnection::RemoveSctpDataStream(int sid) {
5105 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005106 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005107 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005108 return;
5109 }
5110 network_thread()->Invoke<void>(
5111 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5112 sctp_transport_.get(), sid));
5113}
5114
5115bool PeerConnection::ReadyToSendData() const {
5116 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5117 sctp_ready_to_send_data_;
5118}
5119
Zhi Huange830e682018-03-30 10:48:35 -07005120rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5121 if (sctp_mid_ && transport_controller_) {
5122 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5123 if (dtls_transport) {
5124 return dtls_transport->transport_name();
5125 }
5126 return rtc::Optional<std::string>();
5127 }
5128 return rtc::Optional<std::string>();
5129}
5130
Qingsi Wang72a43a12018-02-20 16:03:18 -08005131cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5132 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005133 network_thread()->Invoke<void>(
5134 RTC_FROM_HERE,
5135 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5136 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005137 return candidate_states_list;
5138}
5139
Steve Anton5dfde182018-02-06 10:34:40 -08005140std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5141 const {
5142 std::map<std::string, std::string> transport_names_by_mid;
5143 for (auto transceiver : transceivers_) {
5144 cricket::BaseChannel* channel = transceiver->internal()->channel();
5145 if (channel) {
5146 transport_names_by_mid[channel->content_name()] =
5147 channel->transport_name();
5148 }
Steve Anton75737c02017-11-06 10:37:17 -08005149 }
Steve Anton5dfde182018-02-06 10:34:40 -08005150 if (rtp_data_channel_) {
5151 transport_names_by_mid[rtp_data_channel_->content_name()] =
5152 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005153 }
5154 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005155 rtc::Optional<std::string> transport_name = sctp_transport_name();
5156 RTC_DCHECK(transport_name);
5157 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005158 }
Steve Anton5dfde182018-02-06 10:34:40 -08005159 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005160}
5161
Steve Anton5dfde182018-02-06 10:34:40 -08005162std::map<std::string, cricket::TransportStats>
5163PeerConnection::GetTransportStatsByNames(
5164 const std::set<std::string>& transport_names) {
5165 if (!network_thread()->IsCurrent()) {
5166 return network_thread()
5167 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5168 RTC_FROM_HERE,
5169 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005170 }
Steve Anton5dfde182018-02-06 10:34:40 -08005171 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5172 for (const std::string& transport_name : transport_names) {
5173 cricket::TransportStats transport_stats;
5174 bool success =
5175 transport_controller_->GetStats(transport_name, &transport_stats);
5176 if (success) {
5177 transport_stats_by_name[transport_name] = std::move(transport_stats);
5178 } else {
5179 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5180 << transport_name;
5181 }
5182 }
5183 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005184}
5185
5186bool PeerConnection::GetLocalCertificate(
5187 const std::string& transport_name,
5188 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005189 if (!certificate) {
5190 return false;
5191 }
5192 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5193 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005194}
5195
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005196std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005197 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005198 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005199}
5200
5201cricket::DataChannelType PeerConnection::data_channel_type() const {
5202 return data_channel_type_;
5203}
5204
5205bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5206 return pending_ice_restarts_.find(content_name) !=
5207 pending_ice_restarts_.end();
5208}
5209
Steve Anton75737c02017-11-06 10:37:17 -08005210bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5211 return transport_controller_->NeedsIceRestart(content_name);
5212}
5213
5214void PeerConnection::OnCertificateReady(
5215 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5216 transport_controller_->SetLocalCertificate(certificate);
5217}
5218
5219void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005220 SetSessionError(SessionError::kTransport,
5221 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005222}
5223
5224void PeerConnection::OnTransportControllerConnectionState(
5225 cricket::IceConnectionState state) {
5226 switch (state) {
5227 case cricket::kIceConnectionConnecting:
5228 // If the current state is Connected or Completed, then there were
5229 // writable channels but now there are not, so the next state must
5230 // be Disconnected.
5231 // kIceConnectionConnecting is currently used as the default,
5232 // un-connected state by the TransportController, so its only use is
5233 // detecting disconnections.
5234 if (ice_connection_state_ ==
5235 PeerConnectionInterface::kIceConnectionConnected ||
5236 ice_connection_state_ ==
5237 PeerConnectionInterface::kIceConnectionCompleted) {
5238 SetIceConnectionState(
5239 PeerConnectionInterface::kIceConnectionDisconnected);
5240 }
5241 break;
5242 case cricket::kIceConnectionFailed:
5243 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5244 break;
5245 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005246 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005247 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005248 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005249 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005250 break;
5251 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005252 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005253 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005254 if (ice_connection_state_ !=
5255 PeerConnectionInterface::kIceConnectionConnected) {
5256 // If jumping directly from "checking" to "connected",
5257 // signal "connected" first.
5258 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5259 }
5260 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005261 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005262 if (metrics_observer()) {
5263 ReportTransportStats();
5264 }
5265 break;
5266 default:
5267 RTC_NOTREACHED();
5268 }
5269}
5270
5271void PeerConnection::OnTransportControllerCandidatesGathered(
5272 const std::string& transport_name,
5273 const cricket::Candidates& candidates) {
5274 RTC_DCHECK(signaling_thread()->IsCurrent());
5275 int sdp_mline_index;
5276 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005277 RTC_LOG(LS_ERROR)
5278 << "OnTransportControllerCandidatesGathered: content name "
5279 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005280 return;
5281 }
5282
5283 for (cricket::Candidates::const_iterator citer = candidates.begin();
5284 citer != candidates.end(); ++citer) {
5285 // Use transport_name as the candidate media id.
5286 std::unique_ptr<JsepIceCandidate> candidate(
5287 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5288 if (local_description()) {
5289 mutable_local_description()->AddCandidate(candidate.get());
5290 }
5291 OnIceCandidate(std::move(candidate));
5292 }
5293}
5294
5295void PeerConnection::OnTransportControllerCandidatesRemoved(
5296 const std::vector<cricket::Candidate>& candidates) {
5297 RTC_DCHECK(signaling_thread()->IsCurrent());
5298 // Sanity check.
5299 for (const cricket::Candidate& candidate : candidates) {
5300 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005301 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005302 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005303 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005304 return;
5305 }
5306 }
5307
5308 if (local_description()) {
5309 mutable_local_description()->RemoveCandidates(candidates);
5310 }
5311 OnIceCandidatesRemoved(candidates);
5312}
5313
5314void PeerConnection::OnTransportControllerDtlsHandshakeError(
5315 rtc::SSLHandshakeError error) {
5316 if (metrics_observer()) {
5317 metrics_observer()->IncrementEnumCounter(
5318 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5319 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5320 }
5321}
5322
Steve Antoned10bd92017-12-05 10:52:59 -08005323void PeerConnection::EnableSending() {
5324 for (auto transceiver : transceivers_) {
5325 cricket::BaseChannel* channel = transceiver->internal()->channel();
5326 if (channel && !channel->enabled()) {
5327 channel->Enable(true);
5328 }
Steve Anton75737c02017-11-06 10:37:17 -08005329 }
5330
Steve Anton4171afb2017-11-20 10:20:22 -08005331 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005332 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005333 }
Steve Anton75737c02017-11-06 10:37:17 -08005334}
5335
5336// Returns the media index for a local ice candidate given the content name.
5337bool PeerConnection::GetLocalCandidateMediaIndex(
5338 const std::string& content_name,
5339 int* sdp_mline_index) {
5340 if (!local_description() || !sdp_mline_index) {
5341 return false;
5342 }
5343
5344 bool content_found = false;
5345 const ContentInfos& contents = local_description()->description()->contents();
5346 for (size_t index = 0; index < contents.size(); ++index) {
5347 if (contents[index].name == content_name) {
5348 *sdp_mline_index = static_cast<int>(index);
5349 content_found = true;
5350 break;
5351 }
5352 }
5353 return content_found;
5354}
5355
5356bool PeerConnection::UseCandidatesInSessionDescription(
5357 const SessionDescriptionInterface* remote_desc) {
5358 if (!remote_desc) {
5359 return true;
5360 }
5361 bool ret = true;
5362
5363 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5364 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5365 for (size_t n = 0; n < candidates->count(); ++n) {
5366 const IceCandidateInterface* candidate = candidates->at(n);
5367 bool valid = false;
5368 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5369 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005370 RTC_LOG(LS_INFO)
5371 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005372 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005373 }
5374 continue;
5375 }
5376 ret = UseCandidate(candidate);
5377 if (!ret) {
5378 break;
5379 }
5380 }
5381 }
5382 return ret;
5383}
5384
5385bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5386 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5387 size_t remote_content_size =
5388 remote_description()->description()->contents().size();
5389 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005390 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005391 return false;
5392 }
5393
5394 cricket::ContentInfo content =
5395 remote_description()->description()->contents()[mediacontent_index];
5396 std::vector<cricket::Candidate> candidates;
5397 candidates.push_back(candidate->candidate());
5398 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005399 RTCError error =
5400 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005401 if (error.ok()) {
5402 // Candidates successfully submitted for checking.
5403 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5404 ice_connection_state_ ==
5405 PeerConnectionInterface::kIceConnectionDisconnected) {
5406 // If state is New, then the session has just gotten its first remote ICE
5407 // candidates, so go to Checking.
5408 // If state is Disconnected, the session is re-using old candidates or
5409 // receiving additional ones, so go to Checking.
5410 // If state is Connected, stay Connected.
5411 // TODO(bemasc): If state is Connected, and the new candidates are for a
5412 // newly added transport, then the state actually _should_ move to
5413 // checking. Add a way to distinguish that case.
5414 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5415 }
5416 // TODO(bemasc): If state is Completed, go back to Connected.
5417 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005418 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005419 }
5420 return true;
5421}
5422
5423void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005424 // Destroy video channel first since it may have a pointer to the
5425 // voice channel.
5426 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005427 if (!video_info || video_info->rejected) {
5428 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005429 }
5430
Steve Anton6fec8802017-12-04 10:37:29 -08005431 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5432 if (!audio_info || audio_info->rejected) {
5433 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005434 }
5435
5436 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5437 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005438 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005439 }
5440}
5441
Steve Antondcc3c022017-12-22 16:02:54 -08005442RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5443 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005444 const cricket::ContentGroup* bundle_group = nullptr;
5445 if (configuration_.bundle_policy ==
5446 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005447 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005448 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005449 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5450 "max-bundle configured but session description "
5451 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005452 }
5453 }
Steve Antondcc3c022017-12-22 16:02:54 -08005454 return std::move(bundle_group);
5455}
5456
5457RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005458 // Creating the media channels. Transports should already have been created
5459 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005460 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005461 if (voice && !voice->rejected &&
5462 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005463 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005464 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005465 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5466 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005467 }
5468 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5469 }
5470
Steve Antondcc3c022017-12-22 16:02:54 -08005471 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005472 if (video && !video->rejected &&
5473 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005474 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005475 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005476 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5477 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005478 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005479 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005480 }
5481
Steve Antondcc3c022017-12-22 16:02:54 -08005482 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005483 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5484 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005485 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005486 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5487 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005488 }
5489 }
5490
Steve Anton8a006912017-12-04 15:25:56 -08005491 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005492}
5493
Steve Anton4171afb2017-11-20 10:20:22 -08005494// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005495cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005496 const std::string& mid) {
5497 RtpTransportInternal* rtp_transport =
5498 transport_controller_->GetRtpTransport(mid);
5499 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005500 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005501 call_.get(), configuration_.media_config, rtp_transport,
5502 signaling_thread(), mid, SrtpRequired(),
5503 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005504 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005505 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005506 }
Steve Anton75737c02017-11-06 10:37:17 -08005507 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5508 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005509 voice_channel->SignalSentPacket.connect(this,
5510 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005511 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005512 if (uma_observer_) {
5513 voice_channel->SetMetricsObserver(uma_observer_);
5514 }
Steve Anton4171afb2017-11-20 10:20:22 -08005515
Steve Antoneda6ccd2017-12-04 10:21:55 -08005516 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005517}
5518
Steve Anton4171afb2017-11-20 10:20:22 -08005519// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005520cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005521 const std::string& mid) {
5522 RtpTransportInternal* rtp_transport =
5523 transport_controller_->GetRtpTransport(mid);
5524 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005525 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005526 call_.get(), configuration_.media_config, rtp_transport,
5527 signaling_thread(), mid, SrtpRequired(),
5528 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005529 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005530 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005531 }
Steve Anton75737c02017-11-06 10:37:17 -08005532 video_channel->SignalDtlsSrtpSetupFailure.connect(
5533 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005534 video_channel->SignalSentPacket.connect(this,
5535 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005536 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005537 if (uma_observer_) {
5538 video_channel->SetMetricsObserver(uma_observer_);
5539 }
Steve Anton4171afb2017-11-20 10:20:22 -08005540
Steve Antoneda6ccd2017-12-04 10:21:55 -08005541 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005542}
5543
Zhi Huange830e682018-03-30 10:48:35 -07005544bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005545 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5546 if (sctp) {
5547 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005548 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005549 << "Trying to create SCTP transport, but didn't compile with "
5550 "SCTP support (HAVE_SCTP)";
5551 return false;
5552 }
5553 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005554 RTC_FROM_HERE,
5555 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005556 return false;
5557 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005558 for (const auto& channel : sctp_data_channels_) {
5559 channel->OnTransportChannelCreated();
5560 }
Steve Anton75737c02017-11-06 10:37:17 -08005561 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005562 RtpTransportInternal* rtp_transport =
5563 transport_controller_->GetRtpTransport(mid);
5564 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005565 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005566 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5567 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005568 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005569 return false;
5570 }
Steve Anton75737c02017-11-06 10:37:17 -08005571 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5572 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5573 rtp_data_channel_->SignalSentPacket.connect(
5574 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005575 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005576 if (uma_observer_) {
5577 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5578 }
Steve Anton75737c02017-11-06 10:37:17 -08005579 }
5580
Steve Anton75737c02017-11-06 10:37:17 -08005581 return true;
5582}
5583
5584Call::Stats PeerConnection::GetCallStats() {
5585 if (!worker_thread()->IsCurrent()) {
5586 return worker_thread()->Invoke<Call::Stats>(
5587 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5588 }
5589 if (call_) {
5590 return call_->GetStats();
5591 } else {
5592 return Call::Stats();
5593 }
5594}
5595
Zhi Huange830e682018-03-30 10:48:35 -07005596bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005597 RTC_DCHECK(network_thread()->IsCurrent());
5598 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005599 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005600 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005601 RTC_DCHECK(dtls_transport);
5602 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005603 RTC_DCHECK(sctp_transport_);
5604 sctp_invoker_.reset(new rtc::AsyncInvoker());
5605 sctp_transport_->SignalReadyToSendData.connect(
5606 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5607 sctp_transport_->SignalDataReceived.connect(
5608 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005609 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5610 // another thread. Would be nice if there was a helper class similar to
5611 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5612 // code.
5613 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5614 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5615 sctp_transport_->SignalClosingProcedureComplete.connect(
5616 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005617 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005618 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005619 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005620}
5621
5622void PeerConnection::DestroySctpTransport_n() {
5623 RTC_DCHECK(network_thread()->IsCurrent());
5624 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005625 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005626 sctp_invoker_.reset(nullptr);
5627 sctp_ready_to_send_data_ = false;
5628}
5629
5630void PeerConnection::OnSctpTransportReadyToSendData_n() {
5631 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5632 RTC_DCHECK(network_thread()->IsCurrent());
5633 // Note: Cannot use rtc::Bind here because it will grab a reference to
5634 // PeerConnection and potentially cause PeerConnection to live longer than
5635 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5636 // be destroyed before PeerConnection is destroyed, and at that point all
5637 // pending tasks will be cleared.
5638 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5639 OnSctpTransportReadyToSendData_s(true);
5640 });
5641}
5642
5643void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5644 RTC_DCHECK(signaling_thread()->IsCurrent());
5645 sctp_ready_to_send_data_ = ready;
5646 SignalSctpReadyToSendData(ready);
5647}
5648
5649void PeerConnection::OnSctpTransportDataReceived_n(
5650 const cricket::ReceiveDataParams& params,
5651 const rtc::CopyOnWriteBuffer& payload) {
5652 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5653 RTC_DCHECK(network_thread()->IsCurrent());
5654 // Note: Cannot use rtc::Bind here because it will grab a reference to
5655 // PeerConnection and potentially cause PeerConnection to live longer than
5656 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5657 // be destroyed before PeerConnection is destroyed, and at that point all
5658 // pending tasks will be cleared.
5659 sctp_invoker_->AsyncInvoke<void>(
5660 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5661 OnSctpTransportDataReceived_s(params, payload);
5662 });
5663}
5664
5665void PeerConnection::OnSctpTransportDataReceived_s(
5666 const cricket::ReceiveDataParams& params,
5667 const rtc::CopyOnWriteBuffer& payload) {
5668 RTC_DCHECK(signaling_thread()->IsCurrent());
5669 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5670 // Received OPEN message; parse and signal that a new data channel should
5671 // be created.
5672 std::string label;
5673 InternalDataChannelInit config;
5674 config.id = params.ssrc;
5675 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005676 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5677 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005678 return;
5679 }
5680 config.open_handshake_role = InternalDataChannelInit::kAcker;
5681 OnDataChannelOpenMessage(label, config);
5682 } else {
5683 // Otherwise just forward the signal.
5684 SignalSctpDataReceived(params, payload);
5685 }
5686}
5687
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005688void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005689 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5690 RTC_DCHECK(network_thread()->IsCurrent());
5691 sctp_invoker_->AsyncInvoke<void>(
5692 RTC_FROM_HERE, signaling_thread(),
5693 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005694 &SignalSctpClosingProcedureStartedRemotely, sid));
5695}
5696
5697void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5698 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5699 RTC_DCHECK(network_thread()->IsCurrent());
5700 sctp_invoker_->AsyncInvoke<void>(
5701 RTC_FROM_HERE, signaling_thread(),
5702 rtc::Bind(&sigslot::signal1<int>::operator(),
5703 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005704}
5705
5706// Returns false if bundle is enabled and rtcp_mux is disabled.
5707bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5708 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5709 if (!bundle_enabled)
5710 return true;
5711
5712 const cricket::ContentGroup* bundle_group =
5713 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5714 RTC_DCHECK(bundle_group != NULL);
5715
5716 const cricket::ContentInfos& contents = desc->contents();
5717 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5718 citer != contents.end(); ++citer) {
5719 const cricket::ContentInfo* content = (&*citer);
5720 RTC_DCHECK(content != NULL);
5721 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005722 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005723 if (!HasRtcpMuxEnabled(content))
5724 return false;
5725 }
5726 }
5727 // RTCP-MUX is enabled in all the contents.
5728 return true;
5729}
5730
5731bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005732 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005733}
5734
Steve Anton8a006912017-12-04 15:25:56 -08005735RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005736 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005737 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005738 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005739 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005740 }
5741
5742 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005743 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005744 }
5745
Steve Anton3828c062017-12-06 10:34:51 -08005746 SdpType type = sdesc->GetType();
5747 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5748 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005749 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005750 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005751 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005752 }
5753
5754 // Verify crypto settings.
5755 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005756 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5757 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005758 RTCError crypto_error =
5759 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005760 if (!crypto_error.ok()) {
5761 return crypto_error;
5762 }
Steve Anton75737c02017-11-06 10:37:17 -08005763 }
5764
5765 // Verify ice-ufrag and ice-pwd.
5766 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005767 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5768 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
5770
5771 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005772 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5773 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005774 }
5775
5776 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5777 // m-lines that do not rtcp-mux enabled.
5778
5779 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005780 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005781 // With an answer we want to compare the new answer session description with
5782 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005783 const cricket::SessionDescription* offer_desc =
5784 (source == cricket::CS_LOCAL) ? remote_description()->description()
5785 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005786 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5787 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5788 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005789 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5790 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005791 }
5792 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005793 // The re-offers should respect the order of m= sections in current
5794 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005795 // With a re-offer, either the current local or current remote descriptions
5796 // could be the most up to date, so we would like to check against both of
5797 // them if they exist. It could be the case that one of them has a 0 port
5798 // for a media section, but the other does not. This is important to check
5799 // against in the case that we are recycling an m= section.
5800 const cricket::SessionDescription* current_desc = nullptr;
5801 const cricket::SessionDescription* secondary_current_desc = nullptr;
5802 if (local_description()) {
5803 current_desc = local_description()->description();
5804 if (remote_description()) {
5805 secondary_current_desc = remote_description()->description();
5806 }
5807 } else if (remote_description()) {
5808 current_desc = remote_description()->description();
5809 }
Steve Anton75737c02017-11-06 10:37:17 -08005810 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005811 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5812 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005813 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5814 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005815 }
5816 }
5817
Steve Antonba42e992018-04-09 14:10:01 -07005818 if (IsUnifiedPlan()) {
5819 // Ensure that each audio and video media section has at most one
5820 // "StreamParams". This will return an error if receiving a session
5821 // description from a "Plan B" endpoint which adds multiple tracks of the
5822 // same type. With Unified Plan, there can only be at most one track per
5823 // media section.
5824 for (const ContentInfo& content : sdesc->description()->contents()) {
5825 const MediaContentDescription& desc = *content.description;
5826 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5827 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5828 desc.streams().size() > 1u) {
5829 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5830 "Media section has more than one track specified "
5831 "with a=ssrc lines which is not supported with "
5832 "Unified Plan.");
5833 }
5834 }
5835 }
5836
Steve Anton8a006912017-12-04 15:25:56 -08005837 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005838}
5839
Steve Anton3828c062017-12-06 10:34:51 -08005840bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005841 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005842 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005843 return (state == PeerConnectionInterface::kStable) ||
5844 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005845 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005846 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005847 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5848 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5849 }
5850}
5851
Steve Anton3828c062017-12-06 10:34:51 -08005852bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005853 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005854 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005855 return (state == PeerConnectionInterface::kStable) ||
5856 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005857 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005858 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005859 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5860 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5861 }
5862}
5863
Steve Antonf8470812017-12-04 10:46:21 -08005864const char* PeerConnection::SessionErrorToString(SessionError error) const {
5865 switch (error) {
5866 case SessionError::kNone:
5867 return "ERROR_NONE";
5868 case SessionError::kContent:
5869 return "ERROR_CONTENT";
5870 case SessionError::kTransport:
5871 return "ERROR_TRANSPORT";
5872 }
5873 RTC_NOTREACHED();
5874 return "";
5875}
5876
Steve Anton75737c02017-11-06 10:37:17 -08005877std::string PeerConnection::GetSessionErrorMsg() {
5878 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005879 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5880 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005881 return desc.str();
5882}
5883
Steve Anton8e20f172018-03-06 10:55:04 -08005884void PeerConnection::ReportSdpFormatReceived(
5885 const SessionDescriptionInterface& remote_offer) {
5886 if (!uma_observer_) {
5887 return;
5888 }
5889 int num_audio_mlines = 0;
5890 int num_video_mlines = 0;
5891 int num_audio_tracks = 0;
5892 int num_video_tracks = 0;
5893 for (const ContentInfo& content : remote_offer.description()->contents()) {
5894 cricket::MediaType media_type = content.media_description()->type();
5895 int num_tracks = std::max(
5896 1, static_cast<int>(content.media_description()->streams().size()));
5897 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5898 num_audio_mlines += 1;
5899 num_audio_tracks += num_tracks;
5900 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5901 num_video_mlines += 1;
5902 num_video_tracks += num_tracks;
5903 }
5904 }
5905 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5906 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5907 format = kSdpFormatReceivedComplexUnifiedPlan;
5908 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5909 format = kSdpFormatReceivedComplexPlanB;
5910 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5911 format = kSdpFormatReceivedSimple;
5912 }
5913 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5914 kSdpFormatReceivedMax);
5915}
5916
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005917void PeerConnection::NoteUsageEvent(UsageEvent event) {
5918 RTC_DCHECK_RUN_ON(signaling_thread());
5919 usage_event_accumulator_ |= static_cast<int>(event);
5920}
5921
5922void PeerConnection::ReportUsagePattern() const {
5923 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5924 if (uma_observer_) {
5925 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5926 usage_event_accumulator_);
5927 }
5928}
5929
Steve Anton0ffaaa22018-02-23 10:31:30 -08005930void PeerConnection::ReportNegotiatedSdpSemantics(
5931 const SessionDescriptionInterface& answer) {
5932 if (!uma_observer_) {
5933 return;
5934 }
5935 switch (answer.description()->msid_signaling()) {
5936 case 0:
5937 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5938 kSdpSemanticNegotiatedNone,
5939 kSdpSemanticNegotiatedMax);
5940 break;
5941 case cricket::kMsidSignalingMediaSection:
5942 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5943 kSdpSemanticNegotiatedUnifiedPlan,
5944 kSdpSemanticNegotiatedMax);
5945 break;
5946 case cricket::kMsidSignalingSsrcAttribute:
5947 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5948 kSdpSemanticNegotiatedPlanB,
5949 kSdpSemanticNegotiatedMax);
5950 break;
5951 case cricket::kMsidSignalingMediaSection |
5952 cricket::kMsidSignalingSsrcAttribute:
5953 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5954 kSdpSemanticNegotiatedMixed,
5955 kSdpSemanticNegotiatedMax);
5956 break;
5957 default:
5958 RTC_NOTREACHED();
5959 }
5960}
5961
Steve Anton75737c02017-11-06 10:37:17 -08005962// We need to check the local/remote description for the Transport instead of
5963// the session, because a new Transport added during renegotiation may have
5964// them unset while the session has them set from the previous negotiation.
5965// Not doing so may trigger the auto generation of transport description and
5966// mess up DTLS identity information, ICE credential, etc.
5967bool PeerConnection::ReadyToUseRemoteCandidate(
5968 const IceCandidateInterface* candidate,
5969 const SessionDescriptionInterface* remote_desc,
5970 bool* valid) {
5971 *valid = true;
5972
5973 const SessionDescriptionInterface* current_remote_desc =
5974 remote_desc ? remote_desc : remote_description();
5975
5976 if (!current_remote_desc) {
5977 return false;
5978 }
5979
5980 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5981 size_t remote_content_size =
5982 current_remote_desc->description()->contents().size();
5983 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005984 RTC_LOG(LS_ERROR)
5985 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5986 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005987
5988 *valid = false;
5989 return false;
5990 }
5991
5992 cricket::ContentInfo content =
5993 current_remote_desc->description()->contents()[mediacontent_index];
5994
5995 const std::string transport_name = GetTransportName(content.name);
5996 if (transport_name.empty()) {
5997 return false;
5998 }
Zhi Huange830e682018-03-30 10:48:35 -07005999 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006000}
6001
6002bool PeerConnection::SrtpRequired() const {
6003 return dtls_enabled_ ||
6004 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6005}
6006
6007void PeerConnection::OnTransportControllerGatheringState(
6008 cricket::IceGatheringState state) {
6009 RTC_DCHECK(signaling_thread()->IsCurrent());
6010 if (state == cricket::kIceGatheringGathering) {
6011 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6012 } else if (state == cricket::kIceGatheringComplete) {
6013 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6014 }
6015}
6016
6017void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006018 std::map<std::string, std::set<cricket::MediaType>>
6019 media_types_by_transport_name;
6020 for (auto transceiver : transceivers_) {
6021 if (transceiver->internal()->channel()) {
6022 const std::string& transport_name =
6023 transceiver->internal()->channel()->transport_name();
6024 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006025 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006026 }
Steve Anton75737c02017-11-06 10:37:17 -08006027 }
6028 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006029 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6030 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006031 }
Zhi Huange830e682018-03-30 10:48:35 -07006032
6033 rtc::Optional<std::string> transport_name = sctp_transport_name();
6034 if (transport_name) {
6035 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006036 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006037 }
Zhi Huange830e682018-03-30 10:48:35 -07006038
Steve Antonc7b964c2018-02-01 14:39:45 -08006039 for (const auto& entry : media_types_by_transport_name) {
6040 const std::string& transport_name = entry.first;
6041 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006042 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006043 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006044 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006045 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006046 }
6047 }
6048}
6049// Walk through the ConnectionInfos to gather best connection usage
6050// for IPv4 and IPv6.
6051void PeerConnection::ReportBestConnectionState(
6052 const cricket::TransportStats& stats) {
6053 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006054 for (const cricket::TransportChannelStats& channel_stats :
6055 stats.channel_stats) {
6056 for (const cricket::ConnectionInfo& connection_info :
6057 channel_stats.connection_infos) {
6058 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006059 continue;
6060 }
6061
6062 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006063 const cricket::Candidate& local = connection_info.local_candidate;
6064 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006065
6066 // Increment the counter for IceCandidatePairType.
6067 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6068 (local.type() == RELAY_PORT_TYPE &&
6069 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6070 type = kEnumCounterIceCandidatePairTypeTcp;
6071 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6072 type = kEnumCounterIceCandidatePairTypeUdp;
6073 } else {
6074 RTC_CHECK(0);
6075 }
6076 metrics_observer()->IncrementEnumCounter(
6077 type, GetIceCandidatePairCounter(local, remote),
6078 kIceCandidatePairMax);
6079
6080 // Increment the counter for IP type.
6081 if (local.address().family() == AF_INET) {
6082 metrics_observer()->IncrementEnumCounter(
6083 kEnumCounterAddressFamily, kBestConnections_IPv4,
6084 kPeerConnectionAddressFamilyCounter_Max);
6085
6086 } else if (local.address().family() == AF_INET6) {
6087 metrics_observer()->IncrementEnumCounter(
6088 kEnumCounterAddressFamily, kBestConnections_IPv6,
6089 kPeerConnectionAddressFamilyCounter_Max);
6090 } else {
6091 RTC_CHECK(0);
6092 }
6093
6094 return;
6095 }
6096 }
6097}
6098
6099void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006100 const cricket::TransportStats& stats,
6101 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006102 RTC_DCHECK(metrics_observer());
6103 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6104 return;
6105 }
6106
6107 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6108 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6109 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6110 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6111 return;
6112 }
6113
Steve Antonc7b964c2018-02-01 14:39:45 -08006114 for (cricket::MediaType media_type : media_types) {
6115 PeerConnectionEnumCounterType srtp_counter_type;
6116 PeerConnectionEnumCounterType ssl_counter_type;
6117 switch (media_type) {
6118 case cricket::MEDIA_TYPE_AUDIO:
6119 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6120 ssl_counter_type = kEnumCounterAudioSslCipher;
6121 break;
6122 case cricket::MEDIA_TYPE_VIDEO:
6123 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6124 ssl_counter_type = kEnumCounterVideoSslCipher;
6125 break;
6126 case cricket::MEDIA_TYPE_DATA:
6127 srtp_counter_type = kEnumCounterDataSrtpCipher;
6128 ssl_counter_type = kEnumCounterDataSslCipher;
6129 break;
6130 default:
6131 RTC_NOTREACHED();
6132 continue;
6133 }
6134 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6135 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6136 srtp_crypto_suite);
6137 }
6138 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6139 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6140 ssl_cipher_suite);
6141 }
Steve Anton75737c02017-11-06 10:37:17 -08006142 }
6143}
6144
6145void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6146 RTC_DCHECK(worker_thread()->IsCurrent());
6147 RTC_DCHECK(call_);
6148 call_->OnSentPacket(sent_packet);
6149}
6150
6151const std::string PeerConnection::GetTransportName(
6152 const std::string& content_name) {
6153 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006154 if (channel) {
6155 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006156 }
Steve Anton6fec8802017-12-04 10:37:29 -08006157 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006158 RTC_DCHECK(sctp_mid_);
6159 if (content_name == *sctp_mid_) {
6160 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006161 }
6162 }
6163 // Return an empty string if failed to retrieve the transport name.
6164 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006165}
6166
Steve Anton6fec8802017-12-04 10:37:29 -08006167void PeerConnection::DestroyTransceiverChannel(
6168 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6169 transceiver) {
6170 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006171
Steve Anton6fec8802017-12-04 10:37:29 -08006172 cricket::BaseChannel* channel = transceiver->internal()->channel();
6173 if (channel) {
6174 transceiver->internal()->SetChannel(nullptr);
6175 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006176 }
6177}
6178
6179void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006180 if (rtp_data_channel_) {
6181 OnDataChannelDestroyed();
6182 DestroyBaseChannel(rtp_data_channel_);
6183 rtp_data_channel_ = nullptr;
6184 }
6185
6186 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6187 // grab a reference to this PeerConnection. If this is called from the
6188 // PeerConnection destructor, the RefCountedObject vtable will have already
6189 // been destroyed (since it is a subclass of PeerConnection) and using
6190 // rtc::Bind will cause "Pure virtual function called" error to appear.
6191
6192 if (sctp_transport_) {
6193 OnDataChannelDestroyed();
6194 network_thread()->Invoke<void>(RTC_FROM_HERE,
6195 [this] { DestroySctpTransport_n(); });
6196 }
6197}
6198
6199void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6200 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006201 switch (channel->media_type()) {
6202 case cricket::MEDIA_TYPE_AUDIO:
6203 channel_manager()->DestroyVoiceChannel(
6204 static_cast<cricket::VoiceChannel*>(channel));
6205 break;
6206 case cricket::MEDIA_TYPE_VIDEO:
6207 channel_manager()->DestroyVideoChannel(
6208 static_cast<cricket::VideoChannel*>(channel));
6209 break;
6210 case cricket::MEDIA_TYPE_DATA:
6211 channel_manager()->DestroyRtpDataChannel(
6212 static_cast<cricket::RtpDataChannel*>(channel));
6213 break;
6214 default:
6215 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6216 break;
6217 }
Zhi Huange830e682018-03-30 10:48:35 -07006218}
Steve Anton6fec8802017-12-04 10:37:29 -08006219
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006220bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006221 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006222 RtpTransportInternal* rtp_transport,
6223 cricket::DtlsTransportInternal* dtls_transport) {
6224 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006225 auto base_channel = GetChannel(mid);
6226 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006227 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006228 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006229 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006230 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006231 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006232 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006233}
6234
Harald Alvestrand89061872018-01-02 14:08:34 +01006235void PeerConnection::ClearStatsCache() {
6236 if (stats_collector_) {
6237 stats_collector_->ClearCachedStatsReport();
6238 }
6239}
6240
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006241} // namespace webrtc