blob: 1f792c3e71e58c875bd120c7dd66c4dbe2cd621a [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;
Zhi Huangbae10312018-06-08 14:55:27 -0700696 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800697 };
698 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
699 "Did you add something to RTCConfiguration and forget to "
700 "update operator==?");
701 return type == o.type && servers == o.servers &&
702 bundle_policy == o.bundle_policy &&
703 rtcp_mux_policy == o.rtcp_mux_policy &&
704 tcp_candidate_policy == o.tcp_candidate_policy &&
705 candidate_network_policy == o.candidate_network_policy &&
706 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
707 audio_jitter_buffer_fast_accelerate ==
708 o.audio_jitter_buffer_fast_accelerate &&
709 ice_connection_receiving_timeout ==
710 o.ice_connection_receiving_timeout &&
711 ice_backup_candidate_pair_ping_interval ==
712 o.ice_backup_candidate_pair_ping_interval &&
713 continual_gathering_policy == o.continual_gathering_policy &&
714 certificates == o.certificates &&
715 prioritize_most_likely_ice_candidate_pairs ==
716 o.prioritize_most_likely_ice_candidate_pairs &&
717 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800718 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700719 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100720 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800721 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800722 screencast_min_bitrate == o.screencast_min_bitrate &&
723 combined_audio_video_bwe == o.combined_audio_video_bwe &&
724 enable_dtls_srtp == o.enable_dtls_srtp &&
725 ice_candidate_pool_size == o.ice_candidate_pool_size &&
726 prune_turn_ports == o.prune_turn_ports &&
727 presume_writable_when_fully_relayed ==
728 o.presume_writable_when_fully_relayed &&
729 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800730 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800731 ice_check_interval_strong_connectivity ==
732 o.ice_check_interval_strong_connectivity &&
733 ice_check_interval_weak_connectivity ==
734 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700735 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700736 ice_unwritable_timeout == o.ice_unwritable_timeout &&
737 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800738 stun_candidate_keepalive_interval ==
739 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200740 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800741 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800742 sdp_semantics == o.sdp_semantics &&
Zhi Huangbae10312018-06-08 14:55:27 -0700743 network_preference == o.network_preference &&
744 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800745}
746
747bool PeerConnectionInterface::RTCConfiguration::operator!=(
748 const PeerConnectionInterface::RTCConfiguration& o) const {
749 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800750}
751
zhihuang8f65cdf2016-05-06 18:40:30 -0700752// Generate a RTCP CNAME when a PeerConnection is created.
753std::string GenerateRtcpCname() {
754 std::string cname;
755 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800757 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700758 }
759 return cname;
760}
761
zhihuang1c378ed2017-08-17 14:10:50 -0700762bool ValidateOfferAnswerOptions(
763 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
764 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
765 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700766}
767
zhihuang1c378ed2017-08-17 14:10:50 -0700768// From |rtc_options|, fill parts of |session_options| shared by all generated
769// m= sections (in other words, nothing that involves a map/array).
770void ExtractSharedMediaSessionOptions(
771 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
772 cricket::MediaSessionOptions* session_options) {
773 session_options->vad_enabled = rtc_options.voice_activity_detection;
774 session_options->bundle_enabled = rtc_options.use_rtp_mux;
775}
zhihuanga77e6bb2017-08-14 18:17:48 -0700776
zhihuang1c378ed2017-08-17 14:10:50 -0700777bool ConvertConstraintsToOfferAnswerOptions(
778 const MediaConstraintsInterface* constraints,
779 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700780 if (!constraints) {
781 return true;
782 }
zhihuang1c378ed2017-08-17 14:10:50 -0700783
784 bool value = false;
785 size_t mandatory_constraints_satisfied = 0;
786
787 if (FindConstraint(constraints,
788 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
789 &mandatory_constraints_satisfied)) {
790 offer_answer_options->offer_to_receive_audio =
791 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
792 kOfferToReceiveMediaTrue
793 : 0;
794 }
795
796 if (FindConstraint(constraints,
797 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
798 &mandatory_constraints_satisfied)) {
799 offer_answer_options->offer_to_receive_video =
800 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
801 kOfferToReceiveMediaTrue
802 : 0;
803 }
804 if (FindConstraint(constraints,
805 MediaConstraintsInterface::kVoiceActivityDetection, &value,
806 &mandatory_constraints_satisfied)) {
807 offer_answer_options->voice_activity_detection = value;
808 }
809 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
810 &mandatory_constraints_satisfied)) {
811 offer_answer_options->use_rtp_mux = value;
812 }
813 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
814 &value, &mandatory_constraints_satisfied)) {
815 offer_answer_options->ice_restart = value;
816 }
817
deadbeefab9b2d12015-10-14 11:33:11 -0700818 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
819}
820
zhihuang38ede132017-06-15 12:52:32 -0700821PeerConnection::PeerConnection(PeerConnectionFactory* factory,
822 std::unique_ptr<RtcEventLog> event_log,
823 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700825 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700826 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700827 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700828 remote_streams_(StreamCollection::Create()),
829 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000830
831PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100832 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800833 RTC_DCHECK_RUN_ON(signaling_thread());
834
Steve Anton8af21862017-12-15 11:20:13 -0800835 // Need to stop transceivers before destroying the stats collector because
836 // AudioRtpSender has a reference to the StatsCollector it will update when
837 // stopping.
838 for (auto transceiver : transceivers_) {
839 transceiver->Stop();
840 }
Steve Anton4171afb2017-11-20 10:20:22 -0800841
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700842 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800843 if (stats_collector_) {
844 stats_collector_->WaitForPendingRequest();
845 stats_collector_ = nullptr;
846 }
Steve Anton75737c02017-11-06 10:37:17 -0800847
Steve Anton8af21862017-12-15 11:20:13 -0800848 // Don't destroy BaseChannels until after stats has been cleaned up so that
849 // the last stats request can still read from the channels.
850 DestroyAllChannels();
851
Mirko Bonadei675513b2017-11-09 11:09:25 +0100852 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800853
854 webrtc_session_desc_factory_.reset();
855 sctp_invoker_.reset();
856 sctp_factory_.reset();
857 transport_controller_.reset();
858
deadbeef91dd5672016-05-18 16:55:30 -0700859 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700860 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700861 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700862 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700863 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700864 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800865 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700866 event_log_.reset();
867 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868}
869
Steve Anton8af21862017-12-15 11:20:13 -0800870void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800871 // Destroy video channels first since they may have a pointer to a voice
872 // channel.
873 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800874 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800875 DestroyTransceiverChannel(transceiver);
876 }
877 }
878 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800879 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800880 DestroyTransceiverChannel(transceiver);
881 }
882 }
883 DestroyDataChannel();
884}
885
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000887 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700888 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100889 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700890
891 RTCError config_error = ValidateConfiguration(configuration);
892 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100893 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700894 return false;
895 }
896
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LS_ERROR)
899 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100900 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800901 return false;
902 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200903
Benjamin Wrightcab58882018-05-02 15:12:47 -0700904 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800905 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100906 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100907 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800908 return false;
909 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700910
Benjamin Wrightcab58882018-05-02 15:12:47 -0700911 observer_ = dependencies.observer;
912 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700913 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800914
deadbeef91dd5672016-05-18 16:55:30 -0700915 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700916 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700917 if (!network_thread()->Invoke<bool>(
918 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
919 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920 return false;
921 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922
Zhi Huange830e682018-03-30 10:48:35 -0700923 const PeerConnectionFactoryInterface::Options& options = factory_->options();
924
Steve Anton75737c02017-11-06 10:37:17 -0800925 // RFC 3264: The numeric value of the session id and version in the
926 // o line MUST be representable with a "64 bit signed integer".
927 // Due to this constraint session id |session_id_| is max limited to
928 // LLONG_MAX.
929 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700930 JsepTransportController::Config config;
931 config.redetermine_role_on_ice_restart =
932 configuration.redetermine_role_on_ice_restart;
933 config.ssl_max_version = factory_->options().ssl_max_version;
934 config.disable_encryption = options.disable_encryption;
935 config.bundle_policy = configuration.bundle_policy;
936 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
937 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700938 config.transport_observer = this;
Zhi Huange830e682018-03-30 10:48:35 -0700939#if defined(ENABLE_EXTERNAL_AUTH)
940 config.enable_external_auth = true;
941#endif
Zhi Huangbae10312018-06-08 14:55:27 -0700942 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700943 transport_controller_.reset(new JsepTransportController(
944 signaling_thread(), network_thread(), port_allocator_.get(), config));
945 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800946 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700947 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800948 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700949 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800950 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700951 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800952 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
953 transport_controller_->SignalDtlsHandshakeError.connect(
954 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
955
956 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700957
deadbeefab9b2d12015-10-14 11:33:11 -0700958 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700959 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960
Steve Antonba818672017-11-06 10:21:57 -0800961 configuration_ = configuration;
962
Steve Anton75737c02017-11-06 10:37:17 -0800963 // Obtain a certificate from RTCConfiguration if any were provided (optional).
964 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
965 if (!configuration.certificates.empty()) {
966 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
967 // just picking the first one. The decision should be made based on the DTLS
968 // handshake. The DTLS negotiations need to know about all certificates.
969 certificate = configuration.certificates[0];
970 }
971
Steve Antond25da372017-11-06 14:50:29 -0800972 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800973
974 if (options.disable_encryption) {
975 dtls_enabled_ = false;
976 } else {
977 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700978 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800979 // |configuration| can override the default |dtls_enabled_| value.
980 if (configuration.enable_dtls_srtp) {
981 dtls_enabled_ = *(configuration.enable_dtls_srtp);
982 }
983 }
984
985 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
986 // It takes precendence over the disable_sctp_data_channels
987 // PeerConnectionFactoryInterface::Options.
988 if (configuration.enable_rtp_data_channel) {
989 data_channel_type_ = cricket::DCT_RTP;
990 } else {
991 // DTLS has to be enabled to use SCTP.
992 if (!options.disable_sctp_data_channels && dtls_enabled_) {
993 data_channel_type_ = cricket::DCT_SCTP;
994 }
995 }
996
997 video_options_.screencast_min_bitrate_kbps =
998 configuration.screencast_min_bitrate;
999 audio_options_.combined_audio_video_bwe =
1000 configuration.combined_audio_video_bwe;
1001
1002 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001003 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001004
1005 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001006 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001007
1008 // Whether the certificate generator/certificate is null or not determines
1009 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1010 // the right instructions by clearing the variables if needed.
1011 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001012 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001013 certificate = nullptr;
1014 } else if (certificate) {
1015 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001016 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001017 }
1018
1019 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1020 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001021 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001022 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1023 this, &PeerConnection::OnCertificateReady);
1024
1025 if (options.disable_encryption) {
1026 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1027 }
1028
1029 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1030 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031
Steve Anton4171afb2017-11-20 10:20:22 -08001032 // Add default audio/video transceivers for Plan B SDP.
1033 if (!IsUnifiedPlan()) {
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1037 transceivers_.push_back(
1038 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1039 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1040 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001041 return true;
1042}
1043
Steve Anton038834f2017-07-14 15:59:59 -07001044RTCError PeerConnection::ValidateConfiguration(
1045 const RTCConfiguration& config) const {
1046 if (config.ice_regather_interval_range &&
1047 config.continual_gathering_policy == GATHER_ONCE) {
1048 return RTCError(RTCErrorType::INVALID_PARAMETER,
1049 "ice_regather_interval_range specified but continual "
1050 "gathering policy is GATHER_ONCE");
1051 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001052 auto result =
1053 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1054 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001055}
1056
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001057rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001059 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1060 "Plan SdpSemantics. Please use GetSenders "
1061 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001062 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063}
1064
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001065rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001067 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1068 "Plan SdpSemantics. Please use GetReceivers "
1069 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001070 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071}
1072
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001073bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001074 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1075 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001076 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077 if (IsClosed()) {
1078 return false;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 return false;
1082 }
deadbeefab9b2d12015-10-14 11:33:11 -07001083
1084 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001085 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1086 observer->SignalAudioTrackAdded.connect(this,
1087 &PeerConnection::OnAudioTrackAdded);
1088 observer->SignalAudioTrackRemoved.connect(
1089 this, &PeerConnection::OnAudioTrackRemoved);
1090 observer->SignalVideoTrackAdded.connect(this,
1091 &PeerConnection::OnVideoTrackAdded);
1092 observer->SignalVideoTrackRemoved.connect(
1093 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001094 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001095
deadbeefab9b2d12015-10-14 11:33:11 -07001096 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001097 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001100 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001101 }
1102
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001103 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 observer_->OnRenegotiationNeeded();
1105 return true;
1106}
1107
1108void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001109 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1110 "Plan SdpSemantics. Please use RemoveTrack "
1111 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001112 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001113 if (!IsClosed()) {
1114 for (const auto& track : local_stream->GetAudioTracks()) {
1115 RemoveAudioTrack(track.get(), local_stream);
1116 }
1117 for (const auto& track : local_stream->GetVideoTracks()) {
1118 RemoveVideoTrack(track.get(), local_stream);
1119 }
deadbeefab9b2d12015-10-14 11:33:11 -07001120 }
deadbeefab9b2d12015-10-14 11:33:11 -07001121 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001122 stream_observers_.erase(
1123 std::remove_if(
1124 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001125 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001126 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001127 }),
1128 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001129
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 if (IsClosed()) {
1131 return;
1132 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133 observer_->OnRenegotiationNeeded();
1134}
1135
deadbeefe1f9d832016-01-14 15:35:42 -08001136rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1137 MediaStreamTrackInterface* track,
1138 std::vector<MediaStreamInterface*> streams) {
1139 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001140 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001141 for (auto* stream : streams) {
1142 if (!stream) {
1143 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1144 return nullptr;
1145 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001146 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001147 }
Seth Hampson845e8782018-03-02 11:34:10 -08001148 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001149 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001150 return nullptr;
1151 }
Steve Antonf9381f02017-12-14 10:23:57 -08001152 return sender_or_error.MoveValue();
1153}
1154
Steve Anton2d6c76a2018-01-05 17:10:52 -08001155RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001156 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001157 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001158 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001159 if (!track) {
1160 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1161 }
1162 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1163 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1165 "Track has invalid kind: " + track->kind());
1166 }
Steve Antonf9381f02017-12-14 10:23:57 -08001167 if (IsClosed()) {
1168 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1169 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001170 }
Steve Anton4171afb2017-11-20 10:20:22 -08001171 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001172 LOG_AND_RETURN_ERROR(
1173 RTCErrorType::INVALID_PARAMETER,
1174 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001175 }
Steve Antonf9381f02017-12-14 10:23:57 -08001176 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001177 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1178 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001179 if (sender_or_error.ok()) {
1180 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001181 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001182 }
1183 return sender_or_error;
1184}
deadbeefe1f9d832016-01-14 15:35:42 -08001185
Steve Antonf9381f02017-12-14 10:23:57 -08001186RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1187PeerConnection::AddTrackPlanB(
1188 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001189 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001190 if (stream_ids.size() > 1u) {
1191 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1192 "AddTrack with more than one stream is not "
1193 "supported with Plan B semantics.");
1194 }
1195 std::vector<std::string> adjusted_stream_ids = stream_ids;
1196 if (adjusted_stream_ids.empty()) {
1197 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1198 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001199 cricket::MediaType media_type =
1200 (track->kind() == MediaStreamTrackInterface::kAudioKind
1201 ? cricket::MEDIA_TYPE_AUDIO
1202 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001203 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001204 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001205 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001206 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001207 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001208 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001209 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001210 if (sender_info) {
1211 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001212 }
Steve Antonf9381f02017-12-14 10:23:57 -08001213 } else {
1214 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001215 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001216 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001217 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001218 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001219 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001220 if (sender_info) {
1221 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001222 }
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001224 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001225}
deadbeefe1f9d832016-01-14 15:35:42 -08001226
Steve Antonf9381f02017-12-14 10:23:57 -08001227RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1228PeerConnection::AddTrackUnifiedPlan(
1229 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001230 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001231 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1232 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001233 RTC_LOG(LS_INFO) << "Reusing an existing "
1234 << cricket::MediaTypeToString(transceiver->media_type())
1235 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001236 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001239 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001240 transceiver->internal()->set_direction(
1241 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001242 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001243 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001244 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001245 } else {
1246 cricket::MediaType media_type =
1247 (track->kind() == MediaStreamTrackInterface::kAudioKind
1248 ? cricket::MEDIA_TYPE_AUDIO
1249 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001250 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1251 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001252 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001253 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1254 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001255 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001256 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001257 }
Steve Antonf9381f02017-12-14 10:23:57 -08001258 return transceiver->sender();
1259}
1260
1261rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1262PeerConnection::FindFirstTransceiverForAddedTrack(
1263 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1264 RTC_DCHECK(track);
1265 for (auto transceiver : transceivers_) {
1266 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001267 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001268 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001269 !transceiver->internal()->has_ever_been_used_to_send() &&
1270 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001271 return transceiver;
1272 }
1273 }
1274 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001275}
1276
1277bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1278 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001279 return RemoveTrackInternal(sender).ok();
1280}
1281
1282RTCError PeerConnection::RemoveTrackInternal(
1283 rtc::scoped_refptr<RtpSenderInterface> sender) {
1284 if (!sender) {
1285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1286 }
deadbeefe1f9d832016-01-14 15:35:42 -08001287 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001288 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1289 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001290 }
Steve Antonf9381f02017-12-14 10:23:57 -08001291 if (IsUnifiedPlan()) {
1292 auto transceiver = FindTransceiverBySender(sender);
1293 if (!transceiver || !sender->track()) {
1294 return RTCError::OK();
1295 }
1296 sender->SetTrack(nullptr);
1297 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001300 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001301 transceiver->internal()->set_direction(
1302 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001303 }
Steve Anton4171afb2017-11-20 10:20:22 -08001304 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001305 bool removed;
1306 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1307 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1308 } else {
1309 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1310 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1311 }
1312 if (!removed) {
1313 LOG_AND_RETURN_ERROR(
1314 RTCErrorType::INVALID_PARAMETER,
1315 "Couldn't find sender " + sender->id() + " to remove.");
1316 }
Steve Anton4171afb2017-11-20 10:20:22 -08001317 }
deadbeefe1f9d832016-01-14 15:35:42 -08001318 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001319 return RTCError::OK();
1320}
1321
1322rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1323PeerConnection::FindTransceiverBySender(
1324 rtc::scoped_refptr<RtpSenderInterface> sender) {
1325 for (auto transceiver : transceivers_) {
1326 if (transceiver->sender() == sender) {
1327 return transceiver;
1328 }
1329 }
1330 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001331}
1332
Steve Anton9158ef62017-11-27 13:01:52 -08001333RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1334PeerConnection::AddTransceiver(
1335 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1336 return AddTransceiver(track, RtpTransceiverInit());
1337}
1338
1339RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1340PeerConnection::AddTransceiver(
1341 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1342 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001343 RTC_CHECK(IsUnifiedPlan())
1344 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001345 if (!track) {
1346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1347 }
1348 cricket::MediaType media_type;
1349 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1350 media_type = cricket::MEDIA_TYPE_AUDIO;
1351 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1352 media_type = cricket::MEDIA_TYPE_VIDEO;
1353 } else {
1354 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1355 "Track kind is not audio or video");
1356 }
1357 return AddTransceiver(media_type, track, init);
1358}
1359
1360RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1361PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1362 return AddTransceiver(media_type, RtpTransceiverInit());
1363}
1364
1365RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1366PeerConnection::AddTransceiver(cricket::MediaType media_type,
1367 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001368 RTC_CHECK(IsUnifiedPlan())
1369 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001370 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1371 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1372 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1373 "media type is not audio or video");
1374 }
1375 return AddTransceiver(media_type, nullptr, init);
1376}
1377
1378RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1379PeerConnection::AddTransceiver(
1380 cricket::MediaType media_type,
1381 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001382 const RtpTransceiverInit& init,
1383 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001384 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1385 media_type == cricket::MEDIA_TYPE_VIDEO));
1386 if (track) {
1387 RTC_DCHECK_EQ(media_type,
1388 (track->kind() == MediaStreamTrackInterface::kAudioKind
1389 ? cricket::MEDIA_TYPE_AUDIO
1390 : cricket::MEDIA_TYPE_VIDEO));
1391 }
1392
1393 // TODO(bugs.webrtc.org/7600): Verify init.
1394
Steve Anton3d954a62018-04-02 11:27:23 -07001395 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1396 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001397 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001398 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1399 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1400 transceiver->internal()->set_direction(init.direction);
1401
Steve Anton22da89f2018-01-25 13:58:07 -08001402 if (fire_callback) {
1403 observer_->OnRenegotiationNeeded();
1404 }
Steve Antonf9381f02017-12-14 10:23:57 -08001405
1406 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1407}
1408
Steve Anton02ee47c2018-01-10 16:26:06 -08001409rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1410PeerConnection::CreateSender(
1411 cricket::MediaType media_type,
1412 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001413 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001414 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001415 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1416 RTC_DCHECK(!track ||
1417 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1418 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1419 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001420 new AudioRtpSender(worker_thread(),
1421 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001422 stream_ids, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001423 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001424 } else {
1425 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1426 RTC_DCHECK(!track ||
1427 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1428 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1429 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001430 new VideoRtpSender(worker_thread(),
1431 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001432 stream_ids));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001433 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001434 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001435 return sender;
1436}
1437
1438rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1439PeerConnection::CreateReceiver(cricket::MediaType media_type,
1440 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001441 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1442 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001443 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001444 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001445 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001446 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001447 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001448 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001449 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001450 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1451 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001452 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001453 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001454 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001455 return receiver;
1456}
1457
1458rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1459PeerConnection::CreateAndAddTransceiver(
1460 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1461 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1462 receiver) {
1463 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1464 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001465 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001466 transceiver->internal()->SignalNegotiationNeeded.connect(
1467 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001468 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001469}
1470
Steve Anton52d86772018-02-20 15:48:12 -08001471void PeerConnection::OnNegotiationNeeded() {
1472 RTC_DCHECK_RUN_ON(signaling_thread());
1473 RTC_DCHECK(!IsClosed());
1474 observer_->OnRenegotiationNeeded();
1475}
1476
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001477rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001478 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001479 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001480 if (IsClosed()) {
1481 return nullptr;
1482 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001483 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001484 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001485 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001486 }
Steve Anton4171afb2017-11-20 10:20:22 -08001487 auto track_sender = FindSenderForTrack(track);
1488 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001489 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001490 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001491 }
1492
Steve Anton4171afb2017-11-20 10:20:22 -08001493 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001494}
1495
deadbeeffac06552015-11-25 11:26:01 -08001496rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001497 const std::string& kind,
1498 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001499 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1500 "Plan SdpSemantics. Please use AddTransceiver "
1501 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001502 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001503 if (IsClosed()) {
1504 return nullptr;
1505 }
Steve Anton4171afb2017-11-20 10:20:22 -08001506
Seth Hampson5b4f0752018-04-02 16:31:36 -07001507 // Internally we need to have one stream with Plan B semantics, so we
1508 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001509 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001510 if (stream_id.empty()) {
1511 stream_ids.push_back(rtc::CreateRandomUuid());
1512 RTC_LOG(LS_INFO)
1513 << "No stream_id specified for sender. Generated stream ID: "
1514 << stream_ids[0];
1515 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001516 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001517 }
1518
Steve Anton4171afb2017-11-20 10:20:22 -08001519 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001520 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001521 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001522 auto* audio_sender =
1523 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001524 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001525 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001526 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001527 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001528 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001529 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001530 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001531 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001532 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001533 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001534 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001535 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001536 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001537 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001538 }
Steve Anton4171afb2017-11-20 10:20:22 -08001539
deadbeefe1f9d832016-01-14 15:35:42 -08001540 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001541}
1542
deadbeef70ab1a12015-09-28 16:53:55 -07001543std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1544 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001545 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001546 for (auto sender : GetSendersInternal()) {
1547 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001548 }
1549 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001550}
1551
Steve Anton4171afb2017-11-20 10:20:22 -08001552std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1553PeerConnection::GetSendersInternal() const {
1554 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1555 all_senders;
1556 for (auto transceiver : transceivers_) {
1557 auto senders = transceiver->internal()->senders();
1558 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1559 }
1560 return all_senders;
1561}
1562
deadbeef70ab1a12015-09-28 16:53:55 -07001563std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1564PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001565 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001566 for (const auto& receiver : GetReceiversInternal()) {
1567 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001568 }
1569 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001570}
1571
Steve Anton4171afb2017-11-20 10:20:22 -08001572std::vector<
1573 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1574PeerConnection::GetReceiversInternal() const {
1575 std::vector<
1576 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1577 all_receivers;
1578 for (auto transceiver : transceivers_) {
1579 auto receivers = transceiver->internal()->receivers();
1580 all_receivers.insert(all_receivers.end(), receivers.begin(),
1581 receivers.end());
1582 }
1583 return all_receivers;
1584}
1585
Steve Anton9158ef62017-11-27 13:01:52 -08001586std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1587PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001588 RTC_CHECK(IsUnifiedPlan())
1589 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001590 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1591 for (auto transceiver : transceivers_) {
1592 all_transceivers.push_back(transceiver);
1593 }
1594 return all_transceivers;
1595}
1596
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001597bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001598 MediaStreamTrackInterface* track,
1599 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001600 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001601 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001602 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001603 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001604 return false;
1605 }
1606
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001607 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001608 // The StatsCollector is used to tell if a track is valid because it may
1609 // remember tracks that the PeerConnection previously removed.
1610 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001611 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1612 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001613 return false;
1614 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001615 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001616 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001617 return true;
1618}
1619
hbos74e1a4f2016-09-15 23:33:01 -07001620void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001621 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001622 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001623 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001624 stats_collector_->GetStatsReport(callback);
1625}
1626
Henrik Boström1df1bf82018-03-20 13:24:20 +01001627void PeerConnection::GetStats(
1628 rtc::scoped_refptr<RtpSenderInterface> selector,
1629 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1630 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1631 RTC_DCHECK(callback);
1632 RTC_DCHECK(stats_collector_);
1633 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1634 if (selector) {
1635 for (const auto& proxy_transceiver : transceivers_) {
1636 for (const auto& proxy_sender :
1637 proxy_transceiver->internal()->senders()) {
1638 if (proxy_sender == selector) {
1639 internal_sender = proxy_sender->internal();
1640 break;
1641 }
1642 }
1643 if (internal_sender)
1644 break;
1645 }
1646 }
1647 // If there is no |internal_sender| then |selector| is either null or does not
1648 // belong to the PeerConnection (in Plan B, senders can be removed from the
1649 // PeerConnection). This means that "all the stats objects representing the
1650 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1651 // produces an empty stats report.
1652 stats_collector_->GetStatsReport(internal_sender, callback);
1653}
1654
1655void PeerConnection::GetStats(
1656 rtc::scoped_refptr<RtpReceiverInterface> selector,
1657 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1658 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1659 RTC_DCHECK(callback);
1660 RTC_DCHECK(stats_collector_);
1661 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1662 if (selector) {
1663 for (const auto& proxy_transceiver : transceivers_) {
1664 for (const auto& proxy_receiver :
1665 proxy_transceiver->internal()->receivers()) {
1666 if (proxy_receiver == selector) {
1667 internal_receiver = proxy_receiver->internal();
1668 break;
1669 }
1670 }
1671 if (internal_receiver)
1672 break;
1673 }
1674 }
1675 // If there is no |internal_receiver| then |selector| is either null or does
1676 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1677 // the PeerConnection). This means that "all the stats objects representing
1678 // the selector" is an empty set. Invoking GetStatsReport() with a null
1679 // selector produces an empty stats report.
1680 stats_collector_->GetStatsReport(internal_receiver, callback);
1681}
1682
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1684 return signaling_state_;
1685}
1686
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687PeerConnectionInterface::IceConnectionState
1688PeerConnection::ice_connection_state() {
1689 return ice_connection_state_;
1690}
1691
1692PeerConnectionInterface::IceGatheringState
1693PeerConnection::ice_gathering_state() {
1694 return ice_gathering_state_;
1695}
1696
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001697rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698PeerConnection::CreateDataChannel(
1699 const std::string& label,
1700 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001701 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001702
deadbeefab9b2d12015-10-14 11:33:11 -07001703 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001704
kwibergd1fe2812016-04-27 06:47:29 -07001705 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001706 if (config) {
1707 internal_config.reset(new InternalDataChannelInit(*config));
1708 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001709 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001710 InternalCreateDataChannel(label, internal_config.get()));
1711 if (!channel.get()) {
1712 return nullptr;
1713 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001714
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001715 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1716 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001717 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001718 observer_->OnRenegotiationNeeded();
1719 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001720 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001721 return DataChannelProxy::Create(signaling_thread(), channel.get());
1722}
1723
1724void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1725 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001726 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001727
zhihuang1c378ed2017-08-17 14:10:50 -07001728 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1729 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1730 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1731 // compares the mandatory fields parsed with the mandatory fields added in the
1732 // |constraints| and some downstream applications might create offers with
1733 // mandatory fields which would not be parsed in the helper method. For
1734 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1735 // |constraints| as a mandatory field but it is not parsed.
1736 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001737
zhihuang1c378ed2017-08-17 14:10:50 -07001738 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001739}
1740
1741void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1742 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001743 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001744
nisse7ce109a2017-01-31 00:57:56 -08001745 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001746 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001747 return;
1748 }
deadbeefab9b2d12015-10-14 11:33:11 -07001749
Steve Anton8d3444d2017-10-20 15:30:51 -07001750 if (IsClosed()) {
1751 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001752 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001753 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001754 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001755 return;
1756 }
1757
zhihuang1c378ed2017-08-17 14:10:50 -07001758 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001759 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001761 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001762 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001763 return;
1764 }
1765
Steve Anton22da89f2018-01-25 13:58:07 -08001766 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1767 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1768 if (IsUnifiedPlan()) {
1769 RTCError error = HandleLegacyOfferOptions(options);
1770 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001771 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001772 return;
1773 }
1774 }
1775
zhihuang1c378ed2017-08-17 14:10:50 -07001776 cricket::MediaSessionOptions session_options;
1777 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001778 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779}
1780
Steve Anton22da89f2018-01-25 13:58:07 -08001781RTCError PeerConnection::HandleLegacyOfferOptions(
1782 const RTCOfferAnswerOptions& options) {
1783 RTC_DCHECK(IsUnifiedPlan());
1784
1785 if (options.offer_to_receive_audio == 0) {
1786 RemoveRecvDirectionFromReceivingTransceiversOfType(
1787 cricket::MEDIA_TYPE_AUDIO);
1788 } else if (options.offer_to_receive_audio == 1) {
1789 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1790 } else if (options.offer_to_receive_audio > 1) {
1791 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1792 "offer_to_receive_audio > 1 is not supported.");
1793 }
1794
1795 if (options.offer_to_receive_video == 0) {
1796 RemoveRecvDirectionFromReceivingTransceiversOfType(
1797 cricket::MEDIA_TYPE_VIDEO);
1798 } else if (options.offer_to_receive_video == 1) {
1799 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1800 } else if (options.offer_to_receive_video > 1) {
1801 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1802 "offer_to_receive_video > 1 is not supported.");
1803 }
1804
1805 return RTCError::OK();
1806}
1807
1808void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1809 cricket::MediaType media_type) {
1810 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001811 RtpTransceiverDirection new_direction =
1812 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1813 if (new_direction != transceiver->direction()) {
1814 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1815 << " transceiver (MID="
1816 << transceiver->mid().value_or("<not set>") << ") from "
1817 << RtpTransceiverDirectionToString(
1818 transceiver->direction())
1819 << " to "
1820 << RtpTransceiverDirectionToString(new_direction)
1821 << " since CreateOffer specified offer_to_receive=0";
1822 transceiver->internal()->set_direction(new_direction);
1823 }
Steve Anton22da89f2018-01-25 13:58:07 -08001824 }
1825}
1826
1827void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1828 cricket::MediaType media_type) {
1829 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001830 RTC_LOG(LS_INFO)
1831 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1832 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001833 RtpTransceiverInit init;
1834 init.direction = RtpTransceiverDirection::kRecvOnly;
1835 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1836 }
1837}
1838
1839std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1840PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1841 std::vector<
1842 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1843 receiving_transceivers;
1844 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001845 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001846 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1847 receiving_transceivers.push_back(transceiver);
1848 }
1849 }
1850 return receiving_transceivers;
1851}
1852
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853void PeerConnection::CreateAnswer(
1854 CreateSessionDescriptionObserver* observer,
1855 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001856 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001857
nisse7ce109a2017-01-31 00:57:56 -08001858 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001859 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001860 return;
1861 }
deadbeefab9b2d12015-10-14 11:33:11 -07001862
zhihuang1c378ed2017-08-17 14:10:50 -07001863 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1864 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1865 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001866 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001867 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001868 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001869 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001870 return;
1871 }
1872
Steve Anton8d3444d2017-10-20 15:30:51 -07001873 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001874}
1875
1876void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1877 const RTCOfferAnswerOptions& options) {
1878 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001879 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001880 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001881 return;
1882 }
1883
Steve Antondffead82018-02-06 10:31:29 -08001884 if (!(signaling_state_ == kHaveRemoteOffer ||
1885 signaling_state_ == kHaveLocalPrAnswer)) {
1886 std::string error =
1887 "PeerConnection cannot create an answer in a state other than "
1888 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001889 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001890 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001891 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001892 return;
1893 }
1894
Steve Antondffead82018-02-06 10:31:29 -08001895 // The remote description should be set if we're in the right state.
1896 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001897
Steve Anton22da89f2018-01-25 13:58:07 -08001898 if (IsUnifiedPlan()) {
1899 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1900 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1901 "supported with Unified Plan semantics. Use the "
1902 "RtpTransceiver API instead.";
1903 }
1904 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1905 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1906 "supported with Unified Plan semantics. Use the "
1907 "RtpTransceiver API instead.";
1908 }
1909 }
1910
htaa2a49d92016-03-04 02:51:39 -08001911 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001912 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001913
Steve Antond25da372017-11-06 14:50:29 -08001914 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001915}
1916
1917void PeerConnection::SetLocalDescription(
1918 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001919 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001920 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001921
Steve Anton80dd7b52018-02-16 17:08:42 -08001922 // The SetLocalDescription contract is that we take ownership of the session
1923 // description regardless of the outcome, so wrap it in a unique_ptr right
1924 // away. Ideally, SetLocalDescription's signature will be changed to take the
1925 // description as a unique_ptr argument to formalize this agreement.
1926 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1927
nisse7ce109a2017-01-31 00:57:56 -08001928 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001929 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001930 return;
1931 }
Steve Anton8a006912017-12-04 15:25:56 -08001932
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001933 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001934 PostSetSessionDescriptionFailure(
1935 observer,
1936 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001937 return;
1938 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001939
Steve Anton80dd7b52018-02-16 17:08:42 -08001940 // If a session error has occurred the PeerConnection is in a possibly
1941 // inconsistent state so fail right away.
1942 if (session_error() != SessionError::kNone) {
1943 std::string error_message = GetSessionErrorMsg();
1944 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001945 PostSetSessionDescriptionFailure(
1946 observer,
1947 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001948 return;
1949 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001950
Steve Anton80dd7b52018-02-16 17:08:42 -08001951 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1952 if (!error.ok()) {
1953 std::string error_message = GetSetDescriptionErrorMessage(
1954 cricket::CS_LOCAL, desc->GetType(), error);
1955 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001956 PostSetSessionDescriptionFailure(
1957 observer,
1958 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001959 return;
1960 }
1961
1962 // Grab the description type before moving ownership to ApplyLocalDescription,
1963 // which may destroy it before returning.
1964 const SdpType type = desc->GetType();
1965
1966 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001967 // |desc| may be destroyed at this point.
1968
1969 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001970 // If ApplyLocalDescription fails, the PeerConnection could be in an
1971 // inconsistent state, so act conservatively here and set the session error
1972 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1973 SetSessionError(SessionError::kContent, error.message());
1974 std::string error_message =
1975 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1976 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001977 PostSetSessionDescriptionFailure(
1978 observer,
1979 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001980 return;
1981 }
Steve Anton8a006912017-12-04 15:25:56 -08001982 RTC_DCHECK(local_description());
1983
1984 PostSetSessionDescriptionSuccess(observer);
1985
Steve Anton8a006912017-12-04 15:25:56 -08001986 // MaybeStartGathering needs to be called after posting
1987 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1988 // before signaling that SetLocalDescription completed.
1989 transport_controller_->MaybeStartGathering();
1990
Steve Antona3a92c22017-12-07 10:27:41 -08001991 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001992 // TODO(deadbeef): We already had to hop to the network thread for
1993 // MaybeStartGathering...
1994 network_thread()->Invoke<void>(
1995 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1996 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001997 // Make UMA notes about what was agreed to.
1998 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001999 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002000 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002001}
2002
2003RTCError PeerConnection::ApplyLocalDescription(
2004 std::unique_ptr<SessionDescriptionInterface> desc) {
2005 RTC_DCHECK_RUN_ON(signaling_thread());
2006 RTC_DCHECK(desc);
2007
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008 // Update stats here so that we have the most recent stats for tracks and
2009 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002010 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002011
Steve Antondcc3c022017-12-22 16:02:54 -08002012 // Take a reference to the old local description since it's used below to
2013 // compare against the new local description. When setting the new local
2014 // description, grab ownership of the replaced session description in case it
2015 // is the same as |old_local_description|, to keep it alive for the duration
2016 // of the method.
2017 const SessionDescriptionInterface* old_local_description =
2018 local_description();
2019 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002020 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002021 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002022 replaced_local_description = pending_local_description_
2023 ? std::move(pending_local_description_)
2024 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002025 current_local_description_ = std::move(desc);
2026 pending_local_description_ = nullptr;
2027 current_remote_description_ = std::move(pending_remote_description_);
2028 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002029 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002030 pending_local_description_ = std::move(desc);
2031 }
2032 // The session description to apply now must be accessed by
2033 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002034 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002035
Zhi Huange830e682018-03-30 10:48:35 -07002036 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2037 if (!error.ok()) {
2038 return error;
2039 }
2040
Steve Antondcc3c022017-12-22 16:02:54 -08002041 if (IsUnifiedPlan()) {
2042 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002043 cricket::CS_LOCAL, *local_description(), old_local_description,
2044 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002045 if (!error.ok()) {
2046 return error;
2047 }
Steve Antondcc3c022017-12-22 16:02:54 -08002048 for (auto transceiver : transceivers_) {
2049 const ContentInfo* content =
2050 FindMediaSectionForTransceiver(transceiver, local_description());
2051 if (!content) {
2052 continue;
2053 }
2054 const MediaContentDescription* media_desc = content->media_description();
2055 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2056 transceiver->internal()->set_current_direction(media_desc->direction());
2057 }
2058 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002059 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2060 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002061 transceiver->Stop();
2062 }
2063 }
2064 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002065 // Media channels will be created only when offer is set. These may use new
2066 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002067 if (type == SdpType::kOffer) {
2068 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2069 // description is applied. Restore back to old description.
2070 RTCError error = CreateChannels(*local_description()->description());
2071 if (!error.ok()) {
2072 return error;
2073 }
2074 }
Steve Antondcc3c022017-12-22 16:02:54 -08002075 // Remove unused channels if MediaContentDescription is rejected.
2076 RemoveUnusedChannels(local_description()->description());
2077 }
Steve Anton8a006912017-12-04 15:25:56 -08002078
Zhi Huange830e682018-03-30 10:48:35 -07002079 error = UpdateSessionState(type, cricket::CS_LOCAL,
2080 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002081 if (!error.ok()) {
2082 return error;
2083 }
Steve Antondcc3c022017-12-22 16:02:54 -08002084
Steve Anton8a006912017-12-04 15:25:56 -08002085 if (remote_description()) {
2086 // Now that we have a local description, we can push down remote candidates.
2087 UseCandidatesInSessionDescription(remote_description());
2088 }
2089
2090 pending_ice_restarts_.clear();
2091 if (session_error() != SessionError::kNone) {
2092 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2093 }
2094
deadbeefab9b2d12015-10-14 11:33:11 -07002095 // If setting the description decided our SSL role, allocate any necessary
2096 // SCTP sids.
2097 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002098 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002099 AllocateSctpSids(role);
2100 }
2101
Steve Antond3679212018-01-17 17:41:02 -08002102 if (IsUnifiedPlan()) {
2103 for (auto transceiver : transceivers_) {
2104 const ContentInfo* content =
2105 FindMediaSectionForTransceiver(transceiver, local_description());
2106 if (!content) {
2107 continue;
2108 }
Steve Anton74255ff2018-01-24 18:32:57 -08002109 const auto& streams = content->media_description()->streams();
2110 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002111 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002112 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002113 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002114 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002115 }
2116 }
2117 } else {
2118 // Plan B semantics.
2119
Steve Antondcc3c022017-12-22 16:02:54 -08002120 // Update state and SSRC of local MediaStreams and DataChannels based on the
2121 // local session description.
2122 const cricket::ContentInfo* audio_content =
2123 GetFirstAudioContent(local_description()->description());
2124 if (audio_content) {
2125 if (audio_content->rejected) {
2126 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2127 } else {
2128 const cricket::AudioContentDescription* audio_desc =
2129 audio_content->media_description()->as_audio();
2130 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2131 }
deadbeeffaac4972015-11-12 15:33:07 -08002132 }
deadbeefab9b2d12015-10-14 11:33:11 -07002133
Steve Antondcc3c022017-12-22 16:02:54 -08002134 const cricket::ContentInfo* video_content =
2135 GetFirstVideoContent(local_description()->description());
2136 if (video_content) {
2137 if (video_content->rejected) {
2138 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2139 } else {
2140 const cricket::VideoContentDescription* video_desc =
2141 video_content->media_description()->as_video();
2142 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2143 }
deadbeeffaac4972015-11-12 15:33:07 -08002144 }
deadbeefab9b2d12015-10-14 11:33:11 -07002145 }
2146
2147 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002148 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002149 if (data_content) {
2150 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002151 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002152 if (rtc::starts_with(data_desc->protocol().data(),
2153 cricket::kMediaProtocolRtpPrefix)) {
2154 UpdateLocalRtpDataChannels(data_desc->streams());
2155 }
2156 }
2157
Steve Anton8a006912017-12-04 15:25:56 -08002158 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002159}
2160
2161void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002162 SetSessionDescriptionObserver* observer,
2163 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002164 SetRemoteDescription(
2165 std::unique_ptr<SessionDescriptionInterface>(desc),
2166 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2167 new SetRemoteDescriptionObserverAdapter(this, observer)));
2168}
2169
2170void PeerConnection::SetRemoteDescription(
2171 std::unique_ptr<SessionDescriptionInterface> desc,
2172 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002173 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002174
nisse7ce109a2017-01-31 00:57:56 -08002175 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002176 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002177 return;
2178 }
Steve Anton8a006912017-12-04 15:25:56 -08002179
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002181 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002182 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 return;
2184 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002185
Steve Anton80dd7b52018-02-16 17:08:42 -08002186 // If a session error has occurred the PeerConnection is in a possibly
2187 // inconsistent state so fail right away.
2188 if (session_error() != SessionError::kNone) {
2189 std::string error_message = GetSessionErrorMsg();
2190 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2191 observer->OnSetRemoteDescriptionComplete(
2192 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2193 return;
2194 }
Steve Anton71439a62018-02-15 11:53:06 -08002195
Steve Antonba42e992018-04-09 14:10:01 -07002196 if (desc->GetType() == SdpType::kOffer) {
2197 // Report to UMA the format of the received offer.
2198 ReportSdpFormatReceived(*desc);
2199 }
2200
Steve Anton80dd7b52018-02-16 17:08:42 -08002201 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002202 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002203 std::string error_message = GetSetDescriptionErrorMessage(
2204 cricket::CS_REMOTE, desc->GetType(), error);
2205 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002206 observer->OnSetRemoteDescriptionComplete(
2207 RTCError(error.type(), std::move(error_message)));
2208 return;
2209 }
Steve Anton71439a62018-02-15 11:53:06 -08002210
Steve Anton80dd7b52018-02-16 17:08:42 -08002211 // Grab the description type before moving ownership to
2212 // ApplyRemoteDescription, which may destroy it before returning.
2213 const SdpType type = desc->GetType();
2214
2215 error = ApplyRemoteDescription(std::move(desc));
2216 // |desc| may be destroyed at this point.
2217
2218 if (!error.ok()) {
2219 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2220 // inconsistent state, so act conservatively here and set the session error
2221 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2222 SetSessionError(SessionError::kContent, error.message());
2223 std::string error_message =
2224 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2225 RTC_LOG(LS_ERROR) << error_message;
2226 observer->OnSetRemoteDescriptionComplete(
2227 RTCError(error.type(), std::move(error_message)));
2228 return;
2229 }
2230 RTC_DCHECK(remote_description());
2231
2232 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002233 // TODO(deadbeef): We already had to hop to the network thread for
2234 // MaybeStartGathering...
2235 network_thread()->Invoke<void>(
2236 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2237 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002238 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002239 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002240 }
2241
2242 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002243 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002244}
2245
2246RTCError PeerConnection::ApplyRemoteDescription(
2247 std::unique_ptr<SessionDescriptionInterface> desc) {
2248 RTC_DCHECK_RUN_ON(signaling_thread());
2249 RTC_DCHECK(desc);
2250
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002251 // Update stats here so that we have the most recent stats for tracks and
2252 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002253 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002254
Steve Antondcc3c022017-12-22 16:02:54 -08002255 // Take a reference to the old remote description since it's used below to
2256 // compare against the new remote description. When setting the new remote
2257 // description, grab ownership of the replaced session description in case it
2258 // is the same as |old_remote_description|, to keep it alive for the duration
2259 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002260 const SessionDescriptionInterface* old_remote_description =
2261 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002262 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002263 SdpType type = desc->GetType();
2264 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002265 replaced_remote_description = pending_remote_description_
2266 ? std::move(pending_remote_description_)
2267 : std::move(current_remote_description_);
2268 current_remote_description_ = std::move(desc);
2269 pending_remote_description_ = nullptr;
2270 current_local_description_ = std::move(pending_local_description_);
2271 } else {
2272 replaced_remote_description = std::move(pending_remote_description_);
2273 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002274 }
Steve Anton8a006912017-12-04 15:25:56 -08002275 // The session description to apply now must be accessed by
2276 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002277 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278
Zhi Huange830e682018-03-30 10:48:35 -07002279 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2280 if (!error.ok()) {
2281 return error;
2282 }
Steve Anton8a006912017-12-04 15:25:56 -08002283 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002284 if (IsUnifiedPlan()) {
2285 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002286 cricket::CS_REMOTE, *remote_description(), local_description(),
2287 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002288 if (!error.ok()) {
2289 return error;
2290 }
Steve Antondcc3c022017-12-22 16:02:54 -08002291 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002292 // Media channels will be created only when offer is set. These may use new
2293 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002294 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002295 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002296 // description is applied. Restore back to old description.
2297 RTCError error = CreateChannels(*remote_description()->description());
2298 if (!error.ok()) {
2299 return error;
2300 }
2301 }
Steve Antondcc3c022017-12-22 16:02:54 -08002302 // Remove unused channels if MediaContentDescription is rejected.
2303 RemoveUnusedChannels(remote_description()->description());
2304 }
Steve Anton8a006912017-12-04 15:25:56 -08002305
Zhi Huange830e682018-03-30 10:48:35 -07002306 // NOTE: Candidates allocation will be initiated only when
2307 // SetLocalDescription is called.
2308 error = UpdateSessionState(type, cricket::CS_REMOTE,
2309 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002310 if (!error.ok()) {
2311 return error;
2312 }
2313
2314 if (local_description() &&
2315 !UseCandidatesInSessionDescription(remote_description())) {
2316 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2317 }
2318
2319 if (old_remote_description) {
2320 for (const cricket::ContentInfo& content :
2321 old_remote_description->description()->contents()) {
2322 // Check if this new SessionDescription contains new ICE ufrag and
2323 // password that indicates the remote peer requests an ICE restart.
2324 // TODO(deadbeef): When we start storing both the current and pending
2325 // remote description, this should reset pending_ice_restarts and compare
2326 // against the current description.
2327 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2328 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002329 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002330 pending_ice_restarts_.insert(content.name);
2331 }
2332 } else {
2333 // We retain all received candidates only if ICE is not restarted.
2334 // When ICE is restarted, all previous candidates belong to an old
2335 // generation and should not be kept.
2336 // TODO(deadbeef): This goes against the W3C spec which says the remote
2337 // description should only contain candidates from the last set remote
2338 // description plus any candidates added since then. We should remove
2339 // this once we're sure it won't break anything.
2340 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2341 old_remote_description, content.name, mutable_remote_description());
2342 }
2343 }
2344 }
2345
2346 if (session_error() != SessionError::kNone) {
2347 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2348 }
2349
2350 // Set the the ICE connection state to connecting since the connection may
2351 // become writable with peer reflexive candidates before any remote candidate
2352 // is signaled.
2353 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2354 // is to have a new signal the indicates a change in checking state from the
2355 // transport and expose a new checking() member from transport that can be
2356 // read to determine the current checking state. The existing SignalConnecting
2357 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002358 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002359 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002360 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2361 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2362 }
2363
deadbeefab9b2d12015-10-14 11:33:11 -07002364 // If setting the description decided our SSL role, allocate any necessary
2365 // SCTP sids.
2366 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002367 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002368 AllocateSctpSids(role);
2369 }
2370
Steve Antondcc3c022017-12-22 16:02:54 -08002371 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002372 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002373 now_receiving_transceivers;
2374 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2375 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002376 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002377 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002378 for (auto transceiver : transceivers_) {
2379 const ContentInfo* content =
2380 FindMediaSectionForTransceiver(transceiver, remote_description());
2381 if (!content) {
2382 continue;
2383 }
2384 const MediaContentDescription* media_desc = content->media_description();
2385 RtpTransceiverDirection local_direction =
2386 RtpTransceiverDirectionReversed(media_desc->direction());
2387 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2388 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2389 // transceiver's current direction is neither sendrecv nor recvonly,
2390 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002391 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002392 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002393 // The remote description has signaled the stream IDs.
2394 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002395 }
Steve Antondcc3c022017-12-22 16:02:54 -08002396 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2397 (!transceiver->current_direction() ||
2398 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002399 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002400 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002401 << content->name << " (added to "
2402 << GetStreamIdsString(stream_ids) << ").";
2403
2404 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2405 for (const std::string& stream_id : stream_ids) {
2406 rtc::scoped_refptr<MediaStreamInterface> stream =
2407 remote_streams_->find(stream_id);
2408 if (!stream) {
2409 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2410 MediaStream::Create(stream_id));
2411 remote_streams_->AddStream(stream);
2412 added_streams.push_back(stream);
2413 }
2414 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002415 }
Steve Anton3172c032018-05-03 15:30:18 -07002416 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002417 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002418 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002419 }
2420 // If direction is sendonly or inactive, and transceiver's current
2421 // direction is neither sendonly nor inactive, process the removal of a
2422 // remote track for the media description.
2423 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002424 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002425 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002426 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2427 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002428 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2429 transceiver->internal()->receiver_internal()->streams();
2430 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002431 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002432 no_longer_receiving_transceivers.push_back(transceiver);
2433 // Remove any streams that no longer have tracks.
2434 for (auto stream : media_streams) {
2435 if (stream->GetAudioTracks().empty() &&
2436 stream->GetVideoTracks().empty()) {
2437 remote_streams_->RemoveStream(stream);
2438 removed_streams.push_back(stream);
2439 }
2440 }
Steve Antondcc3c022017-12-22 16:02:54 -08002441 }
2442 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2443 transceiver->internal()->set_current_direction(local_direction);
2444 }
2445 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002446 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2447 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002448 transceiver->Stop();
2449 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002450 if (!content->rejected &&
2451 RtpTransceiverDirectionHasRecv(local_direction)) {
2452 // Set ssrc to 0 in the case of an unsignalled ssrc.
2453 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002454 if (!media_desc->streams().empty() &&
2455 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002456 ssrc = media_desc->streams()[0].first_ssrc();
2457 }
2458 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002459 }
Steve Antondcc3c022017-12-22 16:02:54 -08002460 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002461 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002462 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002463 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002464 observer_->OnTrack(transceiver);
2465 observer_->OnAddTrack(transceiver->receiver(),
2466 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002467 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002468 for (auto stream : added_streams) {
2469 observer_->OnAddStream(stream);
2470 }
Steve Anton3172c032018-05-03 15:30:18 -07002471 for (auto transceiver : no_longer_receiving_transceivers) {
2472 observer_->OnRemoveTrack(transceiver->receiver());
2473 }
2474 for (auto stream : removed_streams) {
2475 observer_->OnRemoveStream(stream);
2476 }
Steve Antondcc3c022017-12-22 16:02:54 -08002477 }
2478
Henrik Boströmfdb92012017-11-09 19:55:44 +01002479 const cricket::ContentInfo* audio_content =
2480 GetFirstAudioContent(remote_description()->description());
2481 const cricket::ContentInfo* video_content =
2482 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002483 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002484 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002485 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002486 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002487 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002488 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002489
2490 // Check if the descriptions include streams, just in case the peer supports
2491 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002492 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002493 (audio_desc && !audio_desc->streams().empty()) ||
2494 (video_desc && !video_desc->streams().empty())) {
2495 remote_peer_supports_msid_ = true;
2496 }
deadbeefab9b2d12015-10-14 11:33:11 -07002497
2498 // We wait to signal new streams until we finish processing the description,
2499 // since only at that point will new streams have all their tracks.
2500 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2501
Steve Antondcc3c022017-12-22 16:02:54 -08002502 if (!IsUnifiedPlan()) {
2503 // TODO(steveanton): When removing RTP senders/receivers in response to a
2504 // rejected media section, there is some cleanup logic that expects the
2505 // voice/ video channel to still be set. But in this method the voice/video
2506 // channel would have been destroyed by the SetRemoteDescription caller
2507 // above so the cleanup that relies on them fails to run. The RemoveSenders
2508 // calls should be moved to right before the DestroyChannel calls to fix
2509 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002510
Steve Antondcc3c022017-12-22 16:02:54 -08002511 // Find all audio rtp streams and create corresponding remote AudioTracks
2512 // and MediaStreams.
2513 if (audio_content) {
2514 if (audio_content->rejected) {
2515 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2516 } else {
2517 bool default_audio_track_needed =
2518 !remote_peer_supports_msid_ &&
2519 RtpTransceiverDirectionHasSend(audio_desc->direction());
2520 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2521 default_audio_track_needed, audio_desc->type(),
2522 new_streams);
2523 }
deadbeeffaac4972015-11-12 15:33:07 -08002524 }
deadbeefab9b2d12015-10-14 11:33:11 -07002525
Steve Antondcc3c022017-12-22 16:02:54 -08002526 // Find all video rtp streams and create corresponding remote VideoTracks
2527 // and MediaStreams.
2528 if (video_content) {
2529 if (video_content->rejected) {
2530 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2531 } else {
2532 bool default_video_track_needed =
2533 !remote_peer_supports_msid_ &&
2534 RtpTransceiverDirectionHasSend(video_desc->direction());
2535 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2536 default_video_track_needed, video_desc->type(),
2537 new_streams);
2538 }
deadbeeffaac4972015-11-12 15:33:07 -08002539 }
deadbeefab9b2d12015-10-14 11:33:11 -07002540
Steve Antondcc3c022017-12-22 16:02:54 -08002541 // Update the DataChannels with the information from the remote peer.
2542 if (data_desc) {
2543 if (rtc::starts_with(data_desc->protocol().data(),
2544 cricket::kMediaProtocolRtpPrefix)) {
2545 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2546 }
deadbeefab9b2d12015-10-14 11:33:11 -07002547 }
deadbeefab9b2d12015-10-14 11:33:11 -07002548
Steve Antondcc3c022017-12-22 16:02:54 -08002549 // Iterate new_streams and notify the observer about new MediaStreams.
2550 for (size_t i = 0; i < new_streams->count(); ++i) {
2551 MediaStreamInterface* new_stream = new_streams->at(i);
2552 stats_->AddStream(new_stream);
2553 observer_->OnAddStream(
2554 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2555 }
deadbeefab9b2d12015-10-14 11:33:11 -07002556
Steve Antondcc3c022017-12-22 16:02:54 -08002557 UpdateEndedRemoteMediaStreams();
2558 }
deadbeefab9b2d12015-10-14 11:33:11 -07002559
Steve Anton8a006912017-12-04 15:25:56 -08002560 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002561}
2562
Steve Antondcc3c022017-12-22 16:02:54 -08002563RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2564 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002565 const SessionDescriptionInterface& new_session,
2566 const SessionDescriptionInterface* old_local_description,
2567 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002568 RTC_DCHECK(IsUnifiedPlan());
2569
Steve Anton7464fca2018-01-19 11:10:37 -08002570 const cricket::ContentGroup* bundle_group = nullptr;
2571 if (new_session.GetType() == SdpType::kOffer) {
2572 auto bundle_group_or_error =
2573 GetEarlyBundleGroup(*new_session.description());
2574 if (!bundle_group_or_error.ok()) {
2575 return bundle_group_or_error.MoveError();
2576 }
2577 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002578 }
Steve Antondcc3c022017-12-22 16:02:54 -08002579
Steve Antondcc3c022017-12-22 16:02:54 -08002580 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002581 for (size_t i = 0; i < new_contents.size(); ++i) {
2582 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002583 cricket::MediaType media_type = new_content.media_description()->type();
2584 seen_mids_.insert(new_content.name);
2585 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2586 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002587 const cricket::ContentInfo* old_local_content = nullptr;
2588 if (old_local_description &&
2589 i < old_local_description->description()->contents().size()) {
2590 old_local_content =
2591 &old_local_description->description()->contents()[i];
2592 }
2593 const cricket::ContentInfo* old_remote_content = nullptr;
2594 if (old_remote_description &&
2595 i < old_remote_description->description()->contents().size()) {
2596 old_remote_content =
2597 &old_remote_description->description()->contents()[i];
2598 }
Steve Antondcc3c022017-12-22 16:02:54 -08002599 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002600 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2601 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002602 if (!transceiver_or_error.ok()) {
2603 return transceiver_or_error.MoveError();
2604 }
2605 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002606 RTCError error =
2607 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2608 if (!error.ok()) {
2609 return error;
2610 }
2611 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002612 if (GetDataMid() && new_content.name != *GetDataMid()) {
2613 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002614 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2615 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002616 continue;
2617 }
2618 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2619 if (!error.ok()) {
2620 return error;
2621 }
Steve Antondcc3c022017-12-22 16:02:54 -08002622 } else {
2623 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2624 "Unknown section type.");
2625 }
2626 }
2627
2628 return RTCError::OK();
2629}
2630
2631RTCError PeerConnection::UpdateTransceiverChannel(
2632 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2633 transceiver,
2634 const cricket::ContentInfo& content,
2635 const cricket::ContentGroup* bundle_group) {
2636 RTC_DCHECK(IsUnifiedPlan());
2637 RTC_DCHECK(transceiver);
2638 cricket::BaseChannel* channel = transceiver->internal()->channel();
2639 if (content.rejected) {
2640 if (channel) {
2641 transceiver->internal()->SetChannel(nullptr);
2642 DestroyBaseChannel(channel);
2643 }
2644 } else {
2645 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002646 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002647 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002648 } else {
Steve Anton69470252018-02-09 11:43:08 -08002649 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002650 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002651 }
2652 if (!channel) {
2653 LOG_AND_RETURN_ERROR(
2654 RTCErrorType::INTERNAL_ERROR,
2655 "Failed to create channel for mid=" + content.name);
2656 }
2657 transceiver->internal()->SetChannel(channel);
2658 }
2659 }
2660 return RTCError::OK();
2661}
2662
Steve Antonfa2260d2017-12-28 16:38:23 -08002663RTCError PeerConnection::UpdateDataChannel(
2664 cricket::ContentSource source,
2665 const cricket::ContentInfo& content,
2666 const cricket::ContentGroup* bundle_group) {
2667 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002668 // If data channels are disabled, ignore this media section. CreateAnswer
2669 // will take care of rejecting it.
2670 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002671 }
2672 if (content.rejected) {
2673 DestroyDataChannel();
2674 } else {
2675 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002676 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002677 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2678 "Failed to create data channel.");
2679 }
2680 }
2681 if (source == cricket::CS_REMOTE) {
2682 const MediaContentDescription* data_desc = content.media_description();
2683 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2684 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2685 }
2686 }
2687 }
2688 return RTCError::OK();
2689}
2690
Steve Antondcc3c022017-12-22 16:02:54 -08002691RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2692PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002693 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002694 size_t mline_index,
2695 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002696 const ContentInfo* old_local_content,
2697 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002698 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002699 // If this is an offer then the m= section might be recycled. If the m=
2700 // section is being recycled (defined as: rejected in the current local or
2701 // remote description and not rejected in new description), dissociate the
2702 // currently associated RtpTransceiver by setting its mid property to null,
2703 // and discard the mapping between the transceiver and its m= section index.
2704 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2705 old_remote_content)) {
2706 // We want to dissociate the transceiver that has the rejected mid.
2707 const std::string& old_mid =
2708 (old_local_content && old_local_content->rejected)
2709 ? old_local_content->name
2710 : old_remote_content->name;
2711 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002712 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002713 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2714 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-22 16:02:54 -08002715 old_transceiver->internal()->set_mid(rtc::nullopt);
2716 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2717 }
2718 }
2719 const MediaContentDescription* media_desc = content.media_description();
2720 auto transceiver = GetAssociatedTransceiver(content.name);
2721 if (source == cricket::CS_LOCAL) {
2722 // Find the RtpTransceiver that corresponds to this m= section, using the
2723 // mapping between transceivers and m= section indices established when
2724 // creating the offer.
2725 if (!transceiver) {
2726 transceiver = GetTransceiverByMLineIndex(mline_index);
2727 }
2728 if (!transceiver) {
2729 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2730 "Unknown transceiver");
2731 }
2732 } else {
2733 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2734 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2735 // of the same type...
2736 if (!transceiver &&
2737 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2738 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2739 }
2740 // If no RtpTransceiver was found in the previous step, create one with a
2741 // recvonly direction.
2742 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002743 RTC_LOG(LS_INFO) << "Adding "
2744 << cricket::MediaTypeToString(media_desc->type())
2745 << " transceiver for MID=" << content.name
2746 << " at i=" << mline_index
2747 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002748 auto sender =
2749 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002750 std::string receiver_id;
2751 if (!media_desc->streams().empty()) {
2752 receiver_id = media_desc->streams()[0].id;
2753 } else {
2754 receiver_id = rtc::CreateRandomUuid();
2755 }
2756 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002757 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002758 transceiver->internal()->set_direction(
2759 RtpTransceiverDirection::kRecvOnly);
2760 }
2761 }
2762 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002763 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002764 LOG_AND_RETURN_ERROR(
2765 RTCErrorType::INVALID_PARAMETER,
2766 "Transceiver type does not match media description type.");
2767 }
2768 // Associate the found or created RtpTransceiver with the m= section by
2769 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2770 // section, and establish a mapping between the transceiver and the index of
2771 // the m= section.
2772 transceiver->internal()->set_mid(content.name);
2773 transceiver->internal()->set_mline_index(mline_index);
2774 return std::move(transceiver);
2775}
2776
2777rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2778PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2779 RTC_DCHECK(IsUnifiedPlan());
2780 for (auto transceiver : transceivers_) {
2781 if (transceiver->mid() == mid) {
2782 return transceiver;
2783 }
2784 }
2785 return nullptr;
2786}
2787
2788rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2789PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2790 RTC_DCHECK(IsUnifiedPlan());
2791 for (auto transceiver : transceivers_) {
2792 if (transceiver->internal()->mline_index() == mline_index) {
2793 return transceiver;
2794 }
2795 }
2796 return nullptr;
2797}
2798
2799rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2800PeerConnection::FindAvailableTransceiverToReceive(
2801 cricket::MediaType media_type) const {
2802 RTC_DCHECK(IsUnifiedPlan());
2803 // From JSEP section 5.10 (Applying a Remote Description):
2804 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2805 // the same type that were added to the PeerConnection by addTrack and are not
2806 // associated with any m= section and are not stopped, find the first such
2807 // RtpTransceiver.
2808 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002809 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002810 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2811 !transceiver->stopped()) {
2812 return transceiver;
2813 }
2814 }
2815 return nullptr;
2816}
2817
Steve Antoned10bd92017-12-05 10:52:59 -08002818const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2819 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2820 transceiver,
2821 const SessionDescriptionInterface* sdesc) const {
2822 RTC_DCHECK(transceiver);
2823 RTC_DCHECK(sdesc);
2824 if (IsUnifiedPlan()) {
2825 if (!transceiver->internal()->mid()) {
2826 // This transceiver is not associated with a media section yet.
2827 return nullptr;
2828 }
2829 return sdesc->description()->GetContentByName(
2830 *transceiver->internal()->mid());
2831 } else {
2832 // Plan B only allows at most one audio and one video section, so use the
2833 // first media section of that type.
2834 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002835 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002836 }
2837}
2838
deadbeef46c73892016-11-16 19:42:04 -08002839PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2840 return configuration_;
2841}
2842
deadbeef293e9262017-01-11 12:28:30 -08002843bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2844 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002845 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002846
Steve Antonc79268f2018-04-24 09:54:10 -07002847 if (IsClosed()) {
2848 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2849 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2850 }
2851
Qingsi Wanga2d60672018-04-11 16:57:45 -07002852 // According to JSEP, after setLocalDescription, changing the candidate pool
2853 // size is not allowed, and changing the set of ICE servers will not result
2854 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002855 if (local_description() && configuration.ice_candidate_pool_size !=
2856 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002857 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2858 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002859 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002860 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002861
deadbeef293e9262017-01-11 12:28:30 -08002862 // The simplest (and most future-compatible) way to tell if the config was
2863 // modified in an invalid way is to copy each property we do support
2864 // modifying, then use operator==. There are far more properties we don't
2865 // support modifying than those we do, and more could be added.
2866 RTCConfiguration modified_config = configuration_;
2867 modified_config.servers = configuration.servers;
2868 modified_config.type = configuration.type;
2869 modified_config.ice_candidate_pool_size =
2870 configuration.ice_candidate_pool_size;
2871 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002872 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002873 modified_config.ice_check_interval_strong_connectivity =
2874 configuration.ice_check_interval_strong_connectivity;
2875 modified_config.ice_check_interval_weak_connectivity =
2876 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002877 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2878 modified_config.ice_unwritable_min_checks =
2879 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002880 modified_config.stun_candidate_keepalive_interval =
2881 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002882 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002883 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002884 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002885 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002886 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2887 }
2888
Steve Anton038834f2017-07-14 15:59:59 -07002889 // Validate the modified configuration.
2890 RTCError validate_error = ValidateConfiguration(modified_config);
2891 if (!validate_error.ok()) {
2892 return SafeSetError(std::move(validate_error), error);
2893 }
2894
deadbeef293e9262017-01-11 12:28:30 -08002895 // Note that this isn't possible through chromium, since it's an unsigned
2896 // short in WebIDL.
2897 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002898 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002899 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2900 }
2901
2902 // Parse ICE servers before hopping to network thread.
2903 cricket::ServerAddresses stun_servers;
2904 std::vector<cricket::RelayServerConfig> turn_servers;
2905 RTCErrorType parse_error =
2906 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2907 if (parse_error != RTCErrorType::NONE) {
2908 return SafeSetError(parse_error, error);
2909 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002910 // Note if STUN or TURN servers were supplied.
2911 if (!stun_servers.empty()) {
2912 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2913 }
2914 if (!turn_servers.empty()) {
2915 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2916 }
deadbeef293e9262017-01-11 12:28:30 -08002917
2918 // In theory this shouldn't fail.
2919 if (!network_thread()->Invoke<bool>(
2920 RTC_FROM_HERE,
2921 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2922 stun_servers, turn_servers, modified_config.type,
2923 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002924 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002925 modified_config.turn_customizer,
2926 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002927 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002928 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2929 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002930
deadbeefd1a38b52016-12-10 13:15:33 -08002931 // As described in JSEP, calling setConfiguration with new ICE servers or
2932 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2933 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002934 if (modified_config.servers != configuration_.servers ||
2935 modified_config.type != configuration_.type ||
2936 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002937 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002938 }
skvladd1f5fda2017-02-03 16:54:05 -08002939
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002940 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002941
deadbeef293e9262017-01-11 12:28:30 -08002942 configuration_ = modified_config;
2943 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002944}
2945
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002946bool PeerConnection::AddIceCandidate(
2947 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002948 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002949 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002950 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002951 return false;
2952 }
Steve Antond25da372017-11-06 14:50:29 -08002953
2954 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002955 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002956 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002957 return false;
2958 }
2959
2960 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002961 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002962 return false;
2963 }
2964
2965 bool valid = false;
2966 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2967 if (!valid) {
2968 return false;
2969 }
2970
2971 // Add this candidate to the remote session description.
2972 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002973 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002974 return false;
2975 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002976 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002977
2978 if (ready) {
2979 return UseCandidate(ice_candidate);
2980 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002981 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002982 return true;
2983 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002984}
2985
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002986bool PeerConnection::RemoveIceCandidates(
2987 const std::vector<cricket::Candidate>& candidates) {
2988 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002989 if (IsClosed()) {
2990 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2991 return false;
2992 }
2993
Steve Antond25da372017-11-06 14:50:29 -08002994 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002995 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2996 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002997 return false;
2998 }
2999
3000 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003001 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003002 return false;
3003 }
3004
3005 size_t number_removed =
3006 mutable_remote_description()->RemoveCandidates(candidates);
3007 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003008 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003009 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003010 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003011 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003012 }
3013
3014 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003015 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3016 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003017 RTC_LOG(LS_ERROR)
3018 << "RemoveIceCandidates: Error when removing remote candidates: "
3019 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003020 }
3021 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003022}
3023
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003024void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003025 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003026 network_thread()->Invoke<void>(
3027 RTC_FROM_HERE,
3028 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3029 // Send information about IPv4/IPv6 status.
3030 if (uma_observer_) {
3031 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3032 uma_observer_->IncrementEnumCounter(
3033 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3034 kPeerConnectionAddressFamilyCounter_Max);
3035 } else {
3036 uma_observer_->IncrementEnumCounter(
3037 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3038 kPeerConnectionAddressFamilyCounter_Max);
3039 }
3040 }
3041}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003042
Qingsi Wanga2d60672018-04-11 16:57:45 -07003043void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3044 RTC_DCHECK(network_thread()->IsCurrent());
3045 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003046 if (transport_controller_) {
3047 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003048 }
3049
3050 for (auto transceiver : transceivers_) {
3051 auto* channel = transceiver->internal()->channel();
3052 if (channel) {
3053 channel->SetMetricsObserver(uma_observer_);
3054 }
3055 }
3056
deadbeef293e9262017-01-11 12:28:30 -08003057 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003058 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003059 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003060}
3061
Niels Möller0c4f7be2018-05-07 14:01:37 +02003062RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003063 if (!worker_thread()->IsCurrent()) {
3064 return worker_thread()->Invoke<RTCError>(
Niels Möller0c4f7be2018-05-07 14:01:37 +02003065 RTC_FROM_HERE, [&](){ return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003066 }
3067
Niels Möller0c4f7be2018-05-07 14:01:37 +02003068 const bool has_min = bitrate.min_bitrate_bps.has_value();
3069 const bool has_start = bitrate.start_bitrate_bps.has_value();
3070 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003071 if (has_min && *bitrate.min_bitrate_bps < 0) {
3072 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3073 "min_bitrate_bps <= 0");
3074 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003075 if (has_start) {
3076 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003078 "start_bitrate_bps < min_bitrate_bps");
3079 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3081 "curent_bitrate_bps < 0");
3082 }
3083 }
3084 if (has_max) {
Niels Möller0c4f7be2018-05-07 14:01:37 +02003085 if (has_start &&
3086 *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003087 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003088 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003089 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3090 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3091 "max_bitrate_bps < min_bitrate_bps");
3092 } else if (*bitrate.max_bitrate_bps < 0) {
3093 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3094 "max_bitrate_bps < 0");
3095 }
3096 }
3097
zstein4b979802017-06-02 14:37:37 -07003098 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003099 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003100
3101 return RTCError::OK();
3102}
3103
Alex Narest78609d52017-10-20 10:37:47 +02003104void PeerConnection::SetBitrateAllocationStrategy(
3105 std::unique_ptr<rtc::BitrateAllocationStrategy>
3106 bitrate_allocation_strategy) {
3107 rtc::Thread* worker_thread = factory_->worker_thread();
3108 if (!worker_thread->IsCurrent()) {
3109 rtc::BitrateAllocationStrategy* strategy_raw =
3110 bitrate_allocation_strategy.release();
3111 auto functor = [this, strategy_raw]() {
3112 call_->SetBitrateAllocationStrategy(
3113 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3114 };
3115 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3116 return;
3117 }
3118 RTC_DCHECK(call_.get());
3119 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3120}
3121
henrika5f6bf242017-11-01 11:06:56 +01003122void PeerConnection::SetAudioPlayout(bool playout) {
3123 if (!worker_thread()->IsCurrent()) {
3124 worker_thread()->Invoke<void>(
3125 RTC_FROM_HERE,
3126 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3127 return;
3128 }
3129 auto audio_state =
3130 factory_->channel_manager()->media_engine()->GetAudioState();
3131 audio_state->SetPlayout(playout);
3132}
3133
3134void PeerConnection::SetAudioRecording(bool recording) {
3135 if (!worker_thread()->IsCurrent()) {
3136 worker_thread()->Invoke<void>(
3137 RTC_FROM_HERE,
3138 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3139 return;
3140 }
3141 auto audio_state =
3142 factory_->channel_manager()->media_engine()->GetAudioState();
3143 audio_state->SetRecording(recording);
3144}
3145
Steve Anton8c0f7a72017-10-03 10:03:10 -07003146std::unique_ptr<rtc::SSLCertificate>
3147PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003148 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3149 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003150 return nullptr;
3151 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003152 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003153}
3154
Zhi Huang70b820f2018-01-27 14:16:15 -08003155std::unique_ptr<rtc::SSLCertChain>
3156PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003157 auto audio_transceiver = GetFirstAudioTransceiver();
3158 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003159 return nullptr;
3160 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003161 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003162 audio_transceiver->internal()->channel()->transport_name());
3163}
3164
3165rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3166PeerConnection::GetFirstAudioTransceiver() const {
3167 for (auto transceiver : transceivers_) {
3168 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3169 return transceiver;
3170 }
3171 }
3172 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003173}
3174
ivoc14d5dbe2016-07-04 07:06:55 -07003175bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3176 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003177 // TODO(eladalon): It would be better to not allow negative values into PC.
3178 const size_t max_size = (max_size_bytes < 0)
3179 ? RtcEventLog::kUnlimitedOutput
3180 : rtc::saturated_cast<size_t>(max_size_bytes);
3181 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003182 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3183 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003184}
3185
Bjorn Tereliusde939432017-11-20 17:38:14 +01003186bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3187 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003188 // TODO(eladalon): In C++14, this can be done with a lambda.
3189 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003190 bool operator()() {
3191 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3192 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003193 PeerConnection* const pc;
3194 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003195 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003196 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003197 return worker_thread()->Invoke<bool>(
3198 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003199}
3200
3201void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003202 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003203 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3204}
3205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003207 return pending_local_description_ ? pending_local_description_.get()
3208 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003209}
3210
3211const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003212 return pending_remote_description_ ? pending_remote_description_.get()
3213 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003214}
3215
deadbeeffe4a8a42016-12-20 17:56:17 -08003216const SessionDescriptionInterface* PeerConnection::current_local_description()
3217 const {
Steve Anton75737c02017-11-06 10:37:17 -08003218 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003219}
3220
3221const SessionDescriptionInterface* PeerConnection::current_remote_description()
3222 const {
Steve Anton75737c02017-11-06 10:37:17 -08003223 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003224}
3225
3226const SessionDescriptionInterface* PeerConnection::pending_local_description()
3227 const {
Steve Anton75737c02017-11-06 10:37:17 -08003228 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003229}
3230
3231const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3232 const {
Steve Anton75737c02017-11-06 10:37:17 -08003233 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003234}
3235
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003236void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003237 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003238 // Update stats here so that we have the most recent stats for tracks and
3239 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003240 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003241
Steve Anton75737c02017-11-06 10:37:17 -08003242 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003243 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003244
Steve Anton8af21862017-12-15 11:20:13 -08003245 for (auto transceiver : transceivers_) {
3246 transceiver->Stop();
3247 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003248
3249 // Ensure that all asynchronous stats requests are completed before destroying
3250 // the transport controller below.
3251 if (stats_collector_) {
3252 stats_collector_->WaitForPendingRequest();
3253 }
3254
3255 // Don't destroy BaseChannels until after stats has been cleaned up so that
3256 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003257 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003258
Qingsi Wang93a84392018-01-30 17:13:09 -08003259 // The event log is used in the transport controller, which must be outlived
3260 // by the former. CreateOffer by the peer connection is implemented
3261 // asynchronously and if the peer connection is closed without resetting the
3262 // WebRTC session description factory, the session description factory would
3263 // call the transport controller.
3264 webrtc_session_desc_factory_.reset();
3265 transport_controller_.reset();
3266
deadbeef42a42632017-03-10 15:18:00 -08003267 network_thread()->Invoke<void>(
3268 RTC_FROM_HERE,
3269 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3270 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003271
Steve Anton978b8762017-09-29 12:15:02 -07003272 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003273 call_.reset();
3274 // The event log must outlive call (and any other object that uses it).
3275 event_log_.reset();
3276 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003277 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278}
3279
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003280void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003281 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003282 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3283 SetSessionDescriptionMsg* param =
3284 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3285 param->observer->OnSuccess();
3286 delete param;
3287 break;
3288 }
3289 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3290 SetSessionDescriptionMsg* param =
3291 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003292 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003293 delete param;
3294 break;
3295 }
deadbeefab9b2d12015-10-14 11:33:11 -07003296 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3297 CreateSessionDescriptionMsg* param =
3298 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003299 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003300 delete param;
3301 break;
3302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 case MSG_GETSTATS: {
3304 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003305 StatsReports reports;
3306 stats_->GetStats(param->track, &reports);
3307 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003308 delete param;
3309 break;
3310 }
deadbeefbd292462015-12-14 18:15:29 -08003311 case MSG_FREE_DATACHANNELS: {
3312 sctp_data_channels_to_free_.clear();
3313 break;
3314 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003316 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 break;
3318 }
3319}
3320
Steve Antonafb0bb72018-02-20 11:35:37 -08003321cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3322 RTC_DCHECK(!IsUnifiedPlan());
3323 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3324 GetAudioTransceiver()->internal()->channel());
3325 if (voice_channel) {
3326 return voice_channel->media_channel();
3327 } else {
3328 return nullptr;
3329 }
3330}
3331
3332cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3333 RTC_DCHECK(!IsUnifiedPlan());
3334 auto* video_channel = static_cast<cricket::VideoChannel*>(
3335 GetVideoTransceiver()->internal()->channel());
3336 if (video_channel) {
3337 return video_channel->media_channel();
3338 } else {
3339 return nullptr;
3340 }
3341}
3342
Steve Anton4171afb2017-11-20 10:20:22 -08003343void PeerConnection::CreateAudioReceiver(
3344 MediaStreamInterface* stream,
3345 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003346 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3347 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003348 auto* audio_receiver = new AudioRtpReceiver(
3349 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003350 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003351 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3352 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3353 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003354 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003355 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003356 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
Steve Anton4171afb2017-11-20 10:20:22 -08003359void PeerConnection::CreateVideoReceiver(
3360 MediaStreamInterface* stream,
3361 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003362 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3363 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003364 auto* video_receiver = new VideoRtpReceiver(
3365 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003366 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003367 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3368 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3369 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003370 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003371 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003372 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003373}
3374
deadbeef70ab1a12015-09-28 16:53:55 -07003375// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3376// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003377rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003378 const RtpSenderInfo& remote_sender_info) {
3379 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3380 if (!receiver) {
3381 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3382 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003383 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003384 }
Steve Anton4171afb2017-11-20 10:20:22 -08003385 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3386 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3387 } else {
3388 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3389 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003390 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391}
3392
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003393void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3394 MediaStreamInterface* stream) {
3395 RTC_DCHECK(!IsClosed());
3396 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003397 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003398 // We already have a sender for this track, so just change the stream_id
3399 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003400 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003401 return;
3402 }
3403
3404 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003405 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003406 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003407 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003408 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003409 // If the sender has already been configured in SDP, we call SetSsrc,
3410 // which will connect the sender to the underlying transport. This can
3411 // occur if a local session description that contains the ID of the sender
3412 // is set before AddStream is called. It can also occur if the local
3413 // session description is not changed and RemoveStream is called, and
3414 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003415 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003416 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003417 if (sender_info) {
3418 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003419 }
3420}
3421
3422// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3423// indefinitely, when we have unified plan SDP.
3424void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3425 MediaStreamInterface* stream) {
3426 RTC_DCHECK(!IsClosed());
3427 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003428 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003429 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3430 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003431 return;
3432 }
Steve Anton4171afb2017-11-20 10:20:22 -08003433 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003434}
3435
3436void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3437 MediaStreamInterface* stream) {
3438 RTC_DCHECK(!IsClosed());
3439 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003440 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003441 // We already have a sender for this track, so just change the stream_id
3442 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003443 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003444 return;
3445 }
3446
3447 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003448 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003449 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003450 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003451 GetVideoTransceiver()->internal()->AddSender(new_sender);
3452 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003453 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003454 if (sender_info) {
3455 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003456 }
3457}
3458
3459void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3460 MediaStreamInterface* stream) {
3461 RTC_DCHECK(!IsClosed());
3462 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003463 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003464 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3465 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003466 return;
3467 }
Steve Anton4171afb2017-11-20 10:20:22 -08003468 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003469}
3470
Steve Antonba818672017-11-06 10:21:57 -08003471void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003472 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003473 if (ice_connection_state_ == new_state) {
3474 return;
3475 }
3476
deadbeefcbecd352015-09-23 11:50:27 -07003477 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003478 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003479 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003480 return;
3481 }
Steve Antonba818672017-11-06 10:21:57 -08003482
Mirko Bonadei675513b2017-11-09 11:09:25 +01003483 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3484 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003485 RTC_DCHECK(ice_connection_state_ !=
3486 PeerConnectionInterface::kIceConnectionClosed);
3487
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003488 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003489 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003490}
3491
3492void PeerConnection::OnIceGatheringChange(
3493 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003494 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495 if (IsClosed()) {
3496 return;
3497 }
3498 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003499 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003500}
3501
jbauch81bf7b02017-03-25 08:31:12 -07003502void PeerConnection::OnIceCandidate(
3503 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003504 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003505 if (IsClosed()) {
3506 return;
3507 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003508 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003509 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003510}
3511
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003512void PeerConnection::OnIceCandidatesRemoved(
3513 const std::vector<cricket::Candidate>& candidates) {
3514 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003515 if (IsClosed()) {
3516 return;
3517 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003518 observer_->OnIceCandidatesRemoved(candidates);
3519}
3520
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003521void PeerConnection::ChangeSignalingState(
3522 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003523 RTC_DCHECK(signaling_thread()->IsCurrent());
3524 if (signaling_state_ == signaling_state) {
3525 return;
3526 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003527 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3528 << GetSignalingStateString(signaling_state_)
3529 << " New state: "
3530 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003531 signaling_state_ = signaling_state;
3532 if (signaling_state == kClosed) {
3533 ice_connection_state_ = kIceConnectionClosed;
3534 observer_->OnIceConnectionChange(ice_connection_state_);
3535 if (ice_gathering_state_ != kIceGatheringComplete) {
3536 ice_gathering_state_ = kIceGatheringComplete;
3537 observer_->OnIceGatheringChange(ice_gathering_state_);
3538 }
3539 }
3540 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003541}
3542
deadbeefeb459812015-12-15 19:24:43 -08003543void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3544 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003545 if (IsClosed()) {
3546 return;
3547 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003548 AddAudioTrack(track, stream);
3549 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003550}
3551
deadbeefeb459812015-12-15 19:24:43 -08003552void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3553 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003554 if (IsClosed()) {
3555 return;
3556 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003557 RemoveAudioTrack(track, stream);
3558 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003559}
3560
3561void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3562 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003563 if (IsClosed()) {
3564 return;
3565 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003566 AddVideoTrack(track, stream);
3567 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003568}
3569
3570void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3571 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003572 if (IsClosed()) {
3573 return;
3574 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003575 RemoveVideoTrack(track, stream);
3576 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003577}
3578
Henrik Boström31638672017-11-23 17:48:32 +01003579void PeerConnection::PostSetSessionDescriptionSuccess(
3580 SetSessionDescriptionObserver* observer) {
3581 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3582 signaling_thread()->Post(RTC_FROM_HERE, this,
3583 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3584}
3585
deadbeefab9b2d12015-10-14 11:33:11 -07003586void PeerConnection::PostSetSessionDescriptionFailure(
3587 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003588 RTCError&& error) {
3589 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003590 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003591 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003592 signaling_thread()->Post(RTC_FROM_HERE, this,
3593 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003594}
3595
3596void PeerConnection::PostCreateSessionDescriptionFailure(
3597 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003598 RTCError error) {
3599 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003600 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003601 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003602 signaling_thread()->Post(RTC_FROM_HERE, this,
3603 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003604}
3605
zhihuang1c378ed2017-08-17 14:10:50 -07003606void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003607 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003608 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003609 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003610
Steve Antondcc3c022017-12-22 16:02:54 -08003611 if (IsUnifiedPlan()) {
3612 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3613 } else {
3614 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3615 }
3616
Steve Antonfa2260d2017-12-28 16:38:23 -08003617 // Intentionally unset the data channel type for RTP data channel with the
3618 // second condition. Otherwise the RTP data channels would be successfully
3619 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3620 // when building with chromium. We want to leave RTP data channels broken, so
3621 // people won't try to use them.
3622 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3623 session_options->data_channel_type = data_channel_type();
3624 }
3625
Steve Antondcc3c022017-12-22 16:02:54 -08003626 // Apply ICE restart flag and renomination flag.
3627 for (auto& options : session_options->media_description_options) {
3628 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3629 options.transport_options.enable_ice_renomination =
3630 configuration_.enable_ice_renomination;
3631 }
3632
3633 session_options->rtcp_cname = rtcp_cname_;
3634 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003635 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003636}
3637
3638void PeerConnection::GetOptionsForPlanBOffer(
3639 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3640 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003641 // Figure out transceiver directional preferences.
3642 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3643 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3644
3645 // By default, generate sendrecv/recvonly m= sections.
3646 bool recv_audio = true;
3647 bool recv_video = true;
3648
3649 // By default, only offer a new m= section if we have media to send with it.
3650 bool offer_new_audio_description = send_audio;
3651 bool offer_new_video_description = send_video;
3652 bool offer_new_data_description = HasDataChannels();
3653
3654 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003655 if (offer_answer_options.offer_to_receive_audio !=
3656 RTCOfferAnswerOptions::kUndefined) {
3657 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003658 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003659 offer_new_audio_description ||
3660 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003661 }
Steve Antondcc3c022017-12-22 16:02:54 -08003662 if (offer_answer_options.offer_to_receive_video !=
3663 RTCOfferAnswerOptions::kUndefined) {
3664 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003665 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003666 offer_new_video_description ||
3667 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003668 }
3669
3670 rtc::Optional<size_t> audio_index;
3671 rtc::Optional<size_t> video_index;
3672 rtc::Optional<size_t> data_index;
3673 // If a current description exists, generate m= sections in the same order,
3674 // using the first audio/video/data section that appears and rejecting
3675 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003676 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003677 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003678 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003679 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3680 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3681 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003682 }
3683
zhihuang1c378ed2017-08-17 14:10:50 -07003684 // Add audio/video/data m= sections to the end if needed.
3685 if (!audio_index && offer_new_audio_description) {
3686 session_options->media_description_options.push_back(
3687 cricket::MediaDescriptionOptions(
3688 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003689 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3690 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003691 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003692 }
zhihuang1c378ed2017-08-17 14:10:50 -07003693 if (!video_index && offer_new_video_description) {
3694 session_options->media_description_options.push_back(
3695 cricket::MediaDescriptionOptions(
3696 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003697 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3698 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003699 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003700 }
zhihuang1c378ed2017-08-17 14:10:50 -07003701 if (!data_index && offer_new_data_description) {
3702 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003703 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003704 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003705 }
3706
3707 cricket::MediaDescriptionOptions* audio_media_description_options =
3708 !audio_index ? nullptr
3709 : &session_options->media_description_options[*audio_index];
3710 cricket::MediaDescriptionOptions* video_media_description_options =
3711 !video_index ? nullptr
3712 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003713
Steve Anton4171afb2017-11-20 10:20:22 -08003714 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003715 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003716}
3717
3718// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3719// and return a reference to it.
3720// Generated MIDs should be no more than 3 bytes long to take up less space in
3721// the RTP packet.
3722static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3723 RTC_DCHECK(used_mids);
3724 // We're boring: just generate MIDs 0, 1, 2, ...
3725 size_t i = 0;
3726 std::set<std::string>::iterator it;
3727 bool inserted;
3728 do {
3729 std::string mid = rtc::ToString(i++);
3730 auto insert_result = used_mids->insert(mid);
3731 it = insert_result.first;
3732 inserted = insert_result.second;
3733 } while (!inserted);
3734 return *it;
3735}
3736
3737static cricket::MediaDescriptionOptions
3738GetMediaDescriptionOptionsForTransceiver(
3739 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3740 transceiver,
3741 const std::string& mid) {
3742 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003743 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003744 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003745 // This behavior is specified in JSEP. The gist is that:
3746 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3747 // sendrecv.
3748 // 2. If the MSID is included, then it must be included in any subsequent
3749 // offer/answer exactly the same until the RtpTransceiver is stopped.
3750 if (!transceiver->stopped() &&
3751 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3752 transceiver->internal()->has_ever_been_used_to_send())) {
3753 cricket::SenderOptions sender_options;
3754 sender_options.track_id = transceiver->sender()->id();
3755 sender_options.stream_ids = transceiver->sender()->stream_ids();
3756 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3757 // set in the RTP parameters when the transceiver was added.
3758 sender_options.num_sim_layers = 1;
3759 media_description_options.sender_options.push_back(sender_options);
3760 }
Steve Antondcc3c022017-12-22 16:02:54 -08003761 return media_description_options;
3762}
3763
3764void PeerConnection::GetOptionsForUnifiedPlanOffer(
3765 const RTCOfferAnswerOptions& offer_answer_options,
3766 cricket::MediaSessionOptions* session_options) {
3767 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3768 // Offers) and 5.2.2 (Subsequent Offers).
3769 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3770 const ContentInfos& local_contents =
3771 (local_description() ? local_description()->description()->contents()
3772 : ContentInfos());
3773 const ContentInfos& remote_contents =
3774 (remote_description() ? remote_description()->description()->contents()
3775 : ContentInfos());
3776 // The mline indices that can be recycled. New transceivers should reuse these
3777 // slots first.
3778 std::queue<size_t> recycleable_mline_indices;
3779 // Track the MIDs used in previous offer/answer exchanges and the current
3780 // offer so that new, unique MIDs are generated.
3781 std::set<std::string> used_mids = seen_mids_;
3782 // First, go through each media section that exists in either the local or
3783 // remote description and generate a media section in this offer for the
3784 // associated transceiver. If a media section can be recycled, generate a
3785 // default, rejected media section here that can be later overwritten.
3786 for (size_t i = 0;
3787 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3788 // Either |local_content| or |remote_content| is non-null.
3789 const ContentInfo* local_content =
3790 (i < local_contents.size() ? &local_contents[i] : nullptr);
3791 const ContentInfo* remote_content =
3792 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3793 bool had_been_rejected = (local_content && local_content->rejected) ||
3794 (remote_content && remote_content->rejected);
3795 const std::string& mid =
3796 (local_content ? local_content->name : remote_content->name);
3797 cricket::MediaType media_type =
3798 (local_content ? local_content->media_description()->type()
3799 : remote_content->media_description()->type());
3800 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3801 media_type == cricket::MEDIA_TYPE_VIDEO) {
3802 auto transceiver = GetAssociatedTransceiver(mid);
3803 RTC_CHECK(transceiver);
3804 // A media section is considered eligible for recycling if it is marked as
3805 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003806 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003807 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003808 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3809 RtpTransceiverDirection::kInactive,
3810 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003811 recycleable_mline_indices.push(i);
3812 } else {
3813 session_options->media_description_options.push_back(
3814 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3815 // CreateOffer shouldn't really cause any state changes in
3816 // PeerConnection, but we need a way to match new transceivers to new
3817 // media sections in SetLocalDescription and JSEP specifies this is done
3818 // by recording the index of the media section generated for the
3819 // transceiver in the offer.
3820 transceiver->internal()->set_mline_index(i);
3821 }
3822 } else {
3823 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003824 RTC_CHECK(GetDataMid());
3825 if (had_been_rejected || mid != *GetDataMid()) {
3826 session_options->media_description_options.push_back(
3827 GetMediaDescriptionOptionsForRejectedData(mid));
3828 } else {
3829 session_options->media_description_options.push_back(
3830 GetMediaDescriptionOptionsForActiveData(mid));
3831 }
Steve Antondcc3c022017-12-22 16:02:54 -08003832 }
3833 }
3834 // Next, look for transceivers that are newly added (that is, are not stopped
3835 // and not associated). Reuse media sections marked as recyclable first,
3836 // otherwise append to the end of the offer. New media sections should be
3837 // added in the order they were added to the PeerConnection.
3838 for (auto transceiver : transceivers_) {
3839 if (transceiver->mid() || transceiver->stopped()) {
3840 continue;
3841 }
3842 size_t mline_index;
3843 if (!recycleable_mline_indices.empty()) {
3844 mline_index = recycleable_mline_indices.front();
3845 recycleable_mline_indices.pop();
3846 session_options->media_description_options[mline_index] =
3847 GetMediaDescriptionOptionsForTransceiver(transceiver,
3848 AllocateMid(&used_mids));
3849 } else {
3850 mline_index = session_options->media_description_options.size();
3851 session_options->media_description_options.push_back(
3852 GetMediaDescriptionOptionsForTransceiver(transceiver,
3853 AllocateMid(&used_mids)));
3854 }
3855 // See comment above for why CreateOffer changes the transceiver's state.
3856 transceiver->internal()->set_mline_index(mline_index);
3857 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003858 // Lastly, add a m-section if we have local data channels and an m section
3859 // does not already exist.
3860 if (!GetDataMid() && HasDataChannels()) {
3861 session_options->media_description_options.push_back(
3862 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3863 }
Steve Antondcc3c022017-12-22 16:02:54 -08003864}
3865
3866void PeerConnection::GetOptionsForAnswer(
3867 const RTCOfferAnswerOptions& offer_answer_options,
3868 cricket::MediaSessionOptions* session_options) {
3869 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3870
3871 if (IsUnifiedPlan()) {
3872 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3873 } else {
3874 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3875 }
3876
Steve Antonfa2260d2017-12-28 16:38:23 -08003877 // Intentionally unset the data channel type for RTP data channel. Otherwise
3878 // the RTP data channels would be successfully negotiated by default and the
3879 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3880 // We want to leave RTP data channels broken, so people won't try to use them.
3881 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3882 session_options->data_channel_type = data_channel_type();
3883 }
3884
Steve Antondcc3c022017-12-22 16:02:54 -08003885 // Apply ICE renomination flag.
3886 for (auto& options : session_options->media_description_options) {
3887 options.transport_options.enable_ice_renomination =
3888 configuration_.enable_ice_renomination;
3889 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003890
3891 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003892 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003893 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003894}
3895
Steve Antondcc3c022017-12-22 16:02:54 -08003896void PeerConnection::GetOptionsForPlanBAnswer(
3897 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003898 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003899 // Figure out transceiver directional preferences.
3900 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3901 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3902
3903 // By default, generate sendrecv/recvonly m= sections. The direction is also
3904 // restricted by the direction in the offer.
3905 bool recv_audio = true;
3906 bool recv_video = true;
3907
3908 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003909 if (offer_answer_options.offer_to_receive_audio !=
3910 RTCOfferAnswerOptions::kUndefined) {
3911 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003912 }
Steve Antondcc3c022017-12-22 16:02:54 -08003913 if (offer_answer_options.offer_to_receive_video !=
3914 RTCOfferAnswerOptions::kUndefined) {
3915 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003916 }
3917
3918 rtc::Optional<size_t> audio_index;
3919 rtc::Optional<size_t> video_index;
3920 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003921
3922 // Generate m= sections that match those in the offer.
3923 // Note that mediasession.cc will handle intersection our preferred
3924 // direction with the offered direction.
3925 GenerateMediaDescriptionOptions(
3926 remote_description(),
3927 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3928 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3929 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003930
3931 cricket::MediaDescriptionOptions* audio_media_description_options =
3932 !audio_index ? nullptr
3933 : &session_options->media_description_options[*audio_index];
3934 cricket::MediaDescriptionOptions* video_media_description_options =
3935 !video_index ? nullptr
3936 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003937
Steve Anton4171afb2017-11-20 10:20:22 -08003938 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003939 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003940}
zhihuangaf388472016-11-02 16:49:48 -07003941
Steve Antondcc3c022017-12-22 16:02:54 -08003942void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3943 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3944 cricket::MediaSessionOptions* session_options) {
3945 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3946 // Answers) and 5.3.2 (Subsequent Answers).
3947 RTC_DCHECK(remote_description());
3948 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3949 for (const ContentInfo& content :
3950 remote_description()->description()->contents()) {
3951 cricket::MediaType media_type = content.media_description()->type();
3952 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3953 media_type == cricket::MEDIA_TYPE_VIDEO) {
3954 auto transceiver = GetAssociatedTransceiver(content.name);
3955 RTC_CHECK(transceiver);
3956 session_options->media_description_options.push_back(
3957 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3958 } else {
3959 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003960 // Reject all data sections if data channels are disabled.
3961 // Reject a data section if it has already been rejected.
3962 // Reject all data sections except for the first one.
3963 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3964 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003965 session_options->media_description_options.push_back(
3966 GetMediaDescriptionOptionsForRejectedData(content.name));
3967 } else {
3968 session_options->media_description_options.push_back(
3969 GetMediaDescriptionOptionsForActiveData(content.name));
3970 }
Steve Antondcc3c022017-12-22 16:02:54 -08003971 }
3972 }
htaa2a49d92016-03-04 02:51:39 -08003973}
3974
zhihuang1c378ed2017-08-17 14:10:50 -07003975void PeerConnection::GenerateMediaDescriptionOptions(
3976 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003977 RtpTransceiverDirection audio_direction,
3978 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003979 rtc::Optional<size_t>* audio_index,
3980 rtc::Optional<size_t>* video_index,
3981 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003982 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003983 for (const cricket::ContentInfo& content :
3984 session_desc->description()->contents()) {
3985 if (IsAudioContent(&content)) {
3986 // If we already have an audio m= section, reject this extra one.
3987 if (*audio_index) {
3988 session_options->media_description_options.push_back(
3989 cricket::MediaDescriptionOptions(
3990 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003991 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003992 } else {
3993 session_options->media_description_options.push_back(
3994 cricket::MediaDescriptionOptions(
3995 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003996 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003997 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003998 }
3999 } else if (IsVideoContent(&content)) {
4000 // If we already have an video m= section, reject this extra one.
4001 if (*video_index) {
4002 session_options->media_description_options.push_back(
4003 cricket::MediaDescriptionOptions(
4004 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004005 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004006 } else {
4007 session_options->media_description_options.push_back(
4008 cricket::MediaDescriptionOptions(
4009 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004010 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004011 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004012 }
4013 } else {
4014 RTC_DCHECK(IsDataContent(&content));
4015 // If we already have an data m= section, reject this extra one.
4016 if (*data_index) {
4017 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004018 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004019 } else {
4020 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004021 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004022 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004023 }
4024 }
htaa2a49d92016-03-04 02:51:39 -08004025 }
deadbeefab9b2d12015-10-14 11:33:11 -07004026}
4027
Steve Antonfa2260d2017-12-28 16:38:23 -08004028cricket::MediaDescriptionOptions
4029PeerConnection::GetMediaDescriptionOptionsForActiveData(
4030 const std::string& mid) const {
4031 // Direction for data sections is meaningless, but legacy endpoints might
4032 // expect sendrecv.
4033 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4034 RtpTransceiverDirection::kSendRecv,
4035 /*stopped=*/false);
4036 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4037 return options;
4038}
4039
4040cricket::MediaDescriptionOptions
4041PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4042 const std::string& mid) const {
4043 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4044 RtpTransceiverDirection::kInactive,
4045 /*stopped=*/true);
4046 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4047 return options;
4048}
4049
4050rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4051 switch (data_channel_type_) {
4052 case cricket::DCT_RTP:
4053 if (!rtp_data_channel_) {
4054 return rtc::nullopt;
4055 }
4056 return rtp_data_channel_->content_name();
4057 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004058 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004059 default:
4060 return rtc::nullopt;
4061 }
4062}
4063
Steve Anton4171afb2017-11-20 10:20:22 -08004064void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4065 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4066 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004067 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004068}
4069
Steve Anton4171afb2017-11-20 10:20:22 -08004070void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004071 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004072 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004073 cricket::MediaType media_type,
4074 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004075 RTC_DCHECK(!IsUnifiedPlan());
4076
Steve Anton4171afb2017-11-20 10:20:22 -08004077 std::vector<RtpSenderInfo>* current_senders =
4078 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004079
Steve Anton4171afb2017-11-20 10:20:22 -08004080 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004081 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004082 for (auto sender_it = current_senders->begin();
4083 sender_it != current_senders->end();
4084 /* incremented manually */) {
4085 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004086 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004087 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004088 std::string params_stream_id;
4089 if (params) {
4090 params_stream_id =
4091 (!params->first_stream_id().empty() ? params->first_stream_id()
4092 : kDefaultStreamId);
4093 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004094 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004095 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004096 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004097 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004098 sender_exists) {
4099 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004100 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004101 OnRemoteSenderRemoved(info, media_type);
4102 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004103 }
4104 }
4105
Steve Anton4171afb2017-11-20 10:20:22 -08004106 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004107 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004108 if (!params.has_ssrcs()) {
4109 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4110 // sender, this means it is coming from a Unified Plan endpoint,so we just
4111 // create a default.
4112 default_sender_needed = true;
4113 break;
4114 }
4115
Seth Hampson845e8782018-03-02 11:34:10 -08004116 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004117 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004118 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4119 // not supported in Plan B, we just take the first here and create the
4120 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004121 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004122 (!params.first_stream_id().empty() ? params.first_stream_id()
4123 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004124 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004125 uint32_t ssrc = params.first_ssrc();
4126
4127 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004128 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004129 if (!stream) {
4130 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004131 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004132 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004133 remote_streams_->AddStream(stream);
4134 new_streams->AddStream(stream);
4135 }
4136
Steve Anton4171afb2017-11-20 10:20:22 -08004137 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004138 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004139 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004140 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004141 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004142 }
4143 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004144
Steve Anton4171afb2017-11-20 10:20:22 -08004145 // Add default sender if necessary.
4146 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004147 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004148 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004149 if (!default_stream) {
4150 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004151 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004152 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004153 remote_streams_->AddStream(default_stream);
4154 new_streams->AddStream(default_stream);
4155 }
Steve Anton4171afb2017-11-20 10:20:22 -08004156 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4157 ? kDefaultAudioSenderId
4158 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004159 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004160 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004161 if (!default_sender_info) {
4162 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004163 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004164 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004165 }
4166 }
deadbeefab9b2d12015-10-14 11:33:11 -07004167}
4168
Steve Anton4171afb2017-11-20 10:20:22 -08004169void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4170 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004171 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4172 << " receiver for track_id=" << sender_info.sender_id
4173 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004174
Steve Anton3d954a62018-04-02 11:27:23 -07004175 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004176 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004177 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004178 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004179 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004180 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004181 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004182 }
4183}
4184
Steve Anton4171afb2017-11-20 10:20:22 -08004185void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4186 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004187 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4188 << " receiver for track_id=" << sender_info.sender_id
4189 << " and stream_id=" << sender_info.stream_id;
4190
Seth Hampson845e8782018-03-02 11:34:10 -08004191 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004192
Henrik Boström933d8b02017-10-10 10:05:16 -07004193 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004194 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004195 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4196 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004197 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004198 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004199 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004200 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004201 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004202 }
4203 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004204 // Stopping or destroying a VideoRtpReceiver will end the
4205 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004206 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004207 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004208 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004209 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004210 // There's no guarantee the track is still available, e.g. the track may
4211 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004212 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004213 }
4214 } else {
nisseede5da42017-01-12 05:15:36 -08004215 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004216 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004217 if (receiver) {
4218 observer_->OnRemoveTrack(receiver);
4219 }
deadbeefab9b2d12015-10-14 11:33:11 -07004220}
4221
4222void PeerConnection::UpdateEndedRemoteMediaStreams() {
4223 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4224 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4225 MediaStreamInterface* stream = remote_streams_->at(i);
4226 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4227 streams_to_remove.push_back(stream);
4228 }
4229 }
4230
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004231 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004232 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004233 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004234 }
4235}
4236
Steve Anton4171afb2017-11-20 10:20:22 -08004237void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004238 const std::vector<cricket::StreamParams>& streams,
4239 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004240 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004241
Seth Hampson845e8782018-03-02 11:34:10 -08004242 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004243 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004244 for (auto sender_it = current_senders->begin();
4245 sender_it != current_senders->end();
4246 /* incremented manually */) {
4247 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004248 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004249 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4250 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004251 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004252 OnLocalSenderRemoved(info, media_type);
4253 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004254 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004255 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004256 }
4257 }
4258
Steve Anton4171afb2017-11-20 10:20:22 -08004259 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004260 for (const cricket::StreamParams& params : streams) {
4261 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004262 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004263 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004264 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004265 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004266 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004267 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004268 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004269 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004270 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004271 }
4272 }
4273}
4274
Steve Anton4171afb2017-11-20 10:20:22 -08004275void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4276 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004277 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004278 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004279 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004280 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4281 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004282 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004283 return;
4284 }
4285
deadbeeffac06552015-11-25 11:26:01 -08004286 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004287 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004288 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004289 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004290 }
deadbeeffac06552015-11-25 11:26:01 -08004291
Seth Hampson5b4f0752018-04-02 16:31:36 -07004292 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004293 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004294}
4295
Steve Anton4171afb2017-11-20 10:20:22 -08004296void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4297 cricket::MediaType media_type) {
4298 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004299 if (!sender) {
4300 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004301 // SessionDescriptions has been renegotiated.
4302 return;
4303 }
deadbeeffac06552015-11-25 11:26:01 -08004304
4305 // A sender has been removed from the SessionDescription but it's still
4306 // associated with the PeerConnection. This only occurs if the SDP doesn't
4307 // match with the calls to CreateSender, AddStream and RemoveStream.
4308 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004309 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004310 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004311 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004312 }
deadbeeffac06552015-11-25 11:26:01 -08004313
Steve Anton4171afb2017-11-20 10:20:22 -08004314 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004315}
4316
4317void PeerConnection::UpdateLocalRtpDataChannels(
4318 const cricket::StreamParamsVec& streams) {
4319 std::vector<std::string> existing_channels;
4320
4321 // Find new and active data channels.
4322 for (const cricket::StreamParams& params : streams) {
4323 // |it->sync_label| is actually the data channel label. The reason is that
4324 // we use the same naming of data channels as we do for
4325 // MediaStreams and Tracks.
4326 // For MediaStreams, the sync_label is the MediaStream label and the
4327 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004328 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004329 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004330 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004331 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004332 continue;
4333 }
4334 // Set the SSRC the data channel should use for sending.
4335 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4336 existing_channels.push_back(data_channel_it->first);
4337 }
4338
4339 UpdateClosingRtpDataChannels(existing_channels, true);
4340}
4341
4342void PeerConnection::UpdateRemoteRtpDataChannels(
4343 const cricket::StreamParamsVec& streams) {
4344 std::vector<std::string> existing_channels;
4345
4346 // Find new and active data channels.
4347 for (const cricket::StreamParams& params : streams) {
4348 // The data channel label is either the mslabel or the SSRC if the mslabel
4349 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004350 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004351 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004352 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004353 auto data_channel_it = rtp_data_channels_.find(label);
4354 if (data_channel_it == rtp_data_channels_.end()) {
4355 // This is a new data channel.
4356 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4357 } else {
4358 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4359 }
4360 existing_channels.push_back(label);
4361 }
4362
4363 UpdateClosingRtpDataChannels(existing_channels, false);
4364}
4365
4366void PeerConnection::UpdateClosingRtpDataChannels(
4367 const std::vector<std::string>& active_channels,
4368 bool is_local_update) {
4369 auto it = rtp_data_channels_.begin();
4370 while (it != rtp_data_channels_.end()) {
4371 DataChannel* data_channel = it->second;
4372 if (std::find(active_channels.begin(), active_channels.end(),
4373 data_channel->label()) != active_channels.end()) {
4374 ++it;
4375 continue;
4376 }
4377
4378 if (is_local_update) {
4379 data_channel->SetSendSsrc(0);
4380 } else {
4381 data_channel->RemotePeerRequestClose();
4382 }
4383
4384 if (data_channel->state() == DataChannel::kClosed) {
4385 rtp_data_channels_.erase(it);
4386 it = rtp_data_channels_.begin();
4387 } else {
4388 ++it;
4389 }
4390 }
4391}
4392
4393void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4394 uint32_t remote_ssrc) {
4395 rtc::scoped_refptr<DataChannel> channel(
4396 InternalCreateDataChannel(label, nullptr));
4397 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004398 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004399 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004400 return;
4401 }
4402 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004403 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4404 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004405 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004406}
4407
4408rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4409 const std::string& label,
4410 const InternalDataChannelInit* config) {
4411 if (IsClosed()) {
4412 return nullptr;
4413 }
Steve Anton75737c02017-11-06 10:37:17 -08004414 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004415 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004416 << "InternalCreateDataChannel: Data is not supported in this call.";
4417 return nullptr;
4418 }
4419 InternalDataChannelInit new_config =
4420 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004421 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004422 if (new_config.id < 0) {
4423 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004424 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004425 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004426 RTC_LOG(LS_ERROR)
4427 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004428 return nullptr;
4429 }
4430 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004431 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004432 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004433 return nullptr;
4434 }
4435 }
4436
Steve Anton75737c02017-11-06 10:37:17 -08004437 rtc::scoped_refptr<DataChannel> channel(
4438 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004439 if (!channel) {
4440 sid_allocator_.ReleaseSid(new_config.id);
4441 return nullptr;
4442 }
4443
4444 if (channel->data_channel_type() == cricket::DCT_RTP) {
4445 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004446 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4447 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004448 return nullptr;
4449 }
4450 rtp_data_channels_[channel->label()] = channel;
4451 } else {
4452 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4453 sctp_data_channels_.push_back(channel);
4454 channel->SignalClosed.connect(this,
4455 &PeerConnection::OnSctpDataChannelClosed);
4456 }
4457
Steve Anton2d8609c2018-01-23 16:38:46 -08004458 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004459 return channel;
4460}
4461
4462bool PeerConnection::HasDataChannels() const {
4463 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4464}
4465
4466void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4467 for (const auto& channel : sctp_data_channels_) {
4468 if (channel->id() < 0) {
4469 int sid;
4470 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004471 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004472 continue;
4473 }
4474 channel->SetSctpSid(sid);
4475 }
4476 }
4477}
4478
4479void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004480 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004481 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4482 ++it) {
4483 if (it->get() == channel) {
4484 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004485 // After the closing procedure is done, it's safe to use this ID for
4486 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004487 sid_allocator_.ReleaseSid(channel->id());
4488 }
deadbeefbd292462015-12-14 18:15:29 -08004489 // Since this method is triggered by a signal from the DataChannel,
4490 // we can't free it directly here; we need to free it asynchronously.
4491 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004492 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004493 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4494 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004495 return;
4496 }
4497 }
4498}
4499
deadbeefab9b2d12015-10-14 11:33:11 -07004500void PeerConnection::OnDataChannelDestroyed() {
4501 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4502 // DataChannel may callback to us and try to modify the list.
4503 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4504 temp_rtp_dcs.swap(rtp_data_channels_);
4505 for (const auto& kv : temp_rtp_dcs) {
4506 kv.second->OnTransportChannelDestroyed();
4507 }
4508
4509 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4510 temp_sctp_dcs.swap(sctp_data_channels_);
4511 for (const auto& channel : temp_sctp_dcs) {
4512 channel->OnTransportChannelDestroyed();
4513 }
4514}
4515
4516void PeerConnection::OnDataChannelOpenMessage(
4517 const std::string& label,
4518 const InternalDataChannelInit& config) {
4519 rtc::scoped_refptr<DataChannel> channel(
4520 InternalCreateDataChannel(label, &config));
4521 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004522 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004523 return;
4524 }
4525
deadbeefa601f5c2016-06-06 14:27:39 -07004526 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4527 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004528 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004529}
4530
Steve Anton4171afb2017-11-20 10:20:22 -08004531rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4532PeerConnection::GetAudioTransceiver() const {
4533 // This method only works with Plan B SDP, where there is a single
4534 // audio/video transceiver.
4535 RTC_DCHECK(!IsUnifiedPlan());
4536 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004537 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004538 return transceiver;
4539 }
4540 }
4541 RTC_NOTREACHED();
4542 return nullptr;
4543}
4544
4545rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4546PeerConnection::GetVideoTransceiver() const {
4547 // This method only works with Plan B SDP, where there is a single
4548 // audio/video transceiver.
4549 RTC_DCHECK(!IsUnifiedPlan());
4550 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004551 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004552 return transceiver;
4553 }
4554 }
4555 RTC_NOTREACHED();
4556 return nullptr;
4557}
4558
4559// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4560// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004561bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004562 switch (type) {
4563 case cricket::MEDIA_TYPE_AUDIO:
4564 return !GetAudioTransceiver()->internal()->senders().empty();
4565 case cricket::MEDIA_TYPE_VIDEO:
4566 return !GetVideoTransceiver()->internal()->senders().empty();
4567 case cricket::MEDIA_TYPE_DATA:
4568 return false;
4569 }
4570 RTC_NOTREACHED();
4571 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004572}
4573
Steve Anton4171afb2017-11-20 10:20:22 -08004574rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4575PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4576 for (auto transceiver : transceivers_) {
4577 for (auto sender : transceiver->internal()->senders()) {
4578 if (sender->track() == track) {
4579 return sender;
4580 }
4581 }
4582 }
4583 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004584}
4585
Steve Anton4171afb2017-11-20 10:20:22 -08004586rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4587PeerConnection::FindSenderById(const std::string& sender_id) const {
4588 for (auto transceiver : transceivers_) {
4589 for (auto sender : transceiver->internal()->senders()) {
4590 if (sender->id() == sender_id) {
4591 return sender;
4592 }
4593 }
4594 }
4595 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004596}
4597
Steve Anton4171afb2017-11-20 10:20:22 -08004598rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4599PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4600 for (auto transceiver : transceivers_) {
4601 for (auto receiver : transceiver->internal()->receivers()) {
4602 if (receiver->id() == receiver_id) {
4603 return receiver;
4604 }
4605 }
4606 }
4607 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004608}
4609
Steve Anton4171afb2017-11-20 10:20:22 -08004610std::vector<PeerConnection::RtpSenderInfo>*
4611PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4612 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4613 media_type == cricket::MEDIA_TYPE_VIDEO);
4614 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4615 ? &remote_audio_sender_infos_
4616 : &remote_video_sender_infos_;
4617}
4618
4619std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004620 cricket::MediaType media_type) {
4621 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4622 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004623 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4624 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004625}
4626
Steve Anton4171afb2017-11-20 10:20:22 -08004627const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4628 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004629 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004630 const std::string sender_id) const {
4631 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004632 if (sender_info.stream_id == stream_id &&
4633 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004634 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004635 }
4636 }
4637 return nullptr;
4638}
4639
4640DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4641 for (const auto& channel : sctp_data_channels_) {
4642 if (channel->id() == sid) {
4643 return channel;
4644 }
4645 }
4646 return nullptr;
4647}
4648
deadbeef91dd5672016-05-18 16:55:30 -07004649bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004650 const RTCConfiguration& configuration) {
4651 cricket::ServerAddresses stun_servers;
4652 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004653 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4654 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004655 return false;
4656 }
4657
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004658 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004659 // To handle both internal and externally created port allocator, we will
4660 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004661 port_allocator_flags_ = port_allocator_->flags();
4662 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4663 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4664 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004665 // If the disable-IPv6 flag was specified, we'll not override it
4666 // by experiment.
4667 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004668 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004669 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4670 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004671 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004672 }
4673
zhihuangb09b3f92017-03-07 14:40:51 -08004674 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004675 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004676 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004677 }
4678
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004679 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004680 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004681 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004682 }
4683
honghaiz60347052016-05-31 18:29:12 -07004684 if (configuration.candidate_network_policy ==
4685 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004686 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004687 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004688 }
4689
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004690 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004691 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004692 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4693 }
4694
Qingsi Wanga2d60672018-04-11 16:57:45 -07004695 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004696 // No step delay is used while allocating ports.
4697 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4698 port_allocator_->set_candidate_filter(
4699 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004700 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004701
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004702 if (tls_cert_verifier_ != nullptr) {
4703 for (auto& turn_server : turn_servers) {
4704 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4705 }
4706 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004707 // Call this last since it may create pooled allocator sessions using the
4708 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004709 port_allocator_->SetConfiguration(
4710 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4711 configuration.prune_turn_ports, configuration.turn_customizer,
4712 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004713 return true;
4714}
4715
deadbeef91dd5672016-05-18 16:55:30 -07004716bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004717 const cricket::ServerAddresses& stun_servers,
4718 const std::vector<cricket::RelayServerConfig>& turn_servers,
4719 IceTransportsType type,
4720 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004721 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004722 webrtc::TurnCustomizer* turn_customizer,
4723 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004724 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004725 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004726 // According to JSEP, after setLocalDescription, changing the candidate pool
4727 // size is not allowed, and changing the set of ICE servers will not result
4728 // in new candidates being gathered.
4729 if (local_description()) {
4730 port_allocator_->FreezeCandidatePool();
4731 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004732 // Call this last since it may create pooled allocator sessions using the
4733 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004734 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004735 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004736 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004737}
4738
Steve Antonba818672017-11-06 10:21:57 -08004739cricket::ChannelManager* PeerConnection::channel_manager() const {
4740 return factory_->channel_manager();
4741}
4742
4743MetricsObserverInterface* PeerConnection::metrics_observer() const {
4744 return uma_observer_;
4745}
4746
Elad Alon99c3fe52017-10-13 16:29:40 +02004747bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004748 std::unique_ptr<RtcEventLogOutput> output,
4749 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004750 if (!event_log_) {
4751 return false;
4752 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004753 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004754}
4755
4756void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004757 if (event_log_) {
4758 event_log_->StopLogging();
4759 }
ivoc14d5dbe2016-07-04 07:06:55 -07004760}
nisseeaabdf62017-05-05 02:23:02 -07004761
Steve Anton75737c02017-11-06 10:37:17 -08004762cricket::BaseChannel* PeerConnection::GetChannel(
4763 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004764 for (auto transceiver : transceivers_) {
4765 cricket::BaseChannel* channel = transceiver->internal()->channel();
4766 if (channel && channel->content_name() == content_name) {
4767 return channel;
4768 }
Steve Anton75737c02017-11-06 10:37:17 -08004769 }
4770 if (rtp_data_channel() &&
4771 rtp_data_channel()->content_name() == content_name) {
4772 return rtp_data_channel();
4773 }
4774 return nullptr;
4775}
4776
4777bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4778 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004779 RTC_LOG(LS_INFO)
4780 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004781 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004782 return false;
4783 }
4784 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004785 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004786 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004787 return false;
4788 }
4789
Zhi Huange830e682018-03-30 10:48:35 -07004790 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4791 if (dtls_role) {
4792 *role = *dtls_role;
4793 return true;
4794 }
4795 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004796}
4797
4798bool PeerConnection::GetSslRole(const std::string& content_name,
4799 rtc::SSLRole* role) {
4800 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004801 RTC_LOG(LS_INFO)
4802 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004803 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004804 return false;
4805 }
4806
Zhi Huange830e682018-03-30 10:48:35 -07004807 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4808 if (dtls_role) {
4809 *role = *dtls_role;
4810 return true;
4811 }
4812 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004813}
4814
Steve Antonf8470812017-12-04 10:46:21 -08004815void PeerConnection::SetSessionError(SessionError error,
4816 const std::string& error_desc) {
4817 RTC_DCHECK_RUN_ON(signaling_thread());
4818 if (error != session_error_) {
4819 session_error_ = error;
4820 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004821 }
4822}
4823
Zhi Huange830e682018-03-30 10:48:35 -07004824RTCError PeerConnection::UpdateSessionState(
4825 SdpType type,
4826 cricket::ContentSource source,
4827 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004828 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004829
4830 // If there's already a pending error then no state transition should happen.
4831 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004832 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004833
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004834 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004835 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004836 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004837 }
4838
4839 // Update the signaling state according to the specified state machine (see
4840 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004841 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004842 ChangeSignalingState(source == cricket::CS_LOCAL
4843 ? PeerConnectionInterface::kHaveLocalOffer
4844 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004845 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004846 ChangeSignalingState(source == cricket::CS_LOCAL
4847 ? PeerConnectionInterface::kHaveLocalPrAnswer
4848 : PeerConnectionInterface::kHaveRemotePrAnswer);
4849 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004850 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004851 ChangeSignalingState(PeerConnectionInterface::kStable);
4852 }
4853
4854 // Update internal objects according to the session description's media
4855 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004856 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004857 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004858 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004859 }
4860
Steve Anton8a006912017-12-04 15:25:56 -08004861 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004862}
4863
Steve Anton8a006912017-12-04 15:25:56 -08004864RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004865 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004866 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004867 const SessionDescriptionInterface* sdesc =
4868 (source == cricket::CS_LOCAL ? local_description()
4869 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004870 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004871
4872 // Push down the new SDP media section for each audio/video transceiver.
4873 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004874 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004875 FindMediaSectionForTransceiver(transceiver, sdesc);
4876 cricket::BaseChannel* channel = transceiver->internal()->channel();
4877 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004878 continue;
4879 }
4880 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004881 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004882 if (!content_desc) {
4883 continue;
4884 }
4885 std::string error;
4886 bool success =
4887 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004888 ? channel->SetLocalContent(content_desc, type, &error)
4889 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004890 if (!success) {
4891 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4892 }
4893 }
4894
4895 // If using the RtpDataChannel, push down the new SDP section for it too.
4896 if (rtp_data_channel_) {
4897 const ContentInfo* data_content =
4898 cricket::GetFirstDataContent(sdesc->description());
4899 if (data_content && !data_content->rejected) {
4900 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004901 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004902 if (data_desc) {
4903 std::string error;
4904 bool success =
4905 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004906 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4907 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004908 &error);
4909 if (!success) {
4910 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4911 std::move(error));
4912 }
Steve Anton75737c02017-11-06 10:37:17 -08004913 }
4914 }
4915 }
Steve Antoned10bd92017-12-05 10:52:59 -08004916
Steve Anton75737c02017-11-06 10:37:17 -08004917 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4918 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4919 if (sctp_transport_ && local_description() && remote_description() &&
4920 cricket::GetFirstDataContent(local_description()->description()) &&
4921 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004922 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004923 RTC_FROM_HERE,
4924 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004925 if (!success) {
4926 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4927 "Failed to push down SCTP parameters.");
4928 }
Steve Anton75737c02017-11-06 10:37:17 -08004929 }
Steve Antoned10bd92017-12-05 10:52:59 -08004930
Steve Anton8a006912017-12-04 15:25:56 -08004931 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004932}
4933
4934bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4935 RTC_DCHECK(network_thread()->IsCurrent());
4936 RTC_DCHECK(local_description());
4937 RTC_DCHECK(remote_description());
4938 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4939 // When we support "max-message-size", that would also be pushed down here.
4940 return sctp_transport_->Start(
4941 GetSctpPort(local_description()->description()),
4942 GetSctpPort(remote_description()->description()));
4943}
4944
Steve Anton8a006912017-12-04 15:25:56 -08004945RTCError PeerConnection::PushdownTransportDescription(
4946 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004947 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004948 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004949
Zhi Huange830e682018-03-30 10:48:35 -07004950 if (source == cricket::CS_LOCAL) {
4951 const SessionDescriptionInterface* sdesc = local_description();
4952 RTC_DCHECK(sdesc);
4953 return transport_controller_->SetLocalDescription(type,
4954 sdesc->description());
4955 } else {
4956 const SessionDescriptionInterface* sdesc = remote_description();
4957 RTC_DCHECK(sdesc);
4958 return transport_controller_->SetRemoteDescription(type,
4959 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004960 }
Steve Anton75737c02017-11-06 10:37:17 -08004961}
4962
4963bool PeerConnection::GetTransportDescription(
4964 const SessionDescription* description,
4965 const std::string& content_name,
4966 cricket::TransportDescription* tdesc) {
4967 if (!description || !tdesc) {
4968 return false;
4969 }
4970 const TransportInfo* transport_info =
4971 description->GetTransportInfoByName(content_name);
4972 if (!transport_info) {
4973 return false;
4974 }
4975 *tdesc = transport_info->description;
4976 return true;
4977}
4978
Steve Anton75737c02017-11-06 10:37:17 -08004979cricket::IceConfig PeerConnection::ParseIceConfig(
4980 const PeerConnectionInterface::RTCConfiguration& config) const {
4981 cricket::ContinualGatheringPolicy gathering_policy;
4982 // TODO(honghaiz): Add the third continual gathering policy in
4983 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4984 switch (config.continual_gathering_policy) {
4985 case PeerConnectionInterface::GATHER_ONCE:
4986 gathering_policy = cricket::GATHER_ONCE;
4987 break;
4988 case PeerConnectionInterface::GATHER_CONTINUALLY:
4989 gathering_policy = cricket::GATHER_CONTINUALLY;
4990 break;
4991 default:
4992 RTC_NOTREACHED();
4993 gathering_policy = cricket::GATHER_ONCE;
4994 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004995
Steve Anton75737c02017-11-06 10:37:17 -08004996 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004997 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4998 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004999 ice_config.prioritize_most_likely_candidate_pairs =
5000 config.prioritize_most_likely_ice_candidate_pairs;
5001 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005002 RTCConfigurationToIceConfigOptionalInt(
5003 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005004 ice_config.continual_gathering_policy = gathering_policy;
5005 ice_config.presume_writable_when_fully_relayed =
5006 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005007 ice_config.ice_check_interval_strong_connectivity =
5008 config.ice_check_interval_strong_connectivity;
5009 ice_config.ice_check_interval_weak_connectivity =
5010 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005011 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005012 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005013 ice_config.regather_all_networks_interval_range =
5014 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005015 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005016 return ice_config;
5017}
5018
Steve Anton75737c02017-11-06 10:37:17 -08005019bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5020 std::string* track_id) {
5021 if (!local_description()) {
5022 return false;
5023 }
5024 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5025 track_id);
5026}
5027
5028bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5029 std::string* track_id) {
5030 if (!remote_description()) {
5031 return false;
5032 }
5033 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5034 track_id);
5035}
5036
5037bool PeerConnection::SendData(const cricket::SendDataParams& params,
5038 const rtc::CopyOnWriteBuffer& payload,
5039 cricket::SendDataResult* result) {
5040 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005041 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005042 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005043 return false;
5044 }
5045 return rtp_data_channel_
5046 ? rtp_data_channel_->SendData(params, payload, result)
5047 : network_thread()->Invoke<bool>(
5048 RTC_FROM_HERE,
5049 Bind(&cricket::SctpTransportInternal::SendData,
5050 sctp_transport_.get(), params, payload, result));
5051}
5052
5053bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5054 if (!rtp_data_channel_ && !sctp_transport_) {
5055 // Don't log an error here, because DataChannels are expected to call
5056 // ConnectDataChannel in this state. It's the only way to initially tell
5057 // whether or not the underlying transport is ready.
5058 return false;
5059 }
5060 if (rtp_data_channel_) {
5061 rtp_data_channel_->SignalReadyToSendData.connect(
5062 webrtc_data_channel, &DataChannel::OnChannelReady);
5063 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5064 &DataChannel::OnDataReceived);
5065 } else {
5066 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5067 &DataChannel::OnChannelReady);
5068 SignalSctpDataReceived.connect(webrtc_data_channel,
5069 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005070 SignalSctpClosingProcedureStartedRemotely.connect(
5071 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5072 SignalSctpClosingProcedureComplete.connect(
5073 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005074 }
5075 return true;
5076}
5077
5078void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5079 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005080 RTC_LOG(LS_ERROR)
5081 << "DisconnectDataChannel called when rtp_data_channel_ and "
5082 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005083 return;
5084 }
5085 if (rtp_data_channel_) {
5086 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5087 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5088 } else {
5089 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5090 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005091 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5092 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005093 }
5094}
5095
5096void PeerConnection::AddSctpDataStream(int sid) {
5097 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005098 RTC_LOG(LS_ERROR)
5099 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005100 return;
5101 }
5102 network_thread()->Invoke<void>(
5103 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5104 sctp_transport_.get(), sid));
5105}
5106
5107void PeerConnection::RemoveSctpDataStream(int sid) {
5108 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005109 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005110 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005111 return;
5112 }
5113 network_thread()->Invoke<void>(
5114 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5115 sctp_transport_.get(), sid));
5116}
5117
5118bool PeerConnection::ReadyToSendData() const {
5119 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5120 sctp_ready_to_send_data_;
5121}
5122
Zhi Huange830e682018-03-30 10:48:35 -07005123rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5124 if (sctp_mid_ && transport_controller_) {
5125 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5126 if (dtls_transport) {
5127 return dtls_transport->transport_name();
5128 }
5129 return rtc::Optional<std::string>();
5130 }
5131 return rtc::Optional<std::string>();
5132}
5133
Qingsi Wang72a43a12018-02-20 16:03:18 -08005134cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5135 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005136 network_thread()->Invoke<void>(
5137 RTC_FROM_HERE,
5138 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5139 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005140 return candidate_states_list;
5141}
5142
Steve Anton5dfde182018-02-06 10:34:40 -08005143std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5144 const {
5145 std::map<std::string, std::string> transport_names_by_mid;
5146 for (auto transceiver : transceivers_) {
5147 cricket::BaseChannel* channel = transceiver->internal()->channel();
5148 if (channel) {
5149 transport_names_by_mid[channel->content_name()] =
5150 channel->transport_name();
5151 }
Steve Anton75737c02017-11-06 10:37:17 -08005152 }
Steve Anton5dfde182018-02-06 10:34:40 -08005153 if (rtp_data_channel_) {
5154 transport_names_by_mid[rtp_data_channel_->content_name()] =
5155 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005156 }
5157 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005158 rtc::Optional<std::string> transport_name = sctp_transport_name();
5159 RTC_DCHECK(transport_name);
5160 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005161 }
Steve Anton5dfde182018-02-06 10:34:40 -08005162 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005163}
5164
Steve Anton5dfde182018-02-06 10:34:40 -08005165std::map<std::string, cricket::TransportStats>
5166PeerConnection::GetTransportStatsByNames(
5167 const std::set<std::string>& transport_names) {
5168 if (!network_thread()->IsCurrent()) {
5169 return network_thread()
5170 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5171 RTC_FROM_HERE,
5172 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005173 }
Steve Anton5dfde182018-02-06 10:34:40 -08005174 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5175 for (const std::string& transport_name : transport_names) {
5176 cricket::TransportStats transport_stats;
5177 bool success =
5178 transport_controller_->GetStats(transport_name, &transport_stats);
5179 if (success) {
5180 transport_stats_by_name[transport_name] = std::move(transport_stats);
5181 } else {
5182 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5183 << transport_name;
5184 }
5185 }
5186 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005187}
5188
5189bool PeerConnection::GetLocalCertificate(
5190 const std::string& transport_name,
5191 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005192 if (!certificate) {
5193 return false;
5194 }
5195 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5196 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005197}
5198
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005199std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005200 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005201 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005202}
5203
5204cricket::DataChannelType PeerConnection::data_channel_type() const {
5205 return data_channel_type_;
5206}
5207
5208bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5209 return pending_ice_restarts_.find(content_name) !=
5210 pending_ice_restarts_.end();
5211}
5212
Steve Anton75737c02017-11-06 10:37:17 -08005213bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5214 return transport_controller_->NeedsIceRestart(content_name);
5215}
5216
5217void PeerConnection::OnCertificateReady(
5218 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5219 transport_controller_->SetLocalCertificate(certificate);
5220}
5221
5222void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005223 SetSessionError(SessionError::kTransport,
5224 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005225}
5226
5227void PeerConnection::OnTransportControllerConnectionState(
5228 cricket::IceConnectionState state) {
5229 switch (state) {
5230 case cricket::kIceConnectionConnecting:
5231 // If the current state is Connected or Completed, then there were
5232 // writable channels but now there are not, so the next state must
5233 // be Disconnected.
5234 // kIceConnectionConnecting is currently used as the default,
5235 // un-connected state by the TransportController, so its only use is
5236 // detecting disconnections.
5237 if (ice_connection_state_ ==
5238 PeerConnectionInterface::kIceConnectionConnected ||
5239 ice_connection_state_ ==
5240 PeerConnectionInterface::kIceConnectionCompleted) {
5241 SetIceConnectionState(
5242 PeerConnectionInterface::kIceConnectionDisconnected);
5243 }
5244 break;
5245 case cricket::kIceConnectionFailed:
5246 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5247 break;
5248 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005249 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005250 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005251 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005252 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005253 break;
5254 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005255 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005256 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005257 if (ice_connection_state_ !=
5258 PeerConnectionInterface::kIceConnectionConnected) {
5259 // If jumping directly from "checking" to "connected",
5260 // signal "connected" first.
5261 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5262 }
5263 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005264 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005265 if (metrics_observer()) {
5266 ReportTransportStats();
5267 }
5268 break;
5269 default:
5270 RTC_NOTREACHED();
5271 }
5272}
5273
5274void PeerConnection::OnTransportControllerCandidatesGathered(
5275 const std::string& transport_name,
5276 const cricket::Candidates& candidates) {
5277 RTC_DCHECK(signaling_thread()->IsCurrent());
5278 int sdp_mline_index;
5279 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005280 RTC_LOG(LS_ERROR)
5281 << "OnTransportControllerCandidatesGathered: content name "
5282 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005283 return;
5284 }
5285
5286 for (cricket::Candidates::const_iterator citer = candidates.begin();
5287 citer != candidates.end(); ++citer) {
5288 // Use transport_name as the candidate media id.
5289 std::unique_ptr<JsepIceCandidate> candidate(
5290 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5291 if (local_description()) {
5292 mutable_local_description()->AddCandidate(candidate.get());
5293 }
5294 OnIceCandidate(std::move(candidate));
5295 }
5296}
5297
5298void PeerConnection::OnTransportControllerCandidatesRemoved(
5299 const std::vector<cricket::Candidate>& candidates) {
5300 RTC_DCHECK(signaling_thread()->IsCurrent());
5301 // Sanity check.
5302 for (const cricket::Candidate& candidate : candidates) {
5303 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005304 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005305 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005306 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005307 return;
5308 }
5309 }
5310
5311 if (local_description()) {
5312 mutable_local_description()->RemoveCandidates(candidates);
5313 }
5314 OnIceCandidatesRemoved(candidates);
5315}
5316
5317void PeerConnection::OnTransportControllerDtlsHandshakeError(
5318 rtc::SSLHandshakeError error) {
5319 if (metrics_observer()) {
5320 metrics_observer()->IncrementEnumCounter(
5321 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5322 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5323 }
5324}
5325
Steve Antoned10bd92017-12-05 10:52:59 -08005326void PeerConnection::EnableSending() {
5327 for (auto transceiver : transceivers_) {
5328 cricket::BaseChannel* channel = transceiver->internal()->channel();
5329 if (channel && !channel->enabled()) {
5330 channel->Enable(true);
5331 }
Steve Anton75737c02017-11-06 10:37:17 -08005332 }
5333
Steve Anton4171afb2017-11-20 10:20:22 -08005334 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005335 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005336 }
Steve Anton75737c02017-11-06 10:37:17 -08005337}
5338
5339// Returns the media index for a local ice candidate given the content name.
5340bool PeerConnection::GetLocalCandidateMediaIndex(
5341 const std::string& content_name,
5342 int* sdp_mline_index) {
5343 if (!local_description() || !sdp_mline_index) {
5344 return false;
5345 }
5346
5347 bool content_found = false;
5348 const ContentInfos& contents = local_description()->description()->contents();
5349 for (size_t index = 0; index < contents.size(); ++index) {
5350 if (contents[index].name == content_name) {
5351 *sdp_mline_index = static_cast<int>(index);
5352 content_found = true;
5353 break;
5354 }
5355 }
5356 return content_found;
5357}
5358
5359bool PeerConnection::UseCandidatesInSessionDescription(
5360 const SessionDescriptionInterface* remote_desc) {
5361 if (!remote_desc) {
5362 return true;
5363 }
5364 bool ret = true;
5365
5366 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5367 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5368 for (size_t n = 0; n < candidates->count(); ++n) {
5369 const IceCandidateInterface* candidate = candidates->at(n);
5370 bool valid = false;
5371 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5372 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005373 RTC_LOG(LS_INFO)
5374 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005375 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005376 }
5377 continue;
5378 }
5379 ret = UseCandidate(candidate);
5380 if (!ret) {
5381 break;
5382 }
5383 }
5384 }
5385 return ret;
5386}
5387
5388bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5389 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5390 size_t remote_content_size =
5391 remote_description()->description()->contents().size();
5392 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005393 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005394 return false;
5395 }
5396
5397 cricket::ContentInfo content =
5398 remote_description()->description()->contents()[mediacontent_index];
5399 std::vector<cricket::Candidate> candidates;
5400 candidates.push_back(candidate->candidate());
5401 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005402 RTCError error =
5403 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005404 if (error.ok()) {
5405 // Candidates successfully submitted for checking.
5406 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5407 ice_connection_state_ ==
5408 PeerConnectionInterface::kIceConnectionDisconnected) {
5409 // If state is New, then the session has just gotten its first remote ICE
5410 // candidates, so go to Checking.
5411 // If state is Disconnected, the session is re-using old candidates or
5412 // receiving additional ones, so go to Checking.
5413 // If state is Connected, stay Connected.
5414 // TODO(bemasc): If state is Connected, and the new candidates are for a
5415 // newly added transport, then the state actually _should_ move to
5416 // checking. Add a way to distinguish that case.
5417 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5418 }
5419 // TODO(bemasc): If state is Completed, go back to Connected.
5420 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005421 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005422 }
5423 return true;
5424}
5425
5426void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005427 // Destroy video channel first since it may have a pointer to the
5428 // voice channel.
5429 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005430 if (!video_info || video_info->rejected) {
5431 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005432 }
5433
Steve Anton6fec8802017-12-04 10:37:29 -08005434 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5435 if (!audio_info || audio_info->rejected) {
5436 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005437 }
5438
5439 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5440 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005441 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005442 }
5443}
5444
Steve Antondcc3c022017-12-22 16:02:54 -08005445RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5446 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005447 const cricket::ContentGroup* bundle_group = nullptr;
5448 if (configuration_.bundle_policy ==
5449 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005450 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005451 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005452 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5453 "max-bundle configured but session description "
5454 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005455 }
5456 }
Steve Antondcc3c022017-12-22 16:02:54 -08005457 return std::move(bundle_group);
5458}
5459
5460RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005461 // Creating the media channels. Transports should already have been created
5462 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005463 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005464 if (voice && !voice->rejected &&
5465 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005466 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005467 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005468 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5469 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005470 }
5471 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5472 }
5473
Steve Antondcc3c022017-12-22 16:02:54 -08005474 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005475 if (video && !video->rejected &&
5476 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005477 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005478 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005479 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5480 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005481 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005482 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005483 }
5484
Steve Antondcc3c022017-12-22 16:02:54 -08005485 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005486 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5487 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005488 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005489 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5490 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005491 }
5492 }
5493
Steve Anton8a006912017-12-04 15:25:56 -08005494 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005495}
5496
Steve Anton4171afb2017-11-20 10:20:22 -08005497// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005498cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005499 const std::string& mid) {
5500 RtpTransportInternal* rtp_transport =
5501 transport_controller_->GetRtpTransport(mid);
5502 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005503 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005504 call_.get(), configuration_.media_config, rtp_transport,
5505 signaling_thread(), mid, SrtpRequired(),
5506 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005507 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005508 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005509 }
Steve Anton75737c02017-11-06 10:37:17 -08005510 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5511 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005512 voice_channel->SignalSentPacket.connect(this,
5513 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005514 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005515 if (uma_observer_) {
5516 voice_channel->SetMetricsObserver(uma_observer_);
5517 }
Steve Anton4171afb2017-11-20 10:20:22 -08005518
Steve Antoneda6ccd2017-12-04 10:21:55 -08005519 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005520}
5521
Steve Anton4171afb2017-11-20 10:20:22 -08005522// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005523cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005524 const std::string& mid) {
5525 RtpTransportInternal* rtp_transport =
5526 transport_controller_->GetRtpTransport(mid);
5527 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005528 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005529 call_.get(), configuration_.media_config, rtp_transport,
5530 signaling_thread(), mid, SrtpRequired(),
5531 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005532 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005533 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005534 }
Steve Anton75737c02017-11-06 10:37:17 -08005535 video_channel->SignalDtlsSrtpSetupFailure.connect(
5536 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005537 video_channel->SignalSentPacket.connect(this,
5538 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005539 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005540 if (uma_observer_) {
5541 video_channel->SetMetricsObserver(uma_observer_);
5542 }
Steve Anton4171afb2017-11-20 10:20:22 -08005543
Steve Antoneda6ccd2017-12-04 10:21:55 -08005544 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005545}
5546
Zhi Huange830e682018-03-30 10:48:35 -07005547bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005548 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5549 if (sctp) {
5550 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005551 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005552 << "Trying to create SCTP transport, but didn't compile with "
5553 "SCTP support (HAVE_SCTP)";
5554 return false;
5555 }
5556 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005557 RTC_FROM_HERE,
5558 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005559 return false;
5560 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005561 for (const auto& channel : sctp_data_channels_) {
5562 channel->OnTransportChannelCreated();
5563 }
Steve Anton75737c02017-11-06 10:37:17 -08005564 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005565 RtpTransportInternal* rtp_transport =
5566 transport_controller_->GetRtpTransport(mid);
5567 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005568 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005569 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5570 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005571 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005572 return false;
5573 }
Steve Anton75737c02017-11-06 10:37:17 -08005574 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5575 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5576 rtp_data_channel_->SignalSentPacket.connect(
5577 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005578 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005579 if (uma_observer_) {
5580 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5581 }
Steve Anton75737c02017-11-06 10:37:17 -08005582 }
5583
Steve Anton75737c02017-11-06 10:37:17 -08005584 return true;
5585}
5586
5587Call::Stats PeerConnection::GetCallStats() {
5588 if (!worker_thread()->IsCurrent()) {
5589 return worker_thread()->Invoke<Call::Stats>(
5590 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5591 }
5592 if (call_) {
5593 return call_->GetStats();
5594 } else {
5595 return Call::Stats();
5596 }
5597}
5598
Zhi Huange830e682018-03-30 10:48:35 -07005599bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005600 RTC_DCHECK(network_thread()->IsCurrent());
5601 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005602 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005603 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005604 RTC_DCHECK(dtls_transport);
5605 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005606 RTC_DCHECK(sctp_transport_);
5607 sctp_invoker_.reset(new rtc::AsyncInvoker());
5608 sctp_transport_->SignalReadyToSendData.connect(
5609 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5610 sctp_transport_->SignalDataReceived.connect(
5611 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005612 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5613 // another thread. Would be nice if there was a helper class similar to
5614 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5615 // code.
5616 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5617 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5618 sctp_transport_->SignalClosingProcedureComplete.connect(
5619 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005620 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005621 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005622 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005623}
5624
5625void PeerConnection::DestroySctpTransport_n() {
5626 RTC_DCHECK(network_thread()->IsCurrent());
5627 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005628 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005629 sctp_invoker_.reset(nullptr);
5630 sctp_ready_to_send_data_ = false;
5631}
5632
5633void PeerConnection::OnSctpTransportReadyToSendData_n() {
5634 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5635 RTC_DCHECK(network_thread()->IsCurrent());
5636 // Note: Cannot use rtc::Bind here because it will grab a reference to
5637 // PeerConnection and potentially cause PeerConnection to live longer than
5638 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5639 // be destroyed before PeerConnection is destroyed, and at that point all
5640 // pending tasks will be cleared.
5641 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5642 OnSctpTransportReadyToSendData_s(true);
5643 });
5644}
5645
5646void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5647 RTC_DCHECK(signaling_thread()->IsCurrent());
5648 sctp_ready_to_send_data_ = ready;
5649 SignalSctpReadyToSendData(ready);
5650}
5651
5652void PeerConnection::OnSctpTransportDataReceived_n(
5653 const cricket::ReceiveDataParams& params,
5654 const rtc::CopyOnWriteBuffer& payload) {
5655 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5656 RTC_DCHECK(network_thread()->IsCurrent());
5657 // Note: Cannot use rtc::Bind here because it will grab a reference to
5658 // PeerConnection and potentially cause PeerConnection to live longer than
5659 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5660 // be destroyed before PeerConnection is destroyed, and at that point all
5661 // pending tasks will be cleared.
5662 sctp_invoker_->AsyncInvoke<void>(
5663 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5664 OnSctpTransportDataReceived_s(params, payload);
5665 });
5666}
5667
5668void PeerConnection::OnSctpTransportDataReceived_s(
5669 const cricket::ReceiveDataParams& params,
5670 const rtc::CopyOnWriteBuffer& payload) {
5671 RTC_DCHECK(signaling_thread()->IsCurrent());
5672 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5673 // Received OPEN message; parse and signal that a new data channel should
5674 // be created.
5675 std::string label;
5676 InternalDataChannelInit config;
5677 config.id = params.ssrc;
5678 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005679 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5680 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005681 return;
5682 }
5683 config.open_handshake_role = InternalDataChannelInit::kAcker;
5684 OnDataChannelOpenMessage(label, config);
5685 } else {
5686 // Otherwise just forward the signal.
5687 SignalSctpDataReceived(params, payload);
5688 }
5689}
5690
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005691void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005692 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5693 RTC_DCHECK(network_thread()->IsCurrent());
5694 sctp_invoker_->AsyncInvoke<void>(
5695 RTC_FROM_HERE, signaling_thread(),
5696 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005697 &SignalSctpClosingProcedureStartedRemotely, sid));
5698}
5699
5700void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5701 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5702 RTC_DCHECK(network_thread()->IsCurrent());
5703 sctp_invoker_->AsyncInvoke<void>(
5704 RTC_FROM_HERE, signaling_thread(),
5705 rtc::Bind(&sigslot::signal1<int>::operator(),
5706 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005707}
5708
5709// Returns false if bundle is enabled and rtcp_mux is disabled.
5710bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5711 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5712 if (!bundle_enabled)
5713 return true;
5714
5715 const cricket::ContentGroup* bundle_group =
5716 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5717 RTC_DCHECK(bundle_group != NULL);
5718
5719 const cricket::ContentInfos& contents = desc->contents();
5720 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5721 citer != contents.end(); ++citer) {
5722 const cricket::ContentInfo* content = (&*citer);
5723 RTC_DCHECK(content != NULL);
5724 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005725 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005726 if (!HasRtcpMuxEnabled(content))
5727 return false;
5728 }
5729 }
5730 // RTCP-MUX is enabled in all the contents.
5731 return true;
5732}
5733
5734bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005735 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005736}
5737
Steve Anton8a006912017-12-04 15:25:56 -08005738RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005739 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005740 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005741 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005742 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005743 }
5744
5745 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005746 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005747 }
5748
Steve Anton3828c062017-12-06 10:34:51 -08005749 SdpType type = sdesc->GetType();
5750 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5751 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005752 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005753 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005754 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005755 }
5756
5757 // Verify crypto settings.
5758 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005759 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5760 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005761 RTCError crypto_error =
5762 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005763 if (!crypto_error.ok()) {
5764 return crypto_error;
5765 }
Steve Anton75737c02017-11-06 10:37:17 -08005766 }
5767
5768 // Verify ice-ufrag and ice-pwd.
5769 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5771 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005772 }
5773
5774 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005775 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5776 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005777 }
5778
5779 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5780 // m-lines that do not rtcp-mux enabled.
5781
5782 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005783 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005784 // With an answer we want to compare the new answer session description with
5785 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005786 const cricket::SessionDescription* offer_desc =
5787 (source == cricket::CS_LOCAL) ? remote_description()->description()
5788 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005789 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5790 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5791 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005792 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5793 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
5795 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005796 // The re-offers should respect the order of m= sections in current
5797 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005798 // With a re-offer, either the current local or current remote descriptions
5799 // could be the most up to date, so we would like to check against both of
5800 // them if they exist. It could be the case that one of them has a 0 port
5801 // for a media section, but the other does not. This is important to check
5802 // against in the case that we are recycling an m= section.
5803 const cricket::SessionDescription* current_desc = nullptr;
5804 const cricket::SessionDescription* secondary_current_desc = nullptr;
5805 if (local_description()) {
5806 current_desc = local_description()->description();
5807 if (remote_description()) {
5808 secondary_current_desc = remote_description()->description();
5809 }
5810 } else if (remote_description()) {
5811 current_desc = remote_description()->description();
5812 }
Steve Anton75737c02017-11-06 10:37:17 -08005813 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005814 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5815 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005816 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5817 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005818 }
5819 }
5820
Steve Antonba42e992018-04-09 14:10:01 -07005821 if (IsUnifiedPlan()) {
5822 // Ensure that each audio and video media section has at most one
5823 // "StreamParams". This will return an error if receiving a session
5824 // description from a "Plan B" endpoint which adds multiple tracks of the
5825 // same type. With Unified Plan, there can only be at most one track per
5826 // media section.
5827 for (const ContentInfo& content : sdesc->description()->contents()) {
5828 const MediaContentDescription& desc = *content.description;
5829 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5830 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5831 desc.streams().size() > 1u) {
5832 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5833 "Media section has more than one track specified "
5834 "with a=ssrc lines which is not supported with "
5835 "Unified Plan.");
5836 }
5837 }
5838 }
5839
Steve Anton8a006912017-12-04 15:25:56 -08005840 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005841}
5842
Steve Anton3828c062017-12-06 10:34:51 -08005843bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005844 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005845 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005846 return (state == PeerConnectionInterface::kStable) ||
5847 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005848 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005849 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005850 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5851 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5852 }
5853}
5854
Steve Anton3828c062017-12-06 10:34:51 -08005855bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005856 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005857 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005858 return (state == PeerConnectionInterface::kStable) ||
5859 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005860 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005861 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005862 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5863 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5864 }
5865}
5866
Steve Antonf8470812017-12-04 10:46:21 -08005867const char* PeerConnection::SessionErrorToString(SessionError error) const {
5868 switch (error) {
5869 case SessionError::kNone:
5870 return "ERROR_NONE";
5871 case SessionError::kContent:
5872 return "ERROR_CONTENT";
5873 case SessionError::kTransport:
5874 return "ERROR_TRANSPORT";
5875 }
5876 RTC_NOTREACHED();
5877 return "";
5878}
5879
Steve Anton75737c02017-11-06 10:37:17 -08005880std::string PeerConnection::GetSessionErrorMsg() {
5881 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005882 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5883 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005884 return desc.str();
5885}
5886
Steve Anton8e20f172018-03-06 10:55:04 -08005887void PeerConnection::ReportSdpFormatReceived(
5888 const SessionDescriptionInterface& remote_offer) {
5889 if (!uma_observer_) {
5890 return;
5891 }
5892 int num_audio_mlines = 0;
5893 int num_video_mlines = 0;
5894 int num_audio_tracks = 0;
5895 int num_video_tracks = 0;
5896 for (const ContentInfo& content : remote_offer.description()->contents()) {
5897 cricket::MediaType media_type = content.media_description()->type();
5898 int num_tracks = std::max(
5899 1, static_cast<int>(content.media_description()->streams().size()));
5900 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5901 num_audio_mlines += 1;
5902 num_audio_tracks += num_tracks;
5903 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5904 num_video_mlines += 1;
5905 num_video_tracks += num_tracks;
5906 }
5907 }
5908 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5909 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5910 format = kSdpFormatReceivedComplexUnifiedPlan;
5911 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5912 format = kSdpFormatReceivedComplexPlanB;
5913 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5914 format = kSdpFormatReceivedSimple;
5915 }
5916 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5917 kSdpFormatReceivedMax);
5918}
5919
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005920void PeerConnection::NoteUsageEvent(UsageEvent event) {
5921 RTC_DCHECK_RUN_ON(signaling_thread());
5922 usage_event_accumulator_ |= static_cast<int>(event);
5923}
5924
5925void PeerConnection::ReportUsagePattern() const {
5926 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5927 if (uma_observer_) {
5928 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5929 usage_event_accumulator_);
5930 }
5931}
5932
Steve Anton0ffaaa22018-02-23 10:31:30 -08005933void PeerConnection::ReportNegotiatedSdpSemantics(
5934 const SessionDescriptionInterface& answer) {
5935 if (!uma_observer_) {
5936 return;
5937 }
5938 switch (answer.description()->msid_signaling()) {
5939 case 0:
5940 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5941 kSdpSemanticNegotiatedNone,
5942 kSdpSemanticNegotiatedMax);
5943 break;
5944 case cricket::kMsidSignalingMediaSection:
5945 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5946 kSdpSemanticNegotiatedUnifiedPlan,
5947 kSdpSemanticNegotiatedMax);
5948 break;
5949 case cricket::kMsidSignalingSsrcAttribute:
5950 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5951 kSdpSemanticNegotiatedPlanB,
5952 kSdpSemanticNegotiatedMax);
5953 break;
5954 case cricket::kMsidSignalingMediaSection |
5955 cricket::kMsidSignalingSsrcAttribute:
5956 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5957 kSdpSemanticNegotiatedMixed,
5958 kSdpSemanticNegotiatedMax);
5959 break;
5960 default:
5961 RTC_NOTREACHED();
5962 }
5963}
5964
Steve Anton75737c02017-11-06 10:37:17 -08005965// We need to check the local/remote description for the Transport instead of
5966// the session, because a new Transport added during renegotiation may have
5967// them unset while the session has them set from the previous negotiation.
5968// Not doing so may trigger the auto generation of transport description and
5969// mess up DTLS identity information, ICE credential, etc.
5970bool PeerConnection::ReadyToUseRemoteCandidate(
5971 const IceCandidateInterface* candidate,
5972 const SessionDescriptionInterface* remote_desc,
5973 bool* valid) {
5974 *valid = true;
5975
5976 const SessionDescriptionInterface* current_remote_desc =
5977 remote_desc ? remote_desc : remote_description();
5978
5979 if (!current_remote_desc) {
5980 return false;
5981 }
5982
5983 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5984 size_t remote_content_size =
5985 current_remote_desc->description()->contents().size();
5986 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005987 RTC_LOG(LS_ERROR)
5988 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5989 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005990
5991 *valid = false;
5992 return false;
5993 }
5994
5995 cricket::ContentInfo content =
5996 current_remote_desc->description()->contents()[mediacontent_index];
5997
5998 const std::string transport_name = GetTransportName(content.name);
5999 if (transport_name.empty()) {
6000 return false;
6001 }
Zhi Huange830e682018-03-30 10:48:35 -07006002 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006003}
6004
6005bool PeerConnection::SrtpRequired() const {
6006 return dtls_enabled_ ||
6007 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6008}
6009
6010void PeerConnection::OnTransportControllerGatheringState(
6011 cricket::IceGatheringState state) {
6012 RTC_DCHECK(signaling_thread()->IsCurrent());
6013 if (state == cricket::kIceGatheringGathering) {
6014 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6015 } else if (state == cricket::kIceGatheringComplete) {
6016 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6017 }
6018}
6019
6020void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006021 std::map<std::string, std::set<cricket::MediaType>>
6022 media_types_by_transport_name;
6023 for (auto transceiver : transceivers_) {
6024 if (transceiver->internal()->channel()) {
6025 const std::string& transport_name =
6026 transceiver->internal()->channel()->transport_name();
6027 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006028 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006029 }
Steve Anton75737c02017-11-06 10:37:17 -08006030 }
6031 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006032 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6033 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006034 }
Zhi Huange830e682018-03-30 10:48:35 -07006035
6036 rtc::Optional<std::string> transport_name = sctp_transport_name();
6037 if (transport_name) {
6038 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006039 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006040 }
Zhi Huange830e682018-03-30 10:48:35 -07006041
Steve Antonc7b964c2018-02-01 14:39:45 -08006042 for (const auto& entry : media_types_by_transport_name) {
6043 const std::string& transport_name = entry.first;
6044 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006045 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006046 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006047 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006048 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006049 }
6050 }
6051}
6052// Walk through the ConnectionInfos to gather best connection usage
6053// for IPv4 and IPv6.
6054void PeerConnection::ReportBestConnectionState(
6055 const cricket::TransportStats& stats) {
6056 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006057 for (const cricket::TransportChannelStats& channel_stats :
6058 stats.channel_stats) {
6059 for (const cricket::ConnectionInfo& connection_info :
6060 channel_stats.connection_infos) {
6061 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006062 continue;
6063 }
6064
6065 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006066 const cricket::Candidate& local = connection_info.local_candidate;
6067 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006068
6069 // Increment the counter for IceCandidatePairType.
6070 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6071 (local.type() == RELAY_PORT_TYPE &&
6072 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6073 type = kEnumCounterIceCandidatePairTypeTcp;
6074 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6075 type = kEnumCounterIceCandidatePairTypeUdp;
6076 } else {
6077 RTC_CHECK(0);
6078 }
6079 metrics_observer()->IncrementEnumCounter(
6080 type, GetIceCandidatePairCounter(local, remote),
6081 kIceCandidatePairMax);
6082
6083 // Increment the counter for IP type.
6084 if (local.address().family() == AF_INET) {
6085 metrics_observer()->IncrementEnumCounter(
6086 kEnumCounterAddressFamily, kBestConnections_IPv4,
6087 kPeerConnectionAddressFamilyCounter_Max);
6088
6089 } else if (local.address().family() == AF_INET6) {
6090 metrics_observer()->IncrementEnumCounter(
6091 kEnumCounterAddressFamily, kBestConnections_IPv6,
6092 kPeerConnectionAddressFamilyCounter_Max);
6093 } else {
6094 RTC_CHECK(0);
6095 }
6096
6097 return;
6098 }
6099 }
6100}
6101
6102void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006103 const cricket::TransportStats& stats,
6104 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006105 RTC_DCHECK(metrics_observer());
6106 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6107 return;
6108 }
6109
6110 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6111 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6112 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6113 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6114 return;
6115 }
6116
Steve Antonc7b964c2018-02-01 14:39:45 -08006117 for (cricket::MediaType media_type : media_types) {
6118 PeerConnectionEnumCounterType srtp_counter_type;
6119 PeerConnectionEnumCounterType ssl_counter_type;
6120 switch (media_type) {
6121 case cricket::MEDIA_TYPE_AUDIO:
6122 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6123 ssl_counter_type = kEnumCounterAudioSslCipher;
6124 break;
6125 case cricket::MEDIA_TYPE_VIDEO:
6126 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6127 ssl_counter_type = kEnumCounterVideoSslCipher;
6128 break;
6129 case cricket::MEDIA_TYPE_DATA:
6130 srtp_counter_type = kEnumCounterDataSrtpCipher;
6131 ssl_counter_type = kEnumCounterDataSslCipher;
6132 break;
6133 default:
6134 RTC_NOTREACHED();
6135 continue;
6136 }
6137 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6138 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6139 srtp_crypto_suite);
6140 }
6141 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6142 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6143 ssl_cipher_suite);
6144 }
Steve Anton75737c02017-11-06 10:37:17 -08006145 }
6146}
6147
6148void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6149 RTC_DCHECK(worker_thread()->IsCurrent());
6150 RTC_DCHECK(call_);
6151 call_->OnSentPacket(sent_packet);
6152}
6153
6154const std::string PeerConnection::GetTransportName(
6155 const std::string& content_name) {
6156 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006157 if (channel) {
6158 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006159 }
Steve Anton6fec8802017-12-04 10:37:29 -08006160 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006161 RTC_DCHECK(sctp_mid_);
6162 if (content_name == *sctp_mid_) {
6163 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006164 }
6165 }
6166 // Return an empty string if failed to retrieve the transport name.
6167 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006168}
6169
Steve Anton6fec8802017-12-04 10:37:29 -08006170void PeerConnection::DestroyTransceiverChannel(
6171 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6172 transceiver) {
6173 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006174
Steve Anton6fec8802017-12-04 10:37:29 -08006175 cricket::BaseChannel* channel = transceiver->internal()->channel();
6176 if (channel) {
6177 transceiver->internal()->SetChannel(nullptr);
6178 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006179 }
6180}
6181
6182void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006183 if (rtp_data_channel_) {
6184 OnDataChannelDestroyed();
6185 DestroyBaseChannel(rtp_data_channel_);
6186 rtp_data_channel_ = nullptr;
6187 }
6188
6189 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6190 // grab a reference to this PeerConnection. If this is called from the
6191 // PeerConnection destructor, the RefCountedObject vtable will have already
6192 // been destroyed (since it is a subclass of PeerConnection) and using
6193 // rtc::Bind will cause "Pure virtual function called" error to appear.
6194
6195 if (sctp_transport_) {
6196 OnDataChannelDestroyed();
6197 network_thread()->Invoke<void>(RTC_FROM_HERE,
6198 [this] { DestroySctpTransport_n(); });
6199 }
6200}
6201
6202void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6203 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006204 switch (channel->media_type()) {
6205 case cricket::MEDIA_TYPE_AUDIO:
6206 channel_manager()->DestroyVoiceChannel(
6207 static_cast<cricket::VoiceChannel*>(channel));
6208 break;
6209 case cricket::MEDIA_TYPE_VIDEO:
6210 channel_manager()->DestroyVideoChannel(
6211 static_cast<cricket::VideoChannel*>(channel));
6212 break;
6213 case cricket::MEDIA_TYPE_DATA:
6214 channel_manager()->DestroyRtpDataChannel(
6215 static_cast<cricket::RtpDataChannel*>(channel));
6216 break;
6217 default:
6218 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6219 break;
6220 }
Zhi Huange830e682018-03-30 10:48:35 -07006221}
Steve Anton6fec8802017-12-04 10:37:29 -08006222
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006223bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006224 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006225 RtpTransportInternal* rtp_transport,
6226 cricket::DtlsTransportInternal* dtls_transport) {
6227 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006228 auto base_channel = GetChannel(mid);
6229 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006230 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006231 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006232 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006233 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006234 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006235 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006236}
6237
Harald Alvestrand89061872018-01-02 14:08:34 +01006238void PeerConnection::ClearStatsCache() {
6239 if (stats_collector_) {
6240 stats_collector_->ClearCachedStatsReport();
6241 }
6242}
6243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006244} // namespace webrtc