blob: 5526d7266a64979b006cbe52194ee2619c53d0fe [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/jsepicecandidate.h"
21#include "api/jsepsessiondescription.h"
22#include "api/mediaconstraintsinterface.h"
23#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
25#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080026#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020027#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080031#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080037#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080040#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080041#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010048#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020049#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
Steve Anton75737c02017-11-06 10:37:17 -080056using cricket::ContentInfo;
57using cricket::ContentInfos;
58using cricket::MediaContentDescription;
59using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080060using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::TransportInfo;
62
63using cricket::LOCAL_PORT_TYPE;
64using cricket::STUN_PORT_TYPE;
65using cricket::RELAY_PORT_TYPE;
66using cricket::PRFLX_PORT_TYPE;
67
Steve Antonba818672017-11-06 10:21:57 -080068namespace webrtc {
69
Steve Anton75737c02017-11-06 10:37:17 -080070// Error messages
71const char kBundleWithoutRtcpMux[] =
72 "rtcp-mux must be enabled when BUNDLE "
73 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080074const char kInvalidCandidates[] = "Description contains invalid candidates.";
75const char kInvalidSdp[] = "Invalid session description.";
76const char kMlineMismatchInAnswer[] =
77 "The order of m-lines in answer doesn't match order in offer. Rejecting "
78 "answer.";
79const char kMlineMismatchInSubsequentOffer[] =
80 "The order of m-lines in subsequent offer doesn't match order from "
81 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080082const char kSdpWithoutDtlsFingerprint[] =
83 "Called with SDP without DTLS fingerprint.";
84const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
85const char kSdpWithoutIceUfragPwd[] =
86 "Called with SDP without ice-ufrag and ice-pwd.";
87const char kSessionError[] = "Session error code: ";
88const char kSessionErrorDesc[] = "Session error description: ";
89const char kDtlsSrtpSetupFailureRtp[] =
90 "Couldn't set up DTLS-SRTP on RTP channel.";
91const char kDtlsSrtpSetupFailureRtcp[] =
92 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 15:03:05 +0200114 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000116 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100117 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118};
119
deadbeefab9b2d12015-10-14 11:33:11 -0700120struct CreateSessionDescriptionMsg : public rtc::MessageData {
121 explicit CreateSessionDescriptionMsg(
122 webrtc::CreateSessionDescriptionObserver* observer)
123 : observer(observer) {}
124
125 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100126 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700127};
128
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000129struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000130 GetStatsMsg(webrtc::StatsObserver* observer,
131 webrtc::MediaStreamTrackInterface* track)
Yves Gerey665174f2018-06-19 15:03:05 +0200132 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000133 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000134 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000135};
136
deadbeefab9b2d12015-10-14 11:33:11 -0700137// Check if we can send |new_stream| on a PeerConnection.
138bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
139 webrtc::MediaStreamInterface* new_stream) {
140 if (!new_stream || !current_streams) {
141 return false;
142 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700143 if (current_streams->find(new_stream->id()) != nullptr) {
144 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100145 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700146 return false;
147 }
148 return true;
149}
150
deadbeef5e97fb52015-10-15 12:49:08 -0700151// If the direction is "recvonly" or "inactive", treat the description
152// as containing no streams.
153// See: https://code.google.com/p/webrtc/issues/detail?id=5054
154std::vector<cricket::StreamParams> GetActiveStreams(
155 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800156 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700157 ? desc->streams()
158 : std::vector<cricket::StreamParams>();
159}
160
deadbeefab9b2d12015-10-14 11:33:11 -0700161bool IsValidOfferToReceiveMedia(int value) {
162 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
163 return (value >= Options::kUndefined) &&
164 (value <= Options::kMaxOfferToReceiveMedia);
165}
166
zhihuang1c378ed2017-08-17 14:10:50 -0700167// Add options to |[audio/video]_media_description_options| from |senders|.
168void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700169 const std::vector<rtc::scoped_refptr<
170 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700171 cricket::MediaDescriptionOptions* audio_media_description_options,
172 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700173 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700174 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
175 if (audio_media_description_options) {
176 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700177 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700178 }
179 } else {
180 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
181 if (video_media_description_options) {
182 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700186 }
zhihuang1c378ed2017-08-17 14:10:50 -0700187}
olka3c747662017-08-17 06:50:32 -0700188
zhihuang1c378ed2017-08-17 14:10:50 -0700189// Add options to |session_options| from |rtp_data_channels|.
190void AddRtpDataChannelOptions(
191 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
192 rtp_data_channels,
193 cricket::MediaDescriptionOptions* data_media_description_options) {
194 if (!data_media_description_options) {
195 return;
196 }
deadbeefab9b2d12015-10-14 11:33:11 -0700197 // Check for data channels.
198 for (const auto& kv : rtp_data_channels) {
199 const DataChannel* channel = kv.second;
200 if (channel->state() == DataChannel::kConnecting ||
201 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700202 // Legacy RTP data channels are signaled with the track/stream ID set to
203 // the data channel's label.
204 data_media_description_options->AddRtpDataChannel(channel->label(),
205 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700206 }
207 }
208}
209
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700210uint32_t ConvertIceTransportTypeToCandidateFilter(
211 PeerConnectionInterface::IceTransportsType type) {
212 switch (type) {
213 case PeerConnectionInterface::kNone:
214 return cricket::CF_NONE;
215 case PeerConnectionInterface::kRelay:
216 return cricket::CF_RELAY;
217 case PeerConnectionInterface::kNoHost:
218 return (cricket::CF_ALL & ~cricket::CF_HOST);
219 case PeerConnectionInterface::kAll:
220 return cricket::CF_ALL;
221 default:
nissec80e7412017-01-11 05:56:46 -0800222 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700223 }
224 return cricket::CF_NONE;
225}
226
deadbeef293e9262017-01-11 12:28:30 -0800227// Helper to set an error and return from a method.
228bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
229 if (error) {
230 error->set_type(type);
231 }
232 return type == webrtc::RTCErrorType::NONE;
233}
234
Steve Anton038834f2017-07-14 15:59:59 -0700235bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
236 if (error_out) {
237 *error_out = std::move(error);
238 }
239 return error.ok();
240}
241
Steve Antonba818672017-11-06 10:21:57 -0800242std::string GetSignalingStateString(
243 PeerConnectionInterface::SignalingState state) {
244 switch (state) {
245 case PeerConnectionInterface::kStable:
246 return "kStable";
247 case PeerConnectionInterface::kHaveLocalOffer:
248 return "kHaveLocalOffer";
249 case PeerConnectionInterface::kHaveLocalPrAnswer:
250 return "kHavePrAnswer";
251 case PeerConnectionInterface::kHaveRemoteOffer:
252 return "kHaveRemoteOffer";
253 case PeerConnectionInterface::kHaveRemotePrAnswer:
254 return "kHaveRemotePrAnswer";
255 case PeerConnectionInterface::kClosed:
256 return "kClosed";
257 }
258 RTC_NOTREACHED();
259 return "";
260}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700261
Steve Anton75737c02017-11-06 10:37:17 -0800262IceCandidatePairType GetIceCandidatePairCounter(
263 const cricket::Candidate& local,
264 const cricket::Candidate& remote) {
265 const auto& l = local.type();
266 const auto& r = remote.type();
267 const auto& host = LOCAL_PORT_TYPE;
268 const auto& srflx = STUN_PORT_TYPE;
269 const auto& relay = RELAY_PORT_TYPE;
270 const auto& prflx = PRFLX_PORT_TYPE;
271 if (l == host && r == host) {
272 bool local_private = IPIsPrivate(local.address().ipaddr());
273 bool remote_private = IPIsPrivate(remote.address().ipaddr());
274 if (local_private) {
275 if (remote_private) {
276 return kIceCandidatePairHostPrivateHostPrivate;
277 } else {
278 return kIceCandidatePairHostPrivateHostPublic;
279 }
280 } else {
281 if (remote_private) {
282 return kIceCandidatePairHostPublicHostPrivate;
283 } else {
284 return kIceCandidatePairHostPublicHostPublic;
285 }
286 }
287 }
288 if (l == host && r == srflx)
289 return kIceCandidatePairHostSrflx;
290 if (l == host && r == relay)
291 return kIceCandidatePairHostRelay;
292 if (l == host && r == prflx)
293 return kIceCandidatePairHostPrflx;
294 if (l == srflx && r == host)
295 return kIceCandidatePairSrflxHost;
296 if (l == srflx && r == srflx)
297 return kIceCandidatePairSrflxSrflx;
298 if (l == srflx && r == relay)
299 return kIceCandidatePairSrflxRelay;
300 if (l == srflx && r == prflx)
301 return kIceCandidatePairSrflxPrflx;
302 if (l == relay && r == host)
303 return kIceCandidatePairRelayHost;
304 if (l == relay && r == srflx)
305 return kIceCandidatePairRelaySrflx;
306 if (l == relay && r == relay)
307 return kIceCandidatePairRelayRelay;
308 if (l == relay && r == prflx)
309 return kIceCandidatePairRelayPrflx;
310 if (l == prflx && r == host)
311 return kIceCandidatePairPrflxHost;
312 if (l == prflx && r == srflx)
313 return kIceCandidatePairPrflxSrflx;
314 if (l == prflx && r == relay)
315 return kIceCandidatePairPrflxRelay;
316 return kIceCandidatePairMax;
317}
318
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800319// Logic to decide if an m= section can be recycled. This means that the new
320// m= section is not rejected, but the old local or remote m= section is
321// rejected. |old_content_one| and |old_content_two| refer to the m= section
322// of the old remote and old local descriptions in no particular order.
323// We need to check both the old local and remote because either
324// could be the most current from the latest negotation.
325bool IsMediaSectionBeingRecycled(SdpType type,
326 const ContentInfo& content,
327 const ContentInfo* old_content_one,
328 const ContentInfo* old_content_two) {
329 return type == SdpType::kOffer && !content.rejected &&
330 ((old_content_one && old_content_one->rejected) ||
331 (old_content_two && old_content_two->rejected));
332}
333
Steve Anton75737c02017-11-06 10:37:17 -0800334// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800335// |current_desc|. The number of m= sections in |new_desc| should be no
336// less than |current_desc|. In the case of checking an answer's
337// |new_desc|, the |current_desc| is the last offer that was set as the
338// local or remote. In the case of checking an offer's |new_desc| we
339// check against the local and remote descriptions stored from the last
340// negotiation, because either of these could be the most up to date for
341// possible rejected m sections. These are the |current_desc| and
342// |secondary_current_desc|.
343bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
344 const SessionDescription* secondary_current_desc,
345 const SessionDescription& new_desc,
346 const SdpType type) {
347 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800348 return false;
349 }
350
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800351 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
352 const cricket::ContentInfo* secondary_content_info = nullptr;
353 if (secondary_current_desc &&
354 i < secondary_current_desc->contents().size()) {
355 secondary_content_info = &secondary_current_desc->contents()[i];
356 }
357 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
358 &current_desc.contents()[i],
359 secondary_content_info)) {
360 // For new offer descriptions, if the media section can be recycled, it's
361 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800362 continue;
363 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800364 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800365 return false;
366 }
367 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800368 new_desc.contents()[i].media_description();
369 const MediaContentDescription* current_desc_mdesc =
370 current_desc.contents()[i].media_description();
371 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 return false;
373 }
374 }
375 return true;
376}
377
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800378bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
379 const SessionDescription& desc2) {
380 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800381}
382
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100383void NoteKeyProtocolAndMedia(
384 KeyExchangeProtocolType protocol_type,
385 cricket::MediaType media_type,
386 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
387 if (!uma_observer)
388 return;
389 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
390 protocol_type,
391 webrtc::kEnumCounterKeyProtocolMax);
392 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
393 KeyExchangeProtocolMedia>
394 proto_media_counter_map = {
395 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
396 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
398 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
400 kEnumCounterKeyProtocolMediaTypeDtlsData},
401 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
402 kEnumCounterKeyProtocolMediaTypeSdesAudio},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
404 kEnumCounterKeyProtocolMediaTypeSdesVideo},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
406 kEnumCounterKeyProtocolMediaTypeSdesData}};
407
408 auto it = proto_media_counter_map.find({protocol_type, media_type});
409 if (it != proto_media_counter_map.end()) {
410 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
411 it->second,
412 kEnumCounterKeyProtocolMediaTypeMax);
413 }
414}
415
Steve Anton75737c02017-11-06 10:37:17 -0800416// Checks that each non-rejected content has SDES crypto keys or a DTLS
417// fingerprint, unless it's in a BUNDLE group, in which case only the
418// BUNDLE-tag section (first media section/description in the BUNDLE group)
419// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
420// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
421// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100422RTCError VerifyCrypto(const SessionDescription* desc,
423 bool dtls_enabled,
424 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800425 const cricket::ContentGroup* bundle =
426 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800427 for (const cricket::ContentInfo& content_info : desc->contents()) {
428 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800429 continue;
430 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100431 // Note what media is used with each crypto protocol, for all sections.
432 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
433 : webrtc::kEnumCounterKeyProtocolSdes,
434 content_info.media_description()->type(),
435 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800436 const std::string& mid = content_info.name;
437 if (bundle && bundle->HasContentName(mid) &&
438 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 // This isn't the first media section in the BUNDLE group, so it's not
440 // required to have crypto attributes, since only the crypto attributes
441 // from the first section actually get used.
442 continue;
443 }
444
445 // If the content isn't rejected or bundled into another m= section, crypto
446 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800447 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800448 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800449 if (!media || !tinfo) {
450 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800451 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800452 }
453 if (dtls_enabled) {
454 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100455 RTC_LOG(LS_WARNING)
456 << "Session description must have DTLS fingerprint if "
457 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800458 return RTCError(RTCErrorType::INVALID_PARAMETER,
459 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800460 }
461 } else {
462 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100463 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800464 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800465 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800466 }
467 }
468 }
Steve Anton8a006912017-12-04 15:25:56 -0800469 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800470}
471
472// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
473// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
474// media section/description in the BUNDLE group) needs a ufrag and pwd.
475bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
476 const cricket::ContentGroup* bundle =
477 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800478 for (const cricket::ContentInfo& content_info : desc->contents()) {
479 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800480 continue;
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 const std::string& mid = content_info.name;
483 if (bundle && bundle->HasContentName(mid) &&
484 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800485 // This isn't the first media section in the BUNDLE group, so it's not
486 // required to have ufrag/password, since only the ufrag/password from
487 // the first section actually get used.
488 continue;
489 }
490
491 // If the content isn't rejected or bundled into another m= section,
492 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800493 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800494 if (!tinfo) {
495 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100496 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800497 return false;
498 }
499 if (tinfo->description.ice_ufrag.empty() ||
500 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100501 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800502 return false;
503 }
504 }
505 return true;
506}
507
508bool GetTrackIdBySsrc(const SessionDescription* session_description,
509 uint32_t ssrc,
510 std::string* track_id) {
511 RTC_DCHECK(track_id != NULL);
512
Steve Antonb1c1de12017-12-21 15:14:30 -0800513 const cricket::AudioContentDescription* audio_desc =
514 cricket::GetFirstAudioContentDescription(session_description);
515 if (audio_desc) {
516 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800517 if (found) {
518 *track_id = found->id;
519 return true;
520 }
521 }
522
Steve Antonb1c1de12017-12-21 15:14:30 -0800523 const cricket::VideoContentDescription* video_desc =
524 cricket::GetFirstVideoContentDescription(session_description);
525 if (video_desc) {
526 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800527 if (found) {
528 *track_id = found->id;
529 return true;
530 }
531 }
532 return false;
533}
534
535// Get the SCTP port out of a SessionDescription.
536// Return -1 if not found.
537int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800538 const cricket::DataContentDescription* data_desc =
539 GetFirstDataContentDescription(session_description);
540 RTC_DCHECK(data_desc);
541 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800542 return -1;
543 }
Steve Anton75737c02017-11-06 10:37:17 -0800544 std::string value;
545 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
546 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800547 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800548 if (!codec.Matches(match_pattern)) {
549 continue;
550 }
551 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
552 return rtc::FromString<int>(value);
553 }
554 }
555 return -1;
556}
557
Steve Anton75737c02017-11-06 10:37:17 -0800558// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
559bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
560 const SessionDescriptionInterface* new_desc,
561 const std::string& content_name) {
562 if (!old_desc) {
563 return false;
564 }
565 const SessionDescription* new_sd = new_desc->description();
566 const SessionDescription* old_sd = old_desc->description();
567 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
568 if (!cinfo || cinfo->rejected) {
569 return false;
570 }
571 // If the content isn't rejected, check if ufrag and password has changed.
572 const cricket::TransportDescription* new_transport_desc =
573 new_sd->GetTransportDescriptionByName(content_name);
574 const cricket::TransportDescription* old_transport_desc =
575 old_sd->GetTransportDescriptionByName(content_name);
576 if (!new_transport_desc || !old_transport_desc) {
577 // No transport description exists. This is not an ICE restart.
578 return false;
579 }
580 if (cricket::IceCredentialsChanged(
581 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
582 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100583 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
584 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800585 return true;
586 }
587 return false;
588}
589
Steve Anton80dd7b52018-02-16 17:08:42 -0800590// Generates a string error message for SetLocalDescription/SetRemoteDescription
591// from an RTCError.
592std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
593 SdpType type,
594 const RTCError& error) {
595 std::ostringstream oss;
596 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
597 << " " << SdpTypeToString(type) << " sdp: " << error.message();
598 return oss.str();
599}
600
Seth Hampson5b4f0752018-04-02 16:31:36 -0700601std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
602 std::string output = "streams=[";
603 const char* separator = "";
604 for (const auto& stream_id : stream_ids) {
605 output.append(separator).append(stream_id);
606 separator = ", ";
607 }
608 output.append("]");
609 return output;
610}
611
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200612absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700613 int rtc_configuration_parameter) {
614 if (rtc_configuration_parameter ==
615 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200616 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700617 }
618 return rtc_configuration_parameter;
619}
620
Steve Anton75737c02017-11-06 10:37:17 -0800621} // namespace
622
Henrik Boström31638672017-11-23 17:48:32 +0100623// Upon completion, posts a task to execute the callback of the
624// SetSessionDescriptionObserver asynchronously on the same thread. At this
625// point, the state of the peer connection might no longer reflect the effects
626// of the SetRemoteDescription operation, as the peer connection could have been
627// modified during the post.
628// TODO(hbos): Remove this class once we remove the version of
629// PeerConnectionInterface::SetRemoteDescription() that takes a
630// SetSessionDescriptionObserver as an argument.
631class PeerConnection::SetRemoteDescriptionObserverAdapter
632 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
633 public:
634 SetRemoteDescriptionObserverAdapter(
635 rtc::scoped_refptr<PeerConnection> pc,
636 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
637 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
638
639 // SetRemoteDescriptionObserverInterface implementation.
640 void OnSetRemoteDescriptionComplete(RTCError error) override {
641 if (error.ok())
642 pc_->PostSetSessionDescriptionSuccess(wrapper_);
643 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100644 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100645 }
646
647 private:
648 rtc::scoped_refptr<PeerConnection> pc_;
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
650};
651
deadbeef293e9262017-01-11 12:28:30 -0800652bool PeerConnectionInterface::RTCConfiguration::operator==(
653 const PeerConnectionInterface::RTCConfiguration& o) const {
654 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700655 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800656 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000657 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800659 BundlePolicy bundle_policy;
660 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700661 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
662 int ice_candidate_pool_size;
663 bool disable_ipv6;
664 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700665 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100666 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700667 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200668 absl::optional<int> screencast_min_bitrate;
669 absl::optional<bool> combined_audio_video_bwe;
670 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800671 TcpCandidatePolicy tcp_candidate_policy;
672 CandidateNetworkPolicy candidate_network_policy;
673 int audio_jitter_buffer_max_packets;
674 bool audio_jitter_buffer_fast_accelerate;
675 int ice_connection_receiving_timeout;
676 int ice_backup_candidate_pair_ping_interval;
677 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800678 bool prioritize_most_likely_ice_candidate_pairs;
679 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800680 bool prune_turn_ports;
681 bool presume_writable_when_fully_relayed;
682 bool enable_ice_renomination;
683 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200684 absl::optional<int> ice_check_interval_strong_connectivity;
685 absl::optional<int> ice_check_interval_weak_connectivity;
686 absl::optional<int> ice_check_min_interval;
687 absl::optional<int> ice_unwritable_timeout;
688 absl::optional<int> ice_unwritable_min_checks;
689 absl::optional<int> stun_candidate_keepalive_interval;
690 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200691 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800692 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200693 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700694 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800695 };
696 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
697 "Did you add something to RTCConfiguration and forget to "
698 "update operator==?");
699 return type == o.type && servers == o.servers &&
700 bundle_policy == o.bundle_policy &&
701 rtcp_mux_policy == o.rtcp_mux_policy &&
702 tcp_candidate_policy == o.tcp_candidate_policy &&
703 candidate_network_policy == o.candidate_network_policy &&
704 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
705 audio_jitter_buffer_fast_accelerate ==
706 o.audio_jitter_buffer_fast_accelerate &&
707 ice_connection_receiving_timeout ==
708 o.ice_connection_receiving_timeout &&
709 ice_backup_candidate_pair_ping_interval ==
710 o.ice_backup_candidate_pair_ping_interval &&
711 continual_gathering_policy == o.continual_gathering_policy &&
712 certificates == o.certificates &&
713 prioritize_most_likely_ice_candidate_pairs ==
714 o.prioritize_most_likely_ice_candidate_pairs &&
715 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800716 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700717 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100718 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800719 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800720 screencast_min_bitrate == o.screencast_min_bitrate &&
721 combined_audio_video_bwe == o.combined_audio_video_bwe &&
722 enable_dtls_srtp == o.enable_dtls_srtp &&
723 ice_candidate_pool_size == o.ice_candidate_pool_size &&
724 prune_turn_ports == o.prune_turn_ports &&
725 presume_writable_when_fully_relayed ==
726 o.presume_writable_when_fully_relayed &&
727 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800728 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800729 ice_check_interval_strong_connectivity ==
730 o.ice_check_interval_strong_connectivity &&
731 ice_check_interval_weak_connectivity ==
732 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700733 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700734 ice_unwritable_timeout == o.ice_unwritable_timeout &&
735 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800736 stun_candidate_keepalive_interval ==
737 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200738 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800739 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800740 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700741 network_preference == o.network_preference &&
742 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800743}
744
745bool PeerConnectionInterface::RTCConfiguration::operator!=(
746 const PeerConnectionInterface::RTCConfiguration& o) const {
747 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800748}
749
zhihuang8f65cdf2016-05-06 18:40:30 -0700750// Generate a RTCP CNAME when a PeerConnection is created.
751std::string GenerateRtcpCname() {
752 std::string cname;
753 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100754 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800755 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700756 }
757 return cname;
758}
759
zhihuang1c378ed2017-08-17 14:10:50 -0700760bool ValidateOfferAnswerOptions(
761 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
762 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
763 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700764}
765
zhihuang1c378ed2017-08-17 14:10:50 -0700766// From |rtc_options|, fill parts of |session_options| shared by all generated
767// m= sections (in other words, nothing that involves a map/array).
768void ExtractSharedMediaSessionOptions(
769 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
770 cricket::MediaSessionOptions* session_options) {
771 session_options->vad_enabled = rtc_options.voice_activity_detection;
772 session_options->bundle_enabled = rtc_options.use_rtp_mux;
773}
zhihuanga77e6bb2017-08-14 18:17:48 -0700774
zhihuang1c378ed2017-08-17 14:10:50 -0700775bool ConvertConstraintsToOfferAnswerOptions(
776 const MediaConstraintsInterface* constraints,
777 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700778 if (!constraints) {
779 return true;
780 }
zhihuang1c378ed2017-08-17 14:10:50 -0700781
782 bool value = false;
783 size_t mandatory_constraints_satisfied = 0;
784
785 if (FindConstraint(constraints,
786 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
787 &mandatory_constraints_satisfied)) {
788 offer_answer_options->offer_to_receive_audio =
789 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
790 kOfferToReceiveMediaTrue
791 : 0;
792 }
793
794 if (FindConstraint(constraints,
795 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
796 &mandatory_constraints_satisfied)) {
797 offer_answer_options->offer_to_receive_video =
798 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
799 kOfferToReceiveMediaTrue
800 : 0;
801 }
802 if (FindConstraint(constraints,
803 MediaConstraintsInterface::kVoiceActivityDetection, &value,
804 &mandatory_constraints_satisfied)) {
805 offer_answer_options->voice_activity_detection = value;
806 }
807 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
808 &mandatory_constraints_satisfied)) {
809 offer_answer_options->use_rtp_mux = value;
810 }
811 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
812 &value, &mandatory_constraints_satisfied)) {
813 offer_answer_options->ice_restart = value;
814 }
815
deadbeefab9b2d12015-10-14 11:33:11 -0700816 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
817}
818
zhihuang38ede132017-06-15 12:52:32 -0700819PeerConnection::PeerConnection(PeerConnectionFactory* factory,
820 std::unique_ptr<RtcEventLog> event_log,
821 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700823 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700824 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700825 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700826 remote_streams_(StreamCollection::Create()),
827 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828
829PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800831 RTC_DCHECK_RUN_ON(signaling_thread());
832
Steve Anton8af21862017-12-15 11:20:13 -0800833 // Need to stop transceivers before destroying the stats collector because
834 // AudioRtpSender has a reference to the StatsCollector it will update when
835 // stopping.
836 for (auto transceiver : transceivers_) {
837 transceiver->Stop();
838 }
Steve Anton4171afb2017-11-20 10:20:22 -0800839
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700840 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800841 if (stats_collector_) {
842 stats_collector_->WaitForPendingRequest();
843 stats_collector_ = nullptr;
844 }
Steve Anton75737c02017-11-06 10:37:17 -0800845
Steve Anton8af21862017-12-15 11:20:13 -0800846 // Don't destroy BaseChannels until after stats has been cleaned up so that
847 // the last stats request can still read from the channels.
848 DestroyAllChannels();
849
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800851
852 webrtc_session_desc_factory_.reset();
853 sctp_invoker_.reset();
854 sctp_factory_.reset();
855 transport_controller_.reset();
856
deadbeef91dd5672016-05-18 16:55:30 -0700857 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700858 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700859 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700860 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700861 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700862 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800863 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700864 event_log_.reset();
865 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866}
867
Steve Anton8af21862017-12-15 11:20:13 -0800868void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800869 // Destroy video channels first since they may have a pointer to a voice
870 // channel.
871 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800872 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800873 DestroyTransceiverChannel(transceiver);
874 }
875 }
876 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800877 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800878 DestroyTransceiverChannel(transceiver);
879 }
880 }
881 DestroyDataChannel();
882}
883
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000885 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700886 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100887 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700888
889 RTCError config_error = ValidateConfiguration(configuration);
890 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100891 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700892 return false;
893 }
894
Benjamin Wrightcab58882018-05-02 15:12:47 -0700895 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100896 RTC_LOG(LS_ERROR)
897 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100898 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800899 return false;
900 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200901
Benjamin Wrightcab58882018-05-02 15:12:47 -0700902 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800903 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100905 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800906 return false;
907 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700908
Benjamin Wrightcab58882018-05-02 15:12:47 -0700909 observer_ = dependencies.observer;
910 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700911 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800912
deadbeef91dd5672016-05-18 16:55:30 -0700913 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700914 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700915 if (!network_thread()->Invoke<bool>(
916 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
917 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 return false;
919 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920
Zhi Huange830e682018-03-30 10:48:35 -0700921 const PeerConnectionFactoryInterface::Options& options = factory_->options();
922
Steve Anton75737c02017-11-06 10:37:17 -0800923 // RFC 3264: The numeric value of the session id and version in the
924 // o line MUST be representable with a "64 bit signed integer".
925 // Due to this constraint session id |session_id_| is max limited to
926 // LLONG_MAX.
927 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700928 JsepTransportController::Config config;
929 config.redetermine_role_on_ice_restart =
930 configuration.redetermine_role_on_ice_restart;
931 config.ssl_max_version = factory_->options().ssl_max_version;
932 config.disable_encryption = options.disable_encryption;
933 config.bundle_policy = configuration.bundle_policy;
934 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
935 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700936 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700937 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700938#if defined(ENABLE_EXTERNAL_AUTH)
939 config.enable_external_auth = true;
940#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700941 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700942 transport_controller_.reset(new JsepTransportController(
943 signaling_thread(), network_thread(), port_allocator_.get(), config));
944 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800945 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700946 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800947 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700948 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800949 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700950 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800951 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
952 transport_controller_->SignalDtlsHandshakeError.connect(
953 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
954
955 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700956
deadbeefab9b2d12015-10-14 11:33:11 -0700957 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700958 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000959
Steve Antonba818672017-11-06 10:21:57 -0800960 configuration_ = configuration;
961
Steve Anton75737c02017-11-06 10:37:17 -0800962 // Obtain a certificate from RTCConfiguration if any were provided (optional).
963 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
964 if (!configuration.certificates.empty()) {
965 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
966 // just picking the first one. The decision should be made based on the DTLS
967 // handshake. The DTLS negotiations need to know about all certificates.
968 certificate = configuration.certificates[0];
969 }
970
Steve Antond25da372017-11-06 14:50:29 -0800971 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800972
973 if (options.disable_encryption) {
974 dtls_enabled_ = false;
975 } else {
976 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700977 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800978 // |configuration| can override the default |dtls_enabled_| value.
979 if (configuration.enable_dtls_srtp) {
980 dtls_enabled_ = *(configuration.enable_dtls_srtp);
981 }
982 }
983
984 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
985 // It takes precendence over the disable_sctp_data_channels
986 // PeerConnectionFactoryInterface::Options.
987 if (configuration.enable_rtp_data_channel) {
988 data_channel_type_ = cricket::DCT_RTP;
989 } else {
990 // DTLS has to be enabled to use SCTP.
991 if (!options.disable_sctp_data_channels && dtls_enabled_) {
992 data_channel_type_ = cricket::DCT_SCTP;
993 }
994 }
995
996 video_options_.screencast_min_bitrate_kbps =
997 configuration.screencast_min_bitrate;
998 audio_options_.combined_audio_video_bwe =
999 configuration.combined_audio_video_bwe;
1000
1001 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001002 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001003
1004 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001005 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001006
1007 // Whether the certificate generator/certificate is null or not determines
1008 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1009 // the right instructions by clearing the variables if needed.
1010 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001011 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001012 certificate = nullptr;
1013 } else if (certificate) {
1014 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001015 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001016 }
1017
1018 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1019 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001020 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001021 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1022 this, &PeerConnection::OnCertificateReady);
1023
1024 if (options.disable_encryption) {
1025 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1026 }
1027
1028 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1029 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030
Steve Anton4171afb2017-11-20 10:20:22 -08001031 // Add default audio/video transceivers for Plan B SDP.
1032 if (!IsUnifiedPlan()) {
1033 transceivers_.push_back(
1034 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1035 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1036 transceivers_.push_back(
1037 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1038 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1039 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001040 return true;
1041}
1042
Steve Anton038834f2017-07-14 15:59:59 -07001043RTCError PeerConnection::ValidateConfiguration(
1044 const RTCConfiguration& config) const {
1045 if (config.ice_regather_interval_range &&
1046 config.continual_gathering_policy == GATHER_ONCE) {
1047 return RTCError(RTCErrorType::INVALID_PARAMETER,
1048 "ice_regather_interval_range specified but continual "
1049 "gathering policy is GATHER_ONCE");
1050 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001051 auto result =
1052 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1053 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001054}
1055
Yves Gerey665174f2018-06-19 15:03:05 +02001056rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001057 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1058 "Plan SdpSemantics. Please use GetSenders "
1059 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001060 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061}
1062
Yves Gerey665174f2018-06-19 15:03:05 +02001063rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001064 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1065 "Plan SdpSemantics. Please use GetReceivers "
1066 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001067 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068}
1069
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001070bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001071 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1072 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001073 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001074 if (IsClosed()) {
1075 return false;
1076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 return false;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080
1081 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001082 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1083 observer->SignalAudioTrackAdded.connect(this,
1084 &PeerConnection::OnAudioTrackAdded);
1085 observer->SignalAudioTrackRemoved.connect(
1086 this, &PeerConnection::OnAudioTrackRemoved);
1087 observer->SignalVideoTrackAdded.connect(this,
1088 &PeerConnection::OnVideoTrackAdded);
1089 observer->SignalVideoTrackRemoved.connect(
1090 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001091 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001092
deadbeefab9b2d12015-10-14 11:33:11 -07001093 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001094 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001095 }
1096 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001097 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001100 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 observer_->OnRenegotiationNeeded();
1102 return true;
1103}
1104
1105void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001106 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1107 "Plan SdpSemantics. Please use RemoveTrack "
1108 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001109 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001110 if (!IsClosed()) {
1111 for (const auto& track : local_stream->GetAudioTracks()) {
1112 RemoveAudioTrack(track.get(), local_stream);
1113 }
1114 for (const auto& track : local_stream->GetVideoTracks()) {
1115 RemoveVideoTrack(track.get(), local_stream);
1116 }
deadbeefab9b2d12015-10-14 11:33:11 -07001117 }
deadbeefab9b2d12015-10-14 11:33:11 -07001118 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001119 stream_observers_.erase(
1120 std::remove_if(
1121 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001122 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001123 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001124 }),
1125 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001126
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127 if (IsClosed()) {
1128 return;
1129 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 observer_->OnRenegotiationNeeded();
1131}
1132
deadbeefe1f9d832016-01-14 15:35:42 -08001133rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1134 MediaStreamTrackInterface* track,
1135 std::vector<MediaStreamInterface*> streams) {
1136 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001137 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001138 for (auto* stream : streams) {
1139 if (!stream) {
1140 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1141 return nullptr;
1142 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001143 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001144 }
Seth Hampson845e8782018-03-02 11:34:10 -08001145 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001146 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001147 return nullptr;
1148 }
Steve Antonf9381f02017-12-14 10:23:57 -08001149 return sender_or_error.MoveValue();
1150}
1151
Steve Anton2d6c76a2018-01-05 17:10:52 -08001152RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001153 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001154 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001155 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001156 if (!track) {
1157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1158 }
1159 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1160 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1162 "Track has invalid kind: " + track->kind());
1163 }
Steve Antonf9381f02017-12-14 10:23:57 -08001164 if (IsClosed()) {
1165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1166 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001167 }
Steve Anton4171afb2017-11-20 10:20:22 -08001168 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001169 LOG_AND_RETURN_ERROR(
1170 RTCErrorType::INVALID_PARAMETER,
1171 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001172 }
Steve Antonf9381f02017-12-14 10:23:57 -08001173 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001174 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1175 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001176 if (sender_or_error.ok()) {
1177 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001178 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001179 }
1180 return sender_or_error;
1181}
deadbeefe1f9d832016-01-14 15:35:42 -08001182
Steve Antonf9381f02017-12-14 10:23:57 -08001183RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1184PeerConnection::AddTrackPlanB(
1185 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001186 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001187 if (stream_ids.size() > 1u) {
1188 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1189 "AddTrack with more than one stream is not "
1190 "supported with Plan B semantics.");
1191 }
1192 std::vector<std::string> adjusted_stream_ids = stream_ids;
1193 if (adjusted_stream_ids.empty()) {
1194 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1195 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001196 cricket::MediaType media_type =
1197 (track->kind() == MediaStreamTrackInterface::kAudioKind
1198 ? cricket::MEDIA_TYPE_AUDIO
1199 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001200 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001201 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001202 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001203 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001204 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001205 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001206 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001207 if (sender_info) {
1208 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001209 }
Steve Antonf9381f02017-12-14 10:23:57 -08001210 } else {
1211 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001212 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001213 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001214 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001215 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001216 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001217 if (sender_info) {
1218 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001219 }
deadbeefe1f9d832016-01-14 15:35:42 -08001220 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001221 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001222}
deadbeefe1f9d832016-01-14 15:35:42 -08001223
Steve Antonf9381f02017-12-14 10:23:57 -08001224RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1225PeerConnection::AddTrackUnifiedPlan(
1226 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001227 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001228 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1229 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001230 RTC_LOG(LS_INFO) << "Reusing an existing "
1231 << cricket::MediaTypeToString(transceiver->media_type())
1232 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001233 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001234 transceiver->internal()->set_direction(
1235 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001236 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001239 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001240 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001241 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001242 } else {
1243 cricket::MediaType media_type =
1244 (track->kind() == MediaStreamTrackInterface::kAudioKind
1245 ? cricket::MEDIA_TYPE_AUDIO
1246 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001247 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1248 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001249 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001250 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1251 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001252 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001253 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001254 }
Steve Antonf9381f02017-12-14 10:23:57 -08001255 return transceiver->sender();
1256}
1257
1258rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1259PeerConnection::FindFirstTransceiverForAddedTrack(
1260 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1261 RTC_DCHECK(track);
1262 for (auto transceiver : transceivers_) {
1263 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001264 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001265 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001266 !transceiver->internal()->has_ever_been_used_to_send() &&
1267 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001268 return transceiver;
1269 }
1270 }
1271 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001272}
1273
1274bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1275 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001276 return RemoveTrackInternal(sender).ok();
1277}
1278
1279RTCError PeerConnection::RemoveTrackInternal(
1280 rtc::scoped_refptr<RtpSenderInterface> sender) {
1281 if (!sender) {
1282 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1283 }
deadbeefe1f9d832016-01-14 15:35:42 -08001284 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1286 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001287 }
Steve Antonf9381f02017-12-14 10:23:57 -08001288 if (IsUnifiedPlan()) {
1289 auto transceiver = FindTransceiverBySender(sender);
1290 if (!transceiver || !sender->track()) {
1291 return RTCError::OK();
1292 }
1293 sender->SetTrack(nullptr);
1294 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001295 transceiver->internal()->set_direction(
1296 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001297 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001300 }
Steve Anton4171afb2017-11-20 10:20:22 -08001301 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001302 bool removed;
1303 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1304 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1305 } else {
1306 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1307 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1308 }
1309 if (!removed) {
1310 LOG_AND_RETURN_ERROR(
1311 RTCErrorType::INVALID_PARAMETER,
1312 "Couldn't find sender " + sender->id() + " to remove.");
1313 }
Steve Anton4171afb2017-11-20 10:20:22 -08001314 }
deadbeefe1f9d832016-01-14 15:35:42 -08001315 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001316 return RTCError::OK();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindTransceiverBySender(
1321 rtc::scoped_refptr<RtpSenderInterface> sender) {
1322 for (auto transceiver : transceivers_) {
1323 if (transceiver->sender() == sender) {
1324 return transceiver;
1325 }
1326 }
1327 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001328}
1329
Steve Anton9158ef62017-11-27 13:01:52 -08001330RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1331PeerConnection::AddTransceiver(
1332 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1333 return AddTransceiver(track, RtpTransceiverInit());
1334}
1335
1336RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1337PeerConnection::AddTransceiver(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1339 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001340 RTC_CHECK(IsUnifiedPlan())
1341 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001342 if (!track) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1344 }
1345 cricket::MediaType media_type;
1346 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1347 media_type = cricket::MEDIA_TYPE_AUDIO;
1348 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1349 media_type = cricket::MEDIA_TYPE_VIDEO;
1350 } else {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1352 "Track kind is not audio or video");
1353 }
1354 return AddTransceiver(media_type, track, init);
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1359 return AddTransceiver(media_type, RtpTransceiverInit());
1360}
1361
1362RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1363PeerConnection::AddTransceiver(cricket::MediaType media_type,
1364 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001365 RTC_CHECK(IsUnifiedPlan())
1366 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001367 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1368 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1370 "media type is not audio or video");
1371 }
1372 return AddTransceiver(media_type, nullptr, init);
1373}
1374
1375RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1376PeerConnection::AddTransceiver(
1377 cricket::MediaType media_type,
1378 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001379 const RtpTransceiverInit& init,
1380 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001381 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1382 media_type == cricket::MEDIA_TYPE_VIDEO));
1383 if (track) {
1384 RTC_DCHECK_EQ(media_type,
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind
1386 ? cricket::MEDIA_TYPE_AUDIO
1387 : cricket::MEDIA_TYPE_VIDEO));
1388 }
1389
1390 // TODO(bugs.webrtc.org/7600): Verify init.
1391
Steve Anton3d954a62018-04-02 11:27:23 -07001392 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1393 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001394 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1396 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1397 transceiver->internal()->set_direction(init.direction);
1398
Steve Anton22da89f2018-01-25 13:58:07 -08001399 if (fire_callback) {
1400 observer_->OnRenegotiationNeeded();
1401 }
Steve Antonf9381f02017-12-14 10:23:57 -08001402
1403 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1404}
1405
Steve Anton02ee47c2018-01-10 16:26:06 -08001406rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1407PeerConnection::CreateSender(
1408 cricket::MediaType media_type,
1409 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001410 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001411 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001412 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1413 RTC_DCHECK(!track ||
1414 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1415 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1416 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001417 new AudioRtpSender(worker_thread(),
1418 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001419 stream_ids, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001420 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001421 } else {
1422 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1423 RTC_DCHECK(!track ||
1424 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1425 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1426 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001427 new VideoRtpSender(worker_thread(),
1428 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001429 stream_ids));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001430 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001432 return sender;
1433}
1434
1435rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1436PeerConnection::CreateReceiver(cricket::MediaType media_type,
1437 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001438 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1439 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001440 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001441 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001442 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001443 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001444 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001445 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001446 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001447 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1448 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001449 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001450 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001451 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001452 return receiver;
1453}
1454
1455rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1456PeerConnection::CreateAndAddTransceiver(
1457 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1458 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1459 receiver) {
1460 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1461 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001462 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001463 transceiver->internal()->SignalNegotiationNeeded.connect(
1464 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001465 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001466}
1467
Steve Anton52d86772018-02-20 15:48:12 -08001468void PeerConnection::OnNegotiationNeeded() {
1469 RTC_DCHECK_RUN_ON(signaling_thread());
1470 RTC_DCHECK(!IsClosed());
1471 observer_->OnRenegotiationNeeded();
1472}
1473
deadbeeffac06552015-11-25 11:26:01 -08001474rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001475 const std::string& kind,
1476 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001477 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1478 "Plan SdpSemantics. Please use AddTransceiver "
1479 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001480 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001481 if (IsClosed()) {
1482 return nullptr;
1483 }
Steve Anton4171afb2017-11-20 10:20:22 -08001484
Seth Hampson5b4f0752018-04-02 16:31:36 -07001485 // Internally we need to have one stream with Plan B semantics, so we
1486 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001487 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001488 if (stream_id.empty()) {
1489 stream_ids.push_back(rtc::CreateRandomUuid());
1490 RTC_LOG(LS_INFO)
1491 << "No stream_id specified for sender. Generated stream ID: "
1492 << stream_ids[0];
1493 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001494 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001495 }
1496
Steve Anton4171afb2017-11-20 10:20:22 -08001497 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001498 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001499 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001500 auto* audio_sender =
1501 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001502 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001503 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001504 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001505 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001506 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001507 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001508 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001509 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001510 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001511 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001512 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001513 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001514 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001515 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001516 }
Steve Anton4171afb2017-11-20 10:20:22 -08001517
deadbeefe1f9d832016-01-14 15:35:42 -08001518 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001519}
1520
deadbeef70ab1a12015-09-28 16:53:55 -07001521std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1522 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001523 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001524 for (auto sender : GetSendersInternal()) {
1525 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001526 }
1527 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001528}
1529
Steve Anton4171afb2017-11-20 10:20:22 -08001530std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1531PeerConnection::GetSendersInternal() const {
1532 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1533 all_senders;
1534 for (auto transceiver : transceivers_) {
1535 auto senders = transceiver->internal()->senders();
1536 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1537 }
1538 return all_senders;
1539}
1540
deadbeef70ab1a12015-09-28 16:53:55 -07001541std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1542PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001543 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001544 for (const auto& receiver : GetReceiversInternal()) {
1545 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001546 }
1547 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001548}
1549
Steve Anton4171afb2017-11-20 10:20:22 -08001550std::vector<
1551 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1552PeerConnection::GetReceiversInternal() const {
1553 std::vector<
1554 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1555 all_receivers;
1556 for (auto transceiver : transceivers_) {
1557 auto receivers = transceiver->internal()->receivers();
1558 all_receivers.insert(all_receivers.end(), receivers.begin(),
1559 receivers.end());
1560 }
1561 return all_receivers;
1562}
1563
Steve Anton9158ef62017-11-27 13:01:52 -08001564std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1565PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001566 RTC_CHECK(IsUnifiedPlan())
1567 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001568 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1569 for (auto transceiver : transceivers_) {
1570 all_transceivers.push_back(transceiver);
1571 }
1572 return all_transceivers;
1573}
1574
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001575bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001576 MediaStreamTrackInterface* track,
1577 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001578 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001579 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001580 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001581 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001582 return false;
1583 }
1584
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001585 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001586 // The StatsCollector is used to tell if a track is valid because it may
1587 // remember tracks that the PeerConnection previously removed.
1588 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001589 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1590 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001591 return false;
1592 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001593 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001594 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001595 return true;
1596}
1597
hbos74e1a4f2016-09-15 23:33:01 -07001598void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001599 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001600 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001601 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001602 stats_collector_->GetStatsReport(callback);
1603}
1604
Henrik Boström1df1bf82018-03-20 13:24:20 +01001605void PeerConnection::GetStats(
1606 rtc::scoped_refptr<RtpSenderInterface> selector,
1607 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1608 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1609 RTC_DCHECK(callback);
1610 RTC_DCHECK(stats_collector_);
1611 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1612 if (selector) {
1613 for (const auto& proxy_transceiver : transceivers_) {
1614 for (const auto& proxy_sender :
1615 proxy_transceiver->internal()->senders()) {
1616 if (proxy_sender == selector) {
1617 internal_sender = proxy_sender->internal();
1618 break;
1619 }
1620 }
1621 if (internal_sender)
1622 break;
1623 }
1624 }
1625 // If there is no |internal_sender| then |selector| is either null or does not
1626 // belong to the PeerConnection (in Plan B, senders can be removed from the
1627 // PeerConnection). This means that "all the stats objects representing the
1628 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1629 // produces an empty stats report.
1630 stats_collector_->GetStatsReport(internal_sender, callback);
1631}
1632
1633void PeerConnection::GetStats(
1634 rtc::scoped_refptr<RtpReceiverInterface> selector,
1635 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1636 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1637 RTC_DCHECK(callback);
1638 RTC_DCHECK(stats_collector_);
1639 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1640 if (selector) {
1641 for (const auto& proxy_transceiver : transceivers_) {
1642 for (const auto& proxy_receiver :
1643 proxy_transceiver->internal()->receivers()) {
1644 if (proxy_receiver == selector) {
1645 internal_receiver = proxy_receiver->internal();
1646 break;
1647 }
1648 }
1649 if (internal_receiver)
1650 break;
1651 }
1652 }
1653 // If there is no |internal_receiver| then |selector| is either null or does
1654 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1655 // the PeerConnection). This means that "all the stats objects representing
1656 // the selector" is an empty set. Invoking GetStatsReport() with a null
1657 // selector produces an empty stats report.
1658 stats_collector_->GetStatsReport(internal_receiver, callback);
1659}
1660
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001661PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1662 return signaling_state_;
1663}
1664
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001665PeerConnectionInterface::IceConnectionState
1666PeerConnection::ice_connection_state() {
1667 return ice_connection_state_;
1668}
1669
1670PeerConnectionInterface::IceGatheringState
1671PeerConnection::ice_gathering_state() {
1672 return ice_gathering_state_;
1673}
1674
Yves Gerey665174f2018-06-19 15:03:05 +02001675rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676 const std::string& label,
1677 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001678 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001679
deadbeefab9b2d12015-10-14 11:33:11 -07001680 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001681
kwibergd1fe2812016-04-27 06:47:29 -07001682 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001683 if (config) {
1684 internal_config.reset(new InternalDataChannelInit(*config));
1685 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001686 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001687 InternalCreateDataChannel(label, internal_config.get()));
1688 if (!channel.get()) {
1689 return nullptr;
1690 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001691
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001692 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1693 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001694 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001695 observer_->OnRenegotiationNeeded();
1696 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001697 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001698 return DataChannelProxy::Create(signaling_thread(), channel.get());
1699}
1700
1701void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1702 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001703 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001704
zhihuang1c378ed2017-08-17 14:10:50 -07001705 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1706 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1707 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1708 // compares the mandatory fields parsed with the mandatory fields added in the
1709 // |constraints| and some downstream applications might create offers with
1710 // mandatory fields which would not be parsed in the helper method. For
1711 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1712 // |constraints| as a mandatory field but it is not parsed.
1713 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001714
zhihuang1c378ed2017-08-17 14:10:50 -07001715 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001716}
1717
1718void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1719 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001720 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001721
nisse7ce109a2017-01-31 00:57:56 -08001722 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001723 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001724 return;
1725 }
deadbeefab9b2d12015-10-14 11:33:11 -07001726
Steve Anton8d3444d2017-10-20 15:30:51 -07001727 if (IsClosed()) {
1728 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001729 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001730 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001731 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001732 return;
1733 }
1734
zhihuang1c378ed2017-08-17 14:10:50 -07001735 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001736 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001737 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001738 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001739 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001740 return;
1741 }
1742
Steve Anton22da89f2018-01-25 13:58:07 -08001743 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1744 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1745 if (IsUnifiedPlan()) {
1746 RTCError error = HandleLegacyOfferOptions(options);
1747 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001748 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001749 return;
1750 }
1751 }
1752
zhihuang1c378ed2017-08-17 14:10:50 -07001753 cricket::MediaSessionOptions session_options;
1754 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001755 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756}
1757
Steve Anton22da89f2018-01-25 13:58:07 -08001758RTCError PeerConnection::HandleLegacyOfferOptions(
1759 const RTCOfferAnswerOptions& options) {
1760 RTC_DCHECK(IsUnifiedPlan());
1761
1762 if (options.offer_to_receive_audio == 0) {
1763 RemoveRecvDirectionFromReceivingTransceiversOfType(
1764 cricket::MEDIA_TYPE_AUDIO);
1765 } else if (options.offer_to_receive_audio == 1) {
1766 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1767 } else if (options.offer_to_receive_audio > 1) {
1768 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1769 "offer_to_receive_audio > 1 is not supported.");
1770 }
1771
1772 if (options.offer_to_receive_video == 0) {
1773 RemoveRecvDirectionFromReceivingTransceiversOfType(
1774 cricket::MEDIA_TYPE_VIDEO);
1775 } else if (options.offer_to_receive_video == 1) {
1776 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1777 } else if (options.offer_to_receive_video > 1) {
1778 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1779 "offer_to_receive_video > 1 is not supported.");
1780 }
1781
1782 return RTCError::OK();
1783}
1784
1785void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1786 cricket::MediaType media_type) {
1787 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001788 RtpTransceiverDirection new_direction =
1789 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1790 if (new_direction != transceiver->direction()) {
1791 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1792 << " transceiver (MID="
1793 << transceiver->mid().value_or("<not set>") << ") from "
1794 << RtpTransceiverDirectionToString(
1795 transceiver->direction())
1796 << " to "
1797 << RtpTransceiverDirectionToString(new_direction)
1798 << " since CreateOffer specified offer_to_receive=0";
1799 transceiver->internal()->set_direction(new_direction);
1800 }
Steve Anton22da89f2018-01-25 13:58:07 -08001801 }
1802}
1803
1804void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1805 cricket::MediaType media_type) {
1806 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001807 RTC_LOG(LS_INFO)
1808 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1809 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001810 RtpTransceiverInit init;
1811 init.direction = RtpTransceiverDirection::kRecvOnly;
1812 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1813 }
1814}
1815
1816std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1817PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1818 std::vector<
1819 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1820 receiving_transceivers;
1821 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001822 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001823 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1824 receiving_transceivers.push_back(transceiver);
1825 }
1826 }
1827 return receiving_transceivers;
1828}
1829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001830void PeerConnection::CreateAnswer(
1831 CreateSessionDescriptionObserver* observer,
1832 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001833 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001834
nisse7ce109a2017-01-31 00:57:56 -08001835 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001836 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837 return;
1838 }
deadbeefab9b2d12015-10-14 11:33:11 -07001839
zhihuang1c378ed2017-08-17 14:10:50 -07001840 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1841 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1842 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001843 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001844 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001845 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001846 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001847 return;
1848 }
1849
Steve Anton8d3444d2017-10-20 15:30:51 -07001850 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001851}
1852
1853void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1854 const RTCOfferAnswerOptions& options) {
1855 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001856 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001857 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001858 return;
1859 }
1860
Steve Antondffead82018-02-06 10:31:29 -08001861 if (!(signaling_state_ == kHaveRemoteOffer ||
1862 signaling_state_ == kHaveLocalPrAnswer)) {
1863 std::string error =
1864 "PeerConnection cannot create an answer in a state other than "
1865 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001866 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001867 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001868 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001869 return;
1870 }
1871
Steve Antondffead82018-02-06 10:31:29 -08001872 // The remote description should be set if we're in the right state.
1873 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001874
Steve Anton22da89f2018-01-25 13:58:07 -08001875 if (IsUnifiedPlan()) {
1876 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1877 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1878 "supported with Unified Plan semantics. Use the "
1879 "RtpTransceiver API instead.";
1880 }
1881 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1882 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1883 "supported with Unified Plan semantics. Use the "
1884 "RtpTransceiver API instead.";
1885 }
1886 }
1887
htaa2a49d92016-03-04 02:51:39 -08001888 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001889 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001890
Steve Antond25da372017-11-06 14:50:29 -08001891 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892}
1893
1894void PeerConnection::SetLocalDescription(
1895 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001896 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001897 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001898
Steve Anton80dd7b52018-02-16 17:08:42 -08001899 // The SetLocalDescription contract is that we take ownership of the session
1900 // description regardless of the outcome, so wrap it in a unique_ptr right
1901 // away. Ideally, SetLocalDescription's signature will be changed to take the
1902 // description as a unique_ptr argument to formalize this agreement.
1903 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1904
nisse7ce109a2017-01-31 00:57:56 -08001905 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001906 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907 return;
1908 }
Steve Anton8a006912017-12-04 15:25:56 -08001909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001911 PostSetSessionDescriptionFailure(
1912 observer,
1913 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914 return;
1915 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001916
Steve Anton80dd7b52018-02-16 17:08:42 -08001917 // If a session error has occurred the PeerConnection is in a possibly
1918 // inconsistent state so fail right away.
1919 if (session_error() != SessionError::kNone) {
1920 std::string error_message = GetSessionErrorMsg();
1921 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001922 PostSetSessionDescriptionFailure(
1923 observer,
1924 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001925 return;
1926 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001927
Steve Anton80dd7b52018-02-16 17:08:42 -08001928 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1929 if (!error.ok()) {
1930 std::string error_message = GetSetDescriptionErrorMessage(
1931 cricket::CS_LOCAL, desc->GetType(), error);
1932 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001933 PostSetSessionDescriptionFailure(
1934 observer,
1935 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001936 return;
1937 }
1938
1939 // Grab the description type before moving ownership to ApplyLocalDescription,
1940 // which may destroy it before returning.
1941 const SdpType type = desc->GetType();
1942
1943 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001944 // |desc| may be destroyed at this point.
1945
1946 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001947 // If ApplyLocalDescription fails, the PeerConnection could be in an
1948 // inconsistent state, so act conservatively here and set the session error
1949 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1950 SetSessionError(SessionError::kContent, error.message());
1951 std::string error_message =
1952 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1953 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001954 PostSetSessionDescriptionFailure(
1955 observer,
1956 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001957 return;
1958 }
Steve Anton8a006912017-12-04 15:25:56 -08001959 RTC_DCHECK(local_description());
1960
1961 PostSetSessionDescriptionSuccess(observer);
1962
Steve Anton8a006912017-12-04 15:25:56 -08001963 // MaybeStartGathering needs to be called after posting
1964 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1965 // before signaling that SetLocalDescription completed.
1966 transport_controller_->MaybeStartGathering();
1967
Steve Antona3a92c22017-12-07 10:27:41 -08001968 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001969 // TODO(deadbeef): We already had to hop to the network thread for
1970 // MaybeStartGathering...
1971 network_thread()->Invoke<void>(
1972 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1973 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001974 // Make UMA notes about what was agreed to.
1975 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001976 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001977 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001978}
1979
1980RTCError PeerConnection::ApplyLocalDescription(
1981 std::unique_ptr<SessionDescriptionInterface> desc) {
1982 RTC_DCHECK_RUN_ON(signaling_thread());
1983 RTC_DCHECK(desc);
1984
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 // Update stats here so that we have the most recent stats for tracks and
1986 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001987 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001988
Steve Antondcc3c022017-12-22 16:02:54 -08001989 // Take a reference to the old local description since it's used below to
1990 // compare against the new local description. When setting the new local
1991 // description, grab ownership of the replaced session description in case it
1992 // is the same as |old_local_description|, to keep it alive for the duration
1993 // of the method.
1994 const SessionDescriptionInterface* old_local_description =
1995 local_description();
1996 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001997 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001998 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001999 replaced_local_description = pending_local_description_
2000 ? std::move(pending_local_description_)
2001 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002002 current_local_description_ = std::move(desc);
2003 pending_local_description_ = nullptr;
2004 current_remote_description_ = std::move(pending_remote_description_);
2005 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002006 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002007 pending_local_description_ = std::move(desc);
2008 }
2009 // The session description to apply now must be accessed by
2010 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002011 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002012
Zhi Huange830e682018-03-30 10:48:35 -07002013 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2014 if (!error.ok()) {
2015 return error;
2016 }
2017
Steve Antondcc3c022017-12-22 16:02:54 -08002018 if (IsUnifiedPlan()) {
2019 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002020 cricket::CS_LOCAL, *local_description(), old_local_description,
2021 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002022 if (!error.ok()) {
2023 return error;
2024 }
Steve Antondcc3c022017-12-22 16:02:54 -08002025 for (auto transceiver : transceivers_) {
2026 const ContentInfo* content =
2027 FindMediaSectionForTransceiver(transceiver, local_description());
2028 if (!content) {
2029 continue;
2030 }
2031 const MediaContentDescription* media_desc = content->media_description();
2032 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2033 transceiver->internal()->set_current_direction(media_desc->direction());
2034 }
2035 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002036 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2037 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002038 transceiver->Stop();
2039 }
2040 }
2041 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002042 // Media channels will be created only when offer is set. These may use new
2043 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002044 if (type == SdpType::kOffer) {
2045 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2046 // description is applied. Restore back to old description.
2047 RTCError error = CreateChannels(*local_description()->description());
2048 if (!error.ok()) {
2049 return error;
2050 }
2051 }
Steve Antondcc3c022017-12-22 16:02:54 -08002052 // Remove unused channels if MediaContentDescription is rejected.
2053 RemoveUnusedChannels(local_description()->description());
2054 }
Steve Anton8a006912017-12-04 15:25:56 -08002055
Zhi Huange830e682018-03-30 10:48:35 -07002056 error = UpdateSessionState(type, cricket::CS_LOCAL,
2057 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002058 if (!error.ok()) {
2059 return error;
2060 }
Steve Antondcc3c022017-12-22 16:02:54 -08002061
Steve Anton8a006912017-12-04 15:25:56 -08002062 if (remote_description()) {
2063 // Now that we have a local description, we can push down remote candidates.
2064 UseCandidatesInSessionDescription(remote_description());
2065 }
2066
2067 pending_ice_restarts_.clear();
2068 if (session_error() != SessionError::kNone) {
2069 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2070 }
2071
deadbeefab9b2d12015-10-14 11:33:11 -07002072 // If setting the description decided our SSL role, allocate any necessary
2073 // SCTP sids.
2074 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002075 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002076 AllocateSctpSids(role);
2077 }
2078
Steve Antond3679212018-01-17 17:41:02 -08002079 if (IsUnifiedPlan()) {
2080 for (auto transceiver : transceivers_) {
2081 const ContentInfo* content =
2082 FindMediaSectionForTransceiver(transceiver, local_description());
2083 if (!content) {
2084 continue;
2085 }
Steve Anton74255ff2018-01-24 18:32:57 -08002086 const auto& streams = content->media_description()->streams();
2087 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002088 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002089 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002090 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002091 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002092 } else {
2093 // 0 is a special value meaning "this sender has no associated send
2094 // stream". Need to call this so the sender won't attempt to configure
2095 // a no longer existing stream and run into DCHECKs in the lower
2096 // layers.
2097 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002098 }
2099 }
2100 } else {
2101 // Plan B semantics.
2102
Steve Antondcc3c022017-12-22 16:02:54 -08002103 // Update state and SSRC of local MediaStreams and DataChannels based on the
2104 // local session description.
2105 const cricket::ContentInfo* audio_content =
2106 GetFirstAudioContent(local_description()->description());
2107 if (audio_content) {
2108 if (audio_content->rejected) {
2109 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2110 } else {
2111 const cricket::AudioContentDescription* audio_desc =
2112 audio_content->media_description()->as_audio();
2113 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2114 }
deadbeeffaac4972015-11-12 15:33:07 -08002115 }
deadbeefab9b2d12015-10-14 11:33:11 -07002116
Steve Antondcc3c022017-12-22 16:02:54 -08002117 const cricket::ContentInfo* video_content =
2118 GetFirstVideoContent(local_description()->description());
2119 if (video_content) {
2120 if (video_content->rejected) {
2121 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2122 } else {
2123 const cricket::VideoContentDescription* video_desc =
2124 video_content->media_description()->as_video();
2125 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2126 }
deadbeeffaac4972015-11-12 15:33:07 -08002127 }
deadbeefab9b2d12015-10-14 11:33:11 -07002128 }
2129
2130 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002131 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002132 if (data_content) {
2133 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002134 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002135 if (rtc::starts_with(data_desc->protocol().data(),
2136 cricket::kMediaProtocolRtpPrefix)) {
2137 UpdateLocalRtpDataChannels(data_desc->streams());
2138 }
2139 }
2140
Steve Anton8a006912017-12-04 15:25:56 -08002141 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002142}
2143
2144void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002145 SetSessionDescriptionObserver* observer,
2146 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002147 SetRemoteDescription(
2148 std::unique_ptr<SessionDescriptionInterface>(desc),
2149 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2150 new SetRemoteDescriptionObserverAdapter(this, observer)));
2151}
2152
2153void PeerConnection::SetRemoteDescription(
2154 std::unique_ptr<SessionDescriptionInterface> desc,
2155 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002156 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002157
nisse7ce109a2017-01-31 00:57:56 -08002158 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002159 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160 return;
2161 }
Steve Anton8a006912017-12-04 15:25:56 -08002162
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002163 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002164 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002165 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 return;
2167 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002168
Steve Anton80dd7b52018-02-16 17:08:42 -08002169 // If a session error has occurred the PeerConnection is in a possibly
2170 // inconsistent state so fail right away.
2171 if (session_error() != SessionError::kNone) {
2172 std::string error_message = GetSessionErrorMsg();
2173 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2174 observer->OnSetRemoteDescriptionComplete(
2175 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2176 return;
2177 }
Steve Anton71439a62018-02-15 11:53:06 -08002178
Steve Antonba42e992018-04-09 14:10:01 -07002179 if (desc->GetType() == SdpType::kOffer) {
2180 // Report to UMA the format of the received offer.
2181 ReportSdpFormatReceived(*desc);
2182 }
2183
Steve Anton80dd7b52018-02-16 17:08:42 -08002184 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002185 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002186 std::string error_message = GetSetDescriptionErrorMessage(
2187 cricket::CS_REMOTE, desc->GetType(), error);
2188 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002189 observer->OnSetRemoteDescriptionComplete(
2190 RTCError(error.type(), std::move(error_message)));
2191 return;
2192 }
Steve Anton71439a62018-02-15 11:53:06 -08002193
Steve Anton80dd7b52018-02-16 17:08:42 -08002194 // Grab the description type before moving ownership to
2195 // ApplyRemoteDescription, which may destroy it before returning.
2196 const SdpType type = desc->GetType();
2197
2198 error = ApplyRemoteDescription(std::move(desc));
2199 // |desc| may be destroyed at this point.
2200
2201 if (!error.ok()) {
2202 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2203 // inconsistent state, so act conservatively here and set the session error
2204 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2205 SetSessionError(SessionError::kContent, error.message());
2206 std::string error_message =
2207 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2208 RTC_LOG(LS_ERROR) << error_message;
2209 observer->OnSetRemoteDescriptionComplete(
2210 RTCError(error.type(), std::move(error_message)));
2211 return;
2212 }
2213 RTC_DCHECK(remote_description());
2214
2215 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002216 // TODO(deadbeef): We already had to hop to the network thread for
2217 // MaybeStartGathering...
2218 network_thread()->Invoke<void>(
2219 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2220 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002221 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002222 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002223 }
2224
2225 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002226 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002227}
2228
2229RTCError PeerConnection::ApplyRemoteDescription(
2230 std::unique_ptr<SessionDescriptionInterface> desc) {
2231 RTC_DCHECK_RUN_ON(signaling_thread());
2232 RTC_DCHECK(desc);
2233
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234 // Update stats here so that we have the most recent stats for tracks and
2235 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002236 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002237
Steve Antondcc3c022017-12-22 16:02:54 -08002238 // Take a reference to the old remote description since it's used below to
2239 // compare against the new remote description. When setting the new remote
2240 // description, grab ownership of the replaced session description in case it
2241 // is the same as |old_remote_description|, to keep it alive for the duration
2242 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002243 const SessionDescriptionInterface* old_remote_description =
2244 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002245 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002246 SdpType type = desc->GetType();
2247 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002248 replaced_remote_description = pending_remote_description_
2249 ? std::move(pending_remote_description_)
2250 : std::move(current_remote_description_);
2251 current_remote_description_ = std::move(desc);
2252 pending_remote_description_ = nullptr;
2253 current_local_description_ = std::move(pending_local_description_);
2254 } else {
2255 replaced_remote_description = std::move(pending_remote_description_);
2256 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257 }
Steve Anton8a006912017-12-04 15:25:56 -08002258 // The session description to apply now must be accessed by
2259 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002260 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002261
Zhi Huange830e682018-03-30 10:48:35 -07002262 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2263 if (!error.ok()) {
2264 return error;
2265 }
Steve Anton8a006912017-12-04 15:25:56 -08002266 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002267 if (IsUnifiedPlan()) {
2268 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002269 cricket::CS_REMOTE, *remote_description(), local_description(),
2270 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002271 if (!error.ok()) {
2272 return error;
2273 }
Steve Antondcc3c022017-12-22 16:02:54 -08002274 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002275 // Media channels will be created only when offer is set. These may use new
2276 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002277 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002278 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002279 // description is applied. Restore back to old description.
2280 RTCError error = CreateChannels(*remote_description()->description());
2281 if (!error.ok()) {
2282 return error;
2283 }
2284 }
Steve Antondcc3c022017-12-22 16:02:54 -08002285 // Remove unused channels if MediaContentDescription is rejected.
2286 RemoveUnusedChannels(remote_description()->description());
2287 }
Steve Anton8a006912017-12-04 15:25:56 -08002288
Zhi Huange830e682018-03-30 10:48:35 -07002289 // NOTE: Candidates allocation will be initiated only when
2290 // SetLocalDescription is called.
2291 error = UpdateSessionState(type, cricket::CS_REMOTE,
2292 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002293 if (!error.ok()) {
2294 return error;
2295 }
2296
2297 if (local_description() &&
2298 !UseCandidatesInSessionDescription(remote_description())) {
2299 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2300 }
2301
2302 if (old_remote_description) {
2303 for (const cricket::ContentInfo& content :
2304 old_remote_description->description()->contents()) {
2305 // Check if this new SessionDescription contains new ICE ufrag and
2306 // password that indicates the remote peer requests an ICE restart.
2307 // TODO(deadbeef): When we start storing both the current and pending
2308 // remote description, this should reset pending_ice_restarts and compare
2309 // against the current description.
2310 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2311 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002312 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002313 pending_ice_restarts_.insert(content.name);
2314 }
2315 } else {
2316 // We retain all received candidates only if ICE is not restarted.
2317 // When ICE is restarted, all previous candidates belong to an old
2318 // generation and should not be kept.
2319 // TODO(deadbeef): This goes against the W3C spec which says the remote
2320 // description should only contain candidates from the last set remote
2321 // description plus any candidates added since then. We should remove
2322 // this once we're sure it won't break anything.
2323 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2324 old_remote_description, content.name, mutable_remote_description());
2325 }
2326 }
2327 }
2328
2329 if (session_error() != SessionError::kNone) {
2330 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2331 }
2332
2333 // Set the the ICE connection state to connecting since the connection may
2334 // become writable with peer reflexive candidates before any remote candidate
2335 // is signaled.
2336 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2337 // is to have a new signal the indicates a change in checking state from the
2338 // transport and expose a new checking() member from transport that can be
2339 // read to determine the current checking state. The existing SignalConnecting
2340 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002341 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002342 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002343 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2344 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2345 }
2346
deadbeefab9b2d12015-10-14 11:33:11 -07002347 // If setting the description decided our SSL role, allocate any necessary
2348 // SCTP sids.
2349 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002350 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002351 AllocateSctpSids(role);
2352 }
2353
Steve Antondcc3c022017-12-22 16:02:54 -08002354 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002355 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002356 now_receiving_transceivers;
2357 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2358 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002359 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002360 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002361 for (auto transceiver : transceivers_) {
2362 const ContentInfo* content =
2363 FindMediaSectionForTransceiver(transceiver, remote_description());
2364 if (!content) {
2365 continue;
2366 }
2367 const MediaContentDescription* media_desc = content->media_description();
2368 RtpTransceiverDirection local_direction =
2369 RtpTransceiverDirectionReversed(media_desc->direction());
2370 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2371 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2372 // transceiver's current direction is neither sendrecv nor recvonly,
2373 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002374 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002375 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002376 // The remote description has signaled the stream IDs.
2377 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002378 }
Steve Antondcc3c022017-12-22 16:02:54 -08002379 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2380 (!transceiver->current_direction() ||
2381 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002382 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002383 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002384 << content->name << " (added to "
2385 << GetStreamIdsString(stream_ids) << ").";
2386
2387 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2388 for (const std::string& stream_id : stream_ids) {
2389 rtc::scoped_refptr<MediaStreamInterface> stream =
2390 remote_streams_->find(stream_id);
2391 if (!stream) {
2392 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2393 MediaStream::Create(stream_id));
2394 remote_streams_->AddStream(stream);
2395 added_streams.push_back(stream);
2396 }
2397 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002398 }
Steve Anton3172c032018-05-03 15:30:18 -07002399 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002400 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002401 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002402 }
2403 // If direction is sendonly or inactive, and transceiver's current
2404 // direction is neither sendonly nor inactive, process the removal of a
2405 // remote track for the media description.
2406 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002407 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002408 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002409 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2410 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002411 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2412 transceiver->internal()->receiver_internal()->streams();
2413 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002414 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002415 no_longer_receiving_transceivers.push_back(transceiver);
2416 // Remove any streams that no longer have tracks.
2417 for (auto stream : media_streams) {
2418 if (stream->GetAudioTracks().empty() &&
2419 stream->GetVideoTracks().empty()) {
2420 remote_streams_->RemoveStream(stream);
2421 removed_streams.push_back(stream);
2422 }
2423 }
Steve Antondcc3c022017-12-22 16:02:54 -08002424 }
2425 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2426 transceiver->internal()->set_current_direction(local_direction);
2427 }
2428 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002429 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2430 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002431 transceiver->Stop();
2432 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002433 if (!content->rejected &&
2434 RtpTransceiverDirectionHasRecv(local_direction)) {
2435 // Set ssrc to 0 in the case of an unsignalled ssrc.
2436 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002437 if (!media_desc->streams().empty() &&
2438 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002439 ssrc = media_desc->streams()[0].first_ssrc();
2440 }
2441 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002442 }
Steve Antondcc3c022017-12-22 16:02:54 -08002443 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002444 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002445 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002446 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002447 observer_->OnTrack(transceiver);
2448 observer_->OnAddTrack(transceiver->receiver(),
2449 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002450 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002451 for (auto stream : added_streams) {
2452 observer_->OnAddStream(stream);
2453 }
Steve Anton3172c032018-05-03 15:30:18 -07002454 for (auto transceiver : no_longer_receiving_transceivers) {
2455 observer_->OnRemoveTrack(transceiver->receiver());
2456 }
2457 for (auto stream : removed_streams) {
2458 observer_->OnRemoveStream(stream);
2459 }
Steve Antondcc3c022017-12-22 16:02:54 -08002460 }
2461
Henrik Boströmfdb92012017-11-09 19:55:44 +01002462 const cricket::ContentInfo* audio_content =
2463 GetFirstAudioContent(remote_description()->description());
2464 const cricket::ContentInfo* video_content =
2465 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002466 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002467 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002468 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002469 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002470 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002471 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002472
2473 // Check if the descriptions include streams, just in case the peer supports
2474 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002475 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002476 (audio_desc && !audio_desc->streams().empty()) ||
2477 (video_desc && !video_desc->streams().empty())) {
2478 remote_peer_supports_msid_ = true;
2479 }
deadbeefab9b2d12015-10-14 11:33:11 -07002480
2481 // We wait to signal new streams until we finish processing the description,
2482 // since only at that point will new streams have all their tracks.
2483 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2484
Steve Antondcc3c022017-12-22 16:02:54 -08002485 if (!IsUnifiedPlan()) {
2486 // TODO(steveanton): When removing RTP senders/receivers in response to a
2487 // rejected media section, there is some cleanup logic that expects the
2488 // voice/ video channel to still be set. But in this method the voice/video
2489 // channel would have been destroyed by the SetRemoteDescription caller
2490 // above so the cleanup that relies on them fails to run. The RemoveSenders
2491 // calls should be moved to right before the DestroyChannel calls to fix
2492 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002493
Steve Antondcc3c022017-12-22 16:02:54 -08002494 // Find all audio rtp streams and create corresponding remote AudioTracks
2495 // and MediaStreams.
2496 if (audio_content) {
2497 if (audio_content->rejected) {
2498 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2499 } else {
2500 bool default_audio_track_needed =
2501 !remote_peer_supports_msid_ &&
2502 RtpTransceiverDirectionHasSend(audio_desc->direction());
2503 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2504 default_audio_track_needed, audio_desc->type(),
2505 new_streams);
2506 }
deadbeeffaac4972015-11-12 15:33:07 -08002507 }
deadbeefab9b2d12015-10-14 11:33:11 -07002508
Steve Antondcc3c022017-12-22 16:02:54 -08002509 // Find all video rtp streams and create corresponding remote VideoTracks
2510 // and MediaStreams.
2511 if (video_content) {
2512 if (video_content->rejected) {
2513 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2514 } else {
2515 bool default_video_track_needed =
2516 !remote_peer_supports_msid_ &&
2517 RtpTransceiverDirectionHasSend(video_desc->direction());
2518 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2519 default_video_track_needed, video_desc->type(),
2520 new_streams);
2521 }
deadbeeffaac4972015-11-12 15:33:07 -08002522 }
deadbeefab9b2d12015-10-14 11:33:11 -07002523
Steve Antondcc3c022017-12-22 16:02:54 -08002524 // Update the DataChannels with the information from the remote peer.
2525 if (data_desc) {
2526 if (rtc::starts_with(data_desc->protocol().data(),
2527 cricket::kMediaProtocolRtpPrefix)) {
2528 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2529 }
deadbeefab9b2d12015-10-14 11:33:11 -07002530 }
deadbeefab9b2d12015-10-14 11:33:11 -07002531
Steve Antondcc3c022017-12-22 16:02:54 -08002532 // Iterate new_streams and notify the observer about new MediaStreams.
2533 for (size_t i = 0; i < new_streams->count(); ++i) {
2534 MediaStreamInterface* new_stream = new_streams->at(i);
2535 stats_->AddStream(new_stream);
2536 observer_->OnAddStream(
2537 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2538 }
deadbeefab9b2d12015-10-14 11:33:11 -07002539
Steve Antondcc3c022017-12-22 16:02:54 -08002540 UpdateEndedRemoteMediaStreams();
2541 }
deadbeefab9b2d12015-10-14 11:33:11 -07002542
Steve Anton8a006912017-12-04 15:25:56 -08002543 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002544}
2545
Steve Antondcc3c022017-12-22 16:02:54 -08002546RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2547 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002548 const SessionDescriptionInterface& new_session,
2549 const SessionDescriptionInterface* old_local_description,
2550 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002551 RTC_DCHECK(IsUnifiedPlan());
2552
Steve Anton7464fca2018-01-19 11:10:37 -08002553 const cricket::ContentGroup* bundle_group = nullptr;
2554 if (new_session.GetType() == SdpType::kOffer) {
2555 auto bundle_group_or_error =
2556 GetEarlyBundleGroup(*new_session.description());
2557 if (!bundle_group_or_error.ok()) {
2558 return bundle_group_or_error.MoveError();
2559 }
2560 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002561 }
Steve Antondcc3c022017-12-22 16:02:54 -08002562
Steve Antondcc3c022017-12-22 16:02:54 -08002563 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002564 for (size_t i = 0; i < new_contents.size(); ++i) {
2565 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002566 cricket::MediaType media_type = new_content.media_description()->type();
2567 seen_mids_.insert(new_content.name);
2568 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2569 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002570 const cricket::ContentInfo* old_local_content = nullptr;
2571 if (old_local_description &&
2572 i < old_local_description->description()->contents().size()) {
2573 old_local_content =
2574 &old_local_description->description()->contents()[i];
2575 }
2576 const cricket::ContentInfo* old_remote_content = nullptr;
2577 if (old_remote_description &&
2578 i < old_remote_description->description()->contents().size()) {
2579 old_remote_content =
2580 &old_remote_description->description()->contents()[i];
2581 }
Steve Antondcc3c022017-12-22 16:02:54 -08002582 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002583 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2584 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002585 if (!transceiver_or_error.ok()) {
2586 return transceiver_or_error.MoveError();
2587 }
2588 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002589 RTCError error =
2590 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2591 if (!error.ok()) {
2592 return error;
2593 }
2594 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002595 if (GetDataMid() && new_content.name != *GetDataMid()) {
2596 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002597 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2598 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002599 continue;
2600 }
2601 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2602 if (!error.ok()) {
2603 return error;
2604 }
Steve Antondcc3c022017-12-22 16:02:54 -08002605 } else {
2606 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2607 "Unknown section type.");
2608 }
2609 }
2610
2611 return RTCError::OK();
2612}
2613
2614RTCError PeerConnection::UpdateTransceiverChannel(
2615 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2616 transceiver,
2617 const cricket::ContentInfo& content,
2618 const cricket::ContentGroup* bundle_group) {
2619 RTC_DCHECK(IsUnifiedPlan());
2620 RTC_DCHECK(transceiver);
2621 cricket::BaseChannel* channel = transceiver->internal()->channel();
2622 if (content.rejected) {
2623 if (channel) {
2624 transceiver->internal()->SetChannel(nullptr);
2625 DestroyBaseChannel(channel);
2626 }
2627 } else {
2628 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002629 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002630 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002631 } else {
Steve Anton69470252018-02-09 11:43:08 -08002632 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002633 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002634 }
2635 if (!channel) {
2636 LOG_AND_RETURN_ERROR(
2637 RTCErrorType::INTERNAL_ERROR,
2638 "Failed to create channel for mid=" + content.name);
2639 }
2640 transceiver->internal()->SetChannel(channel);
2641 }
2642 }
2643 return RTCError::OK();
2644}
2645
Steve Antonfa2260d2017-12-28 16:38:23 -08002646RTCError PeerConnection::UpdateDataChannel(
2647 cricket::ContentSource source,
2648 const cricket::ContentInfo& content,
2649 const cricket::ContentGroup* bundle_group) {
2650 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002651 // If data channels are disabled, ignore this media section. CreateAnswer
2652 // will take care of rejecting it.
2653 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002654 }
2655 if (content.rejected) {
2656 DestroyDataChannel();
2657 } else {
2658 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002659 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002660 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2661 "Failed to create data channel.");
2662 }
2663 }
2664 if (source == cricket::CS_REMOTE) {
2665 const MediaContentDescription* data_desc = content.media_description();
2666 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2667 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2668 }
2669 }
2670 }
2671 return RTCError::OK();
2672}
2673
Steve Antondcc3c022017-12-22 16:02:54 -08002674RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2675PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002676 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002677 size_t mline_index,
2678 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002679 const ContentInfo* old_local_content,
2680 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002681 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002682 // If this is an offer then the m= section might be recycled. If the m=
2683 // section is being recycled (defined as: rejected in the current local or
2684 // remote description and not rejected in new description), dissociate the
2685 // currently associated RtpTransceiver by setting its mid property to null,
2686 // and discard the mapping between the transceiver and its m= section index.
2687 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2688 old_remote_content)) {
2689 // We want to dissociate the transceiver that has the rejected mid.
2690 const std::string& old_mid =
2691 (old_local_content && old_local_content->rejected)
2692 ? old_local_content->name
2693 : old_remote_content->name;
2694 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002695 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002696 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2697 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002698 old_transceiver->internal()->set_mid(absl::nullopt);
2699 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002700 }
2701 }
2702 const MediaContentDescription* media_desc = content.media_description();
2703 auto transceiver = GetAssociatedTransceiver(content.name);
2704 if (source == cricket::CS_LOCAL) {
2705 // Find the RtpTransceiver that corresponds to this m= section, using the
2706 // mapping between transceivers and m= section indices established when
2707 // creating the offer.
2708 if (!transceiver) {
2709 transceiver = GetTransceiverByMLineIndex(mline_index);
2710 }
2711 if (!transceiver) {
2712 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2713 "Unknown transceiver");
2714 }
2715 } else {
2716 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2717 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2718 // of the same type...
2719 if (!transceiver &&
2720 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2721 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2722 }
2723 // If no RtpTransceiver was found in the previous step, create one with a
2724 // recvonly direction.
2725 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002726 RTC_LOG(LS_INFO) << "Adding "
2727 << cricket::MediaTypeToString(media_desc->type())
2728 << " transceiver for MID=" << content.name
2729 << " at i=" << mline_index
2730 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002731 auto sender =
2732 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002733 std::string receiver_id;
2734 if (!media_desc->streams().empty()) {
2735 receiver_id = media_desc->streams()[0].id;
2736 } else {
2737 receiver_id = rtc::CreateRandomUuid();
2738 }
2739 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002740 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002741 transceiver->internal()->set_direction(
2742 RtpTransceiverDirection::kRecvOnly);
2743 }
2744 }
2745 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002746 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002747 LOG_AND_RETURN_ERROR(
2748 RTCErrorType::INVALID_PARAMETER,
2749 "Transceiver type does not match media description type.");
2750 }
2751 // Associate the found or created RtpTransceiver with the m= section by
2752 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2753 // section, and establish a mapping between the transceiver and the index of
2754 // the m= section.
2755 transceiver->internal()->set_mid(content.name);
2756 transceiver->internal()->set_mline_index(mline_index);
2757 return std::move(transceiver);
2758}
2759
2760rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2761PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2762 RTC_DCHECK(IsUnifiedPlan());
2763 for (auto transceiver : transceivers_) {
2764 if (transceiver->mid() == mid) {
2765 return transceiver;
2766 }
2767 }
2768 return nullptr;
2769}
2770
2771rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2772PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2773 RTC_DCHECK(IsUnifiedPlan());
2774 for (auto transceiver : transceivers_) {
2775 if (transceiver->internal()->mline_index() == mline_index) {
2776 return transceiver;
2777 }
2778 }
2779 return nullptr;
2780}
2781
2782rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2783PeerConnection::FindAvailableTransceiverToReceive(
2784 cricket::MediaType media_type) const {
2785 RTC_DCHECK(IsUnifiedPlan());
2786 // From JSEP section 5.10 (Applying a Remote Description):
2787 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2788 // the same type that were added to the PeerConnection by addTrack and are not
2789 // associated with any m= section and are not stopped, find the first such
2790 // RtpTransceiver.
2791 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002792 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002793 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2794 !transceiver->stopped()) {
2795 return transceiver;
2796 }
2797 }
2798 return nullptr;
2799}
2800
Steve Antoned10bd92017-12-05 10:52:59 -08002801const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2802 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2803 transceiver,
2804 const SessionDescriptionInterface* sdesc) const {
2805 RTC_DCHECK(transceiver);
2806 RTC_DCHECK(sdesc);
2807 if (IsUnifiedPlan()) {
2808 if (!transceiver->internal()->mid()) {
2809 // This transceiver is not associated with a media section yet.
2810 return nullptr;
2811 }
2812 return sdesc->description()->GetContentByName(
2813 *transceiver->internal()->mid());
2814 } else {
2815 // Plan B only allows at most one audio and one video section, so use the
2816 // first media section of that type.
2817 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002818 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002819 }
2820}
2821
deadbeef46c73892016-11-16 19:42:04 -08002822PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2823 return configuration_;
2824}
2825
deadbeef293e9262017-01-11 12:28:30 -08002826bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2827 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002828 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002829 if (IsClosed()) {
2830 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2831 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2832 }
2833
Qingsi Wanga2d60672018-04-11 16:57:45 -07002834 // According to JSEP, after setLocalDescription, changing the candidate pool
2835 // size is not allowed, and changing the set of ICE servers will not result
2836 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002837 if (local_description() && configuration.ice_candidate_pool_size !=
2838 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002839 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2840 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002841 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002842 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002843
deadbeef293e9262017-01-11 12:28:30 -08002844 // The simplest (and most future-compatible) way to tell if the config was
2845 // modified in an invalid way is to copy each property we do support
2846 // modifying, then use operator==. There are far more properties we don't
2847 // support modifying than those we do, and more could be added.
2848 RTCConfiguration modified_config = configuration_;
2849 modified_config.servers = configuration.servers;
2850 modified_config.type = configuration.type;
2851 modified_config.ice_candidate_pool_size =
2852 configuration.ice_candidate_pool_size;
2853 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002854 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002855 modified_config.ice_check_interval_strong_connectivity =
2856 configuration.ice_check_interval_strong_connectivity;
2857 modified_config.ice_check_interval_weak_connectivity =
2858 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002859 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2860 modified_config.ice_unwritable_min_checks =
2861 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002862 modified_config.stun_candidate_keepalive_interval =
2863 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002864 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002865 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002866 modified_config.active_reset_srtp_params =
2867 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002868 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002869 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002870 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2871 }
2872
Steve Anton038834f2017-07-14 15:59:59 -07002873 // Validate the modified configuration.
2874 RTCError validate_error = ValidateConfiguration(modified_config);
2875 if (!validate_error.ok()) {
2876 return SafeSetError(std::move(validate_error), error);
2877 }
2878
deadbeef293e9262017-01-11 12:28:30 -08002879 // Note that this isn't possible through chromium, since it's an unsigned
2880 // short in WebIDL.
2881 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002882 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002883 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2884 }
2885
2886 // Parse ICE servers before hopping to network thread.
2887 cricket::ServerAddresses stun_servers;
2888 std::vector<cricket::RelayServerConfig> turn_servers;
2889 RTCErrorType parse_error =
2890 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2891 if (parse_error != RTCErrorType::NONE) {
2892 return SafeSetError(parse_error, error);
2893 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002894 // Note if STUN or TURN servers were supplied.
2895 if (!stun_servers.empty()) {
2896 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2897 }
2898 if (!turn_servers.empty()) {
2899 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2900 }
deadbeef293e9262017-01-11 12:28:30 -08002901
2902 // In theory this shouldn't fail.
2903 if (!network_thread()->Invoke<bool>(
2904 RTC_FROM_HERE,
2905 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2906 stun_servers, turn_servers, modified_config.type,
2907 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002908 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002909 modified_config.turn_customizer,
2910 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002911 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002912 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2913 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002914
deadbeefd1a38b52016-12-10 13:15:33 -08002915 // As described in JSEP, calling setConfiguration with new ICE servers or
2916 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2917 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002918 if (modified_config.servers != configuration_.servers ||
2919 modified_config.type != configuration_.type ||
2920 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002921 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002922 }
skvladd1f5fda2017-02-03 16:54:05 -08002923
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002924 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002925
Zhi Huangb57e1692018-06-12 11:41:11 -07002926 if (configuration_.active_reset_srtp_params !=
2927 modified_config.active_reset_srtp_params) {
2928 transport_controller_->SetActiveResetSrtpParams(
2929 modified_config.active_reset_srtp_params);
2930 }
2931
deadbeef293e9262017-01-11 12:28:30 -08002932 configuration_ = modified_config;
2933 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002934}
2935
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002936bool PeerConnection::AddIceCandidate(
2937 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002938 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002939 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002940 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002941 return false;
2942 }
Steve Antond25da372017-11-06 14:50:29 -08002943
2944 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002945 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002946 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002947 return false;
2948 }
2949
2950 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002951 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002952 return false;
2953 }
2954
2955 bool valid = false;
2956 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2957 if (!valid) {
2958 return false;
2959 }
2960
2961 // Add this candidate to the remote session description.
2962 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002963 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002964 return false;
2965 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002966 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002967
2968 if (ready) {
2969 return UseCandidate(ice_candidate);
2970 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002971 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002972 return true;
2973 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002974}
2975
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002976bool PeerConnection::RemoveIceCandidates(
2977 const std::vector<cricket::Candidate>& candidates) {
2978 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002979 if (IsClosed()) {
2980 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2981 return false;
2982 }
2983
Steve Antond25da372017-11-06 14:50:29 -08002984 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002985 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2986 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002987 return false;
2988 }
2989
2990 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002991 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002992 return false;
2993 }
2994
2995 size_t number_removed =
2996 mutable_remote_description()->RemoveCandidates(candidates);
2997 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002998 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07002999 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003000 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003001 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003002 }
3003
3004 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003005 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3006 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003007 RTC_LOG(LS_ERROR)
3008 << "RemoveIceCandidates: Error when removing remote candidates: "
3009 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003010 }
3011 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003012}
3013
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003014void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003015 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003016 network_thread()->Invoke<void>(
3017 RTC_FROM_HERE,
3018 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3019 // Send information about IPv4/IPv6 status.
3020 if (uma_observer_) {
3021 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3022 uma_observer_->IncrementEnumCounter(
3023 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3024 kPeerConnectionAddressFamilyCounter_Max);
3025 } else {
3026 uma_observer_->IncrementEnumCounter(
3027 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3028 kPeerConnectionAddressFamilyCounter_Max);
3029 }
3030 }
3031}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003032
Qingsi Wanga2d60672018-04-11 16:57:45 -07003033void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3034 RTC_DCHECK(network_thread()->IsCurrent());
3035 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003036 if (transport_controller_) {
3037 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003038 }
3039
3040 for (auto transceiver : transceivers_) {
3041 auto* channel = transceiver->internal()->channel();
3042 if (channel) {
3043 channel->SetMetricsObserver(uma_observer_);
3044 }
3045 }
3046
deadbeef293e9262017-01-11 12:28:30 -08003047 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003048 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003049 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003050}
3051
Niels Möller0c4f7be2018-05-07 14:01:37 +02003052RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003053 if (!worker_thread()->IsCurrent()) {
3054 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003055 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003056 }
3057
Niels Möller0c4f7be2018-05-07 14:01:37 +02003058 const bool has_min = bitrate.min_bitrate_bps.has_value();
3059 const bool has_start = bitrate.start_bitrate_bps.has_value();
3060 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003061 if (has_min && *bitrate.min_bitrate_bps < 0) {
3062 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3063 "min_bitrate_bps <= 0");
3064 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003065 if (has_start) {
3066 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003067 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003068 "start_bitrate_bps < min_bitrate_bps");
3069 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3071 "curent_bitrate_bps < 0");
3072 }
3073 }
3074 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003075 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003076 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003077 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003078 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3079 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3080 "max_bitrate_bps < min_bitrate_bps");
3081 } else if (*bitrate.max_bitrate_bps < 0) {
3082 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3083 "max_bitrate_bps < 0");
3084 }
3085 }
3086
zstein4b979802017-06-02 14:37:37 -07003087 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003088 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003089
3090 return RTCError::OK();
3091}
3092
Alex Narest78609d52017-10-20 10:37:47 +02003093void PeerConnection::SetBitrateAllocationStrategy(
3094 std::unique_ptr<rtc::BitrateAllocationStrategy>
3095 bitrate_allocation_strategy) {
3096 rtc::Thread* worker_thread = factory_->worker_thread();
3097 if (!worker_thread->IsCurrent()) {
3098 rtc::BitrateAllocationStrategy* strategy_raw =
3099 bitrate_allocation_strategy.release();
3100 auto functor = [this, strategy_raw]() {
3101 call_->SetBitrateAllocationStrategy(
3102 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3103 };
3104 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3105 return;
3106 }
3107 RTC_DCHECK(call_.get());
3108 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3109}
3110
henrika5f6bf242017-11-01 11:06:56 +01003111void PeerConnection::SetAudioPlayout(bool playout) {
3112 if (!worker_thread()->IsCurrent()) {
3113 worker_thread()->Invoke<void>(
3114 RTC_FROM_HERE,
3115 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3116 return;
3117 }
3118 auto audio_state =
3119 factory_->channel_manager()->media_engine()->GetAudioState();
3120 audio_state->SetPlayout(playout);
3121}
3122
3123void PeerConnection::SetAudioRecording(bool recording) {
3124 if (!worker_thread()->IsCurrent()) {
3125 worker_thread()->Invoke<void>(
3126 RTC_FROM_HERE,
3127 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3128 return;
3129 }
3130 auto audio_state =
3131 factory_->channel_manager()->media_engine()->GetAudioState();
3132 audio_state->SetRecording(recording);
3133}
3134
Steve Anton8c0f7a72017-10-03 10:03:10 -07003135std::unique_ptr<rtc::SSLCertificate>
3136PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003137 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3138 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003139 return nullptr;
3140 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003141 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003142}
3143
Zhi Huang70b820f2018-01-27 14:16:15 -08003144std::unique_ptr<rtc::SSLCertChain>
3145PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003146 auto audio_transceiver = GetFirstAudioTransceiver();
3147 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003148 return nullptr;
3149 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003150 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003151 audio_transceiver->internal()->channel()->transport_name());
3152}
3153
3154rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3155PeerConnection::GetFirstAudioTransceiver() const {
3156 for (auto transceiver : transceivers_) {
3157 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3158 return transceiver;
3159 }
3160 }
3161 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003162}
3163
ivoc14d5dbe2016-07-04 07:06:55 -07003164bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3165 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003166 // TODO(eladalon): It would be better to not allow negative values into PC.
3167 const size_t max_size = (max_size_bytes < 0)
3168 ? RtcEventLog::kUnlimitedOutput
3169 : rtc::saturated_cast<size_t>(max_size_bytes);
3170 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003171 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3172 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003173}
3174
Bjorn Tereliusde939432017-11-20 17:38:14 +01003175bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3176 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003177 // TODO(eladalon): In C++14, this can be done with a lambda.
3178 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003179 bool operator()() {
3180 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3181 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003182 PeerConnection* const pc;
3183 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003184 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003185 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003186 return worker_thread()->Invoke<bool>(
3187 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003188}
3189
3190void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003191 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003192 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3193}
3194
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003195const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003196 return pending_local_description_ ? pending_local_description_.get()
3197 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198}
3199
3200const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003201 return pending_remote_description_ ? pending_remote_description_.get()
3202 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203}
3204
deadbeeffe4a8a42016-12-20 17:56:17 -08003205const SessionDescriptionInterface* PeerConnection::current_local_description()
3206 const {
Steve Anton75737c02017-11-06 10:37:17 -08003207 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003208}
3209
3210const SessionDescriptionInterface* PeerConnection::current_remote_description()
3211 const {
Steve Anton75737c02017-11-06 10:37:17 -08003212 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003213}
3214
3215const SessionDescriptionInterface* PeerConnection::pending_local_description()
3216 const {
Steve Anton75737c02017-11-06 10:37:17 -08003217 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003218}
3219
3220const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3221 const {
Steve Anton75737c02017-11-06 10:37:17 -08003222 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003223}
3224
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003225void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003226 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003227 // Update stats here so that we have the most recent stats for tracks and
3228 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003229 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003230
Steve Anton75737c02017-11-06 10:37:17 -08003231 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003232 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003233
Steve Anton8af21862017-12-15 11:20:13 -08003234 for (auto transceiver : transceivers_) {
3235 transceiver->Stop();
3236 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003237
3238 // Ensure that all asynchronous stats requests are completed before destroying
3239 // the transport controller below.
3240 if (stats_collector_) {
3241 stats_collector_->WaitForPendingRequest();
3242 }
3243
3244 // Don't destroy BaseChannels until after stats has been cleaned up so that
3245 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003246 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003247
Qingsi Wang93a84392018-01-30 17:13:09 -08003248 // The event log is used in the transport controller, which must be outlived
3249 // by the former. CreateOffer by the peer connection is implemented
3250 // asynchronously and if the peer connection is closed without resetting the
3251 // WebRTC session description factory, the session description factory would
3252 // call the transport controller.
3253 webrtc_session_desc_factory_.reset();
3254 transport_controller_.reset();
3255
deadbeef42a42632017-03-10 15:18:00 -08003256 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003257 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3258 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003259
Steve Anton978b8762017-09-29 12:15:02 -07003260 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003261 call_.reset();
3262 // The event log must outlive call (and any other object that uses it).
3263 event_log_.reset();
3264 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003265 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003266}
3267
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003268void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003269 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003270 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3271 SetSessionDescriptionMsg* param =
3272 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3273 param->observer->OnSuccess();
3274 delete param;
3275 break;
3276 }
3277 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3278 SetSessionDescriptionMsg* param =
3279 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003280 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003281 delete param;
3282 break;
3283 }
deadbeefab9b2d12015-10-14 11:33:11 -07003284 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3285 CreateSessionDescriptionMsg* param =
3286 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003287 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003288 delete param;
3289 break;
3290 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291 case MSG_GETSTATS: {
3292 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003293 StatsReports reports;
3294 stats_->GetStats(param->track, &reports);
3295 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003296 delete param;
3297 break;
3298 }
deadbeefbd292462015-12-14 18:15:29 -08003299 case MSG_FREE_DATACHANNELS: {
3300 sctp_data_channels_to_free_.clear();
3301 break;
3302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003303 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003304 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003305 break;
3306 }
3307}
3308
Steve Antonafb0bb72018-02-20 11:35:37 -08003309cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3310 RTC_DCHECK(!IsUnifiedPlan());
3311 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3312 GetAudioTransceiver()->internal()->channel());
3313 if (voice_channel) {
3314 return voice_channel->media_channel();
3315 } else {
3316 return nullptr;
3317 }
3318}
3319
3320cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3321 RTC_DCHECK(!IsUnifiedPlan());
3322 auto* video_channel = static_cast<cricket::VideoChannel*>(
3323 GetVideoTransceiver()->internal()->channel());
3324 if (video_channel) {
3325 return video_channel->media_channel();
3326 } else {
3327 return nullptr;
3328 }
3329}
3330
Steve Anton4171afb2017-11-20 10:20:22 -08003331void PeerConnection::CreateAudioReceiver(
3332 MediaStreamInterface* stream,
3333 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003334 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3335 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003336 auto* audio_receiver = new AudioRtpReceiver(
3337 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003338 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003339 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3340 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3341 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003342 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003343 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003344 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003345}
3346
Steve Anton4171afb2017-11-20 10:20:22 -08003347void PeerConnection::CreateVideoReceiver(
3348 MediaStreamInterface* stream,
3349 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003350 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3351 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003352 auto* video_receiver = new VideoRtpReceiver(
3353 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003354 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003355 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3356 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3357 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003358 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003359 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003360 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003361}
3362
deadbeef70ab1a12015-09-28 16:53:55 -07003363// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3364// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003365rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003366 const RtpSenderInfo& remote_sender_info) {
3367 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3368 if (!receiver) {
3369 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3370 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003371 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003372 }
Steve Anton4171afb2017-11-20 10:20:22 -08003373 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3374 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3375 } else {
3376 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3377 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003378 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003379}
3380
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003381void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3382 MediaStreamInterface* stream) {
3383 RTC_DCHECK(!IsClosed());
3384 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003385 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003386 // We already have a sender for this track, so just change the stream_id
3387 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003388 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003389 return;
3390 }
3391
3392 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003393 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003394 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003395 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003396 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003397 // If the sender has already been configured in SDP, we call SetSsrc,
3398 // which will connect the sender to the underlying transport. This can
3399 // occur if a local session description that contains the ID of the sender
3400 // is set before AddStream is called. It can also occur if the local
3401 // session description is not changed and RemoveStream is called, and
3402 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003403 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003404 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003405 if (sender_info) {
3406 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003407 }
3408}
3409
3410// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3411// indefinitely, when we have unified plan SDP.
3412void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3413 MediaStreamInterface* stream) {
3414 RTC_DCHECK(!IsClosed());
3415 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003416 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003417 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3418 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003419 return;
3420 }
Steve Anton4171afb2017-11-20 10:20:22 -08003421 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003422}
3423
3424void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3425 MediaStreamInterface* stream) {
3426 RTC_DCHECK(!IsClosed());
3427 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003428 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003429 // We already have a sender for this track, so just change the stream_id
3430 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003431 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003432 return;
3433 }
3434
3435 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003436 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003437 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003438 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003439 GetVideoTransceiver()->internal()->AddSender(new_sender);
3440 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003441 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003442 if (sender_info) {
3443 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003444 }
3445}
3446
3447void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3448 MediaStreamInterface* stream) {
3449 RTC_DCHECK(!IsClosed());
3450 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003451 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003452 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3453 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003454 return;
3455 }
Steve Anton4171afb2017-11-20 10:20:22 -08003456 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003457}
3458
Steve Antonba818672017-11-06 10:21:57 -08003459void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003460 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003461 if (ice_connection_state_ == new_state) {
3462 return;
3463 }
3464
deadbeefcbecd352015-09-23 11:50:27 -07003465 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003466 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003467 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003468 return;
3469 }
Steve Antonba818672017-11-06 10:21:57 -08003470
Mirko Bonadei675513b2017-11-09 11:09:25 +01003471 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3472 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003473 RTC_DCHECK(ice_connection_state_ !=
3474 PeerConnectionInterface::kIceConnectionClosed);
3475
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003476 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003477 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003478}
3479
3480void PeerConnection::OnIceGatheringChange(
3481 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003482 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003483 if (IsClosed()) {
3484 return;
3485 }
3486 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003487 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003488}
3489
jbauch81bf7b02017-03-25 08:31:12 -07003490void PeerConnection::OnIceCandidate(
3491 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003492 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003493 if (IsClosed()) {
3494 return;
3495 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003496 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003497 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003498}
3499
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003500void PeerConnection::OnIceCandidatesRemoved(
3501 const std::vector<cricket::Candidate>& candidates) {
3502 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003503 if (IsClosed()) {
3504 return;
3505 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003506 observer_->OnIceCandidatesRemoved(candidates);
3507}
3508
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509void PeerConnection::ChangeSignalingState(
3510 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003511 RTC_DCHECK(signaling_thread()->IsCurrent());
3512 if (signaling_state_ == signaling_state) {
3513 return;
3514 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003515 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3516 << GetSignalingStateString(signaling_state_)
3517 << " New state: "
3518 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003519 signaling_state_ = signaling_state;
3520 if (signaling_state == kClosed) {
3521 ice_connection_state_ = kIceConnectionClosed;
3522 observer_->OnIceConnectionChange(ice_connection_state_);
3523 if (ice_gathering_state_ != kIceGatheringComplete) {
3524 ice_gathering_state_ = kIceGatheringComplete;
3525 observer_->OnIceGatheringChange(ice_gathering_state_);
3526 }
3527 }
3528 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529}
3530
deadbeefeb459812015-12-15 19:24:43 -08003531void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3532 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003533 if (IsClosed()) {
3534 return;
3535 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003536 AddAudioTrack(track, stream);
3537 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003538}
3539
deadbeefeb459812015-12-15 19:24:43 -08003540void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3541 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003542 if (IsClosed()) {
3543 return;
3544 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003545 RemoveAudioTrack(track, stream);
3546 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003547}
3548
3549void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3550 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003551 if (IsClosed()) {
3552 return;
3553 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003554 AddVideoTrack(track, stream);
3555 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003556}
3557
3558void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3559 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003560 if (IsClosed()) {
3561 return;
3562 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003563 RemoveVideoTrack(track, stream);
3564 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003565}
3566
Henrik Boström31638672017-11-23 17:48:32 +01003567void PeerConnection::PostSetSessionDescriptionSuccess(
3568 SetSessionDescriptionObserver* observer) {
3569 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3570 signaling_thread()->Post(RTC_FROM_HERE, this,
3571 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3572}
3573
deadbeefab9b2d12015-10-14 11:33:11 -07003574void PeerConnection::PostSetSessionDescriptionFailure(
3575 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003576 RTCError&& error) {
3577 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003578 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003579 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003580 signaling_thread()->Post(RTC_FROM_HERE, this,
3581 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003582}
3583
3584void PeerConnection::PostCreateSessionDescriptionFailure(
3585 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003586 RTCError error) {
3587 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003588 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003589 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003590 signaling_thread()->Post(RTC_FROM_HERE, this,
3591 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003592}
3593
zhihuang1c378ed2017-08-17 14:10:50 -07003594void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003595 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003596 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003597 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003598
Steve Antondcc3c022017-12-22 16:02:54 -08003599 if (IsUnifiedPlan()) {
3600 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3601 } else {
3602 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3603 }
3604
Steve Antonfa2260d2017-12-28 16:38:23 -08003605 // Intentionally unset the data channel type for RTP data channel with the
3606 // second condition. Otherwise the RTP data channels would be successfully
3607 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3608 // when building with chromium. We want to leave RTP data channels broken, so
3609 // people won't try to use them.
3610 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3611 session_options->data_channel_type = data_channel_type();
3612 }
3613
Steve Antondcc3c022017-12-22 16:02:54 -08003614 // Apply ICE restart flag and renomination flag.
3615 for (auto& options : session_options->media_description_options) {
3616 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3617 options.transport_options.enable_ice_renomination =
3618 configuration_.enable_ice_renomination;
3619 }
3620
3621 session_options->rtcp_cname = rtcp_cname_;
3622 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003623 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003624}
3625
3626void PeerConnection::GetOptionsForPlanBOffer(
3627 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3628 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003629 // Figure out transceiver directional preferences.
3630 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3631 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3632
3633 // By default, generate sendrecv/recvonly m= sections.
3634 bool recv_audio = true;
3635 bool recv_video = true;
3636
3637 // By default, only offer a new m= section if we have media to send with it.
3638 bool offer_new_audio_description = send_audio;
3639 bool offer_new_video_description = send_video;
3640 bool offer_new_data_description = HasDataChannels();
3641
3642 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003643 if (offer_answer_options.offer_to_receive_audio !=
3644 RTCOfferAnswerOptions::kUndefined) {
3645 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003646 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003647 offer_new_audio_description ||
3648 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003649 }
Steve Antondcc3c022017-12-22 16:02:54 -08003650 if (offer_answer_options.offer_to_receive_video !=
3651 RTCOfferAnswerOptions::kUndefined) {
3652 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003653 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003654 offer_new_video_description ||
3655 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003656 }
3657
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003658 absl::optional<size_t> audio_index;
3659 absl::optional<size_t> video_index;
3660 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003661 // If a current description exists, generate m= sections in the same order,
3662 // using the first audio/video/data section that appears and rejecting
3663 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003664 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003665 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003666 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003667 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3668 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3669 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003670 }
3671
zhihuang1c378ed2017-08-17 14:10:50 -07003672 // Add audio/video/data m= sections to the end if needed.
3673 if (!audio_index && offer_new_audio_description) {
3674 session_options->media_description_options.push_back(
3675 cricket::MediaDescriptionOptions(
3676 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003677 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3678 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003679 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003680 }
zhihuang1c378ed2017-08-17 14:10:50 -07003681 if (!video_index && offer_new_video_description) {
3682 session_options->media_description_options.push_back(
3683 cricket::MediaDescriptionOptions(
3684 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003685 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3686 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003687 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003688 }
zhihuang1c378ed2017-08-17 14:10:50 -07003689 if (!data_index && offer_new_data_description) {
3690 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003691 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003692 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003693 }
3694
3695 cricket::MediaDescriptionOptions* audio_media_description_options =
3696 !audio_index ? nullptr
3697 : &session_options->media_description_options[*audio_index];
3698 cricket::MediaDescriptionOptions* video_media_description_options =
3699 !video_index ? nullptr
3700 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003701
Steve Anton4171afb2017-11-20 10:20:22 -08003702 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003703 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003704}
3705
3706// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3707// and return a reference to it.
3708// Generated MIDs should be no more than 3 bytes long to take up less space in
3709// the RTP packet.
3710static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3711 RTC_DCHECK(used_mids);
3712 // We're boring: just generate MIDs 0, 1, 2, ...
3713 size_t i = 0;
3714 std::set<std::string>::iterator it;
3715 bool inserted;
3716 do {
3717 std::string mid = rtc::ToString(i++);
3718 auto insert_result = used_mids->insert(mid);
3719 it = insert_result.first;
3720 inserted = insert_result.second;
3721 } while (!inserted);
3722 return *it;
3723}
3724
3725static cricket::MediaDescriptionOptions
3726GetMediaDescriptionOptionsForTransceiver(
3727 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3728 transceiver,
3729 const std::string& mid) {
3730 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003731 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003732 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003733 // This behavior is specified in JSEP. The gist is that:
3734 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3735 // sendrecv.
3736 // 2. If the MSID is included, then it must be included in any subsequent
3737 // offer/answer exactly the same until the RtpTransceiver is stopped.
3738 if (!transceiver->stopped() &&
3739 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3740 transceiver->internal()->has_ever_been_used_to_send())) {
3741 cricket::SenderOptions sender_options;
3742 sender_options.track_id = transceiver->sender()->id();
3743 sender_options.stream_ids = transceiver->sender()->stream_ids();
3744 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3745 // set in the RTP parameters when the transceiver was added.
3746 sender_options.num_sim_layers = 1;
3747 media_description_options.sender_options.push_back(sender_options);
3748 }
Steve Antondcc3c022017-12-22 16:02:54 -08003749 return media_description_options;
3750}
3751
3752void PeerConnection::GetOptionsForUnifiedPlanOffer(
3753 const RTCOfferAnswerOptions& offer_answer_options,
3754 cricket::MediaSessionOptions* session_options) {
3755 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3756 // Offers) and 5.2.2 (Subsequent Offers).
3757 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3758 const ContentInfos& local_contents =
3759 (local_description() ? local_description()->description()->contents()
3760 : ContentInfos());
3761 const ContentInfos& remote_contents =
3762 (remote_description() ? remote_description()->description()->contents()
3763 : ContentInfos());
3764 // The mline indices that can be recycled. New transceivers should reuse these
3765 // slots first.
3766 std::queue<size_t> recycleable_mline_indices;
3767 // Track the MIDs used in previous offer/answer exchanges and the current
3768 // offer so that new, unique MIDs are generated.
3769 std::set<std::string> used_mids = seen_mids_;
3770 // First, go through each media section that exists in either the local or
3771 // remote description and generate a media section in this offer for the
3772 // associated transceiver. If a media section can be recycled, generate a
3773 // default, rejected media section here that can be later overwritten.
3774 for (size_t i = 0;
3775 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3776 // Either |local_content| or |remote_content| is non-null.
3777 const ContentInfo* local_content =
3778 (i < local_contents.size() ? &local_contents[i] : nullptr);
3779 const ContentInfo* remote_content =
3780 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3781 bool had_been_rejected = (local_content && local_content->rejected) ||
3782 (remote_content && remote_content->rejected);
3783 const std::string& mid =
3784 (local_content ? local_content->name : remote_content->name);
3785 cricket::MediaType media_type =
3786 (local_content ? local_content->media_description()->type()
3787 : remote_content->media_description()->type());
3788 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3789 media_type == cricket::MEDIA_TYPE_VIDEO) {
3790 auto transceiver = GetAssociatedTransceiver(mid);
3791 RTC_CHECK(transceiver);
3792 // A media section is considered eligible for recycling if it is marked as
3793 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003794 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003795 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003796 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3797 RtpTransceiverDirection::kInactive,
3798 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003799 recycleable_mline_indices.push(i);
3800 } else {
3801 session_options->media_description_options.push_back(
3802 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3803 // CreateOffer shouldn't really cause any state changes in
3804 // PeerConnection, but we need a way to match new transceivers to new
3805 // media sections in SetLocalDescription and JSEP specifies this is done
3806 // by recording the index of the media section generated for the
3807 // transceiver in the offer.
3808 transceiver->internal()->set_mline_index(i);
3809 }
3810 } else {
3811 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003812 RTC_CHECK(GetDataMid());
3813 if (had_been_rejected || mid != *GetDataMid()) {
3814 session_options->media_description_options.push_back(
3815 GetMediaDescriptionOptionsForRejectedData(mid));
3816 } else {
3817 session_options->media_description_options.push_back(
3818 GetMediaDescriptionOptionsForActiveData(mid));
3819 }
Steve Antondcc3c022017-12-22 16:02:54 -08003820 }
3821 }
3822 // Next, look for transceivers that are newly added (that is, are not stopped
3823 // and not associated). Reuse media sections marked as recyclable first,
3824 // otherwise append to the end of the offer. New media sections should be
3825 // added in the order they were added to the PeerConnection.
3826 for (auto transceiver : transceivers_) {
3827 if (transceiver->mid() || transceiver->stopped()) {
3828 continue;
3829 }
3830 size_t mline_index;
3831 if (!recycleable_mline_indices.empty()) {
3832 mline_index = recycleable_mline_indices.front();
3833 recycleable_mline_indices.pop();
3834 session_options->media_description_options[mline_index] =
3835 GetMediaDescriptionOptionsForTransceiver(transceiver,
3836 AllocateMid(&used_mids));
3837 } else {
3838 mline_index = session_options->media_description_options.size();
3839 session_options->media_description_options.push_back(
3840 GetMediaDescriptionOptionsForTransceiver(transceiver,
3841 AllocateMid(&used_mids)));
3842 }
3843 // See comment above for why CreateOffer changes the transceiver's state.
3844 transceiver->internal()->set_mline_index(mline_index);
3845 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003846 // Lastly, add a m-section if we have local data channels and an m section
3847 // does not already exist.
3848 if (!GetDataMid() && HasDataChannels()) {
3849 session_options->media_description_options.push_back(
3850 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3851 }
Steve Antondcc3c022017-12-22 16:02:54 -08003852}
3853
3854void PeerConnection::GetOptionsForAnswer(
3855 const RTCOfferAnswerOptions& offer_answer_options,
3856 cricket::MediaSessionOptions* session_options) {
3857 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3858
3859 if (IsUnifiedPlan()) {
3860 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3861 } else {
3862 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3863 }
3864
Steve Antonfa2260d2017-12-28 16:38:23 -08003865 // Intentionally unset the data channel type for RTP data channel. Otherwise
3866 // the RTP data channels would be successfully negotiated by default and the
3867 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3868 // We want to leave RTP data channels broken, so people won't try to use them.
3869 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3870 session_options->data_channel_type = data_channel_type();
3871 }
3872
Steve Antondcc3c022017-12-22 16:02:54 -08003873 // Apply ICE renomination flag.
3874 for (auto& options : session_options->media_description_options) {
3875 options.transport_options.enable_ice_renomination =
3876 configuration_.enable_ice_renomination;
3877 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003878
3879 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003880 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003881 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003882}
3883
Steve Antondcc3c022017-12-22 16:02:54 -08003884void PeerConnection::GetOptionsForPlanBAnswer(
3885 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003886 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003887 // Figure out transceiver directional preferences.
3888 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3889 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3890
3891 // By default, generate sendrecv/recvonly m= sections. The direction is also
3892 // restricted by the direction in the offer.
3893 bool recv_audio = true;
3894 bool recv_video = true;
3895
3896 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003897 if (offer_answer_options.offer_to_receive_audio !=
3898 RTCOfferAnswerOptions::kUndefined) {
3899 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003900 }
Steve Antondcc3c022017-12-22 16:02:54 -08003901 if (offer_answer_options.offer_to_receive_video !=
3902 RTCOfferAnswerOptions::kUndefined) {
3903 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003904 }
3905
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003906 absl::optional<size_t> audio_index;
3907 absl::optional<size_t> video_index;
3908 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003909
3910 // Generate m= sections that match those in the offer.
3911 // Note that mediasession.cc will handle intersection our preferred
3912 // direction with the offered direction.
3913 GenerateMediaDescriptionOptions(
3914 remote_description(),
3915 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3916 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3917 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003918
3919 cricket::MediaDescriptionOptions* audio_media_description_options =
3920 !audio_index ? nullptr
3921 : &session_options->media_description_options[*audio_index];
3922 cricket::MediaDescriptionOptions* video_media_description_options =
3923 !video_index ? nullptr
3924 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003925
Steve Anton4171afb2017-11-20 10:20:22 -08003926 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003927 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003928}
zhihuangaf388472016-11-02 16:49:48 -07003929
Steve Antondcc3c022017-12-22 16:02:54 -08003930void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3931 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3932 cricket::MediaSessionOptions* session_options) {
3933 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3934 // Answers) and 5.3.2 (Subsequent Answers).
3935 RTC_DCHECK(remote_description());
3936 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3937 for (const ContentInfo& content :
3938 remote_description()->description()->contents()) {
3939 cricket::MediaType media_type = content.media_description()->type();
3940 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3941 media_type == cricket::MEDIA_TYPE_VIDEO) {
3942 auto transceiver = GetAssociatedTransceiver(content.name);
3943 RTC_CHECK(transceiver);
3944 session_options->media_description_options.push_back(
3945 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3946 } else {
3947 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003948 // Reject all data sections if data channels are disabled.
3949 // Reject a data section if it has already been rejected.
3950 // Reject all data sections except for the first one.
3951 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3952 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003953 session_options->media_description_options.push_back(
3954 GetMediaDescriptionOptionsForRejectedData(content.name));
3955 } else {
3956 session_options->media_description_options.push_back(
3957 GetMediaDescriptionOptionsForActiveData(content.name));
3958 }
Steve Antondcc3c022017-12-22 16:02:54 -08003959 }
3960 }
htaa2a49d92016-03-04 02:51:39 -08003961}
3962
zhihuang1c378ed2017-08-17 14:10:50 -07003963void PeerConnection::GenerateMediaDescriptionOptions(
3964 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003965 RtpTransceiverDirection audio_direction,
3966 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003967 absl::optional<size_t>* audio_index,
3968 absl::optional<size_t>* video_index,
3969 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003970 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003971 for (const cricket::ContentInfo& content :
3972 session_desc->description()->contents()) {
3973 if (IsAudioContent(&content)) {
3974 // If we already have an audio m= section, reject this extra one.
3975 if (*audio_index) {
3976 session_options->media_description_options.push_back(
3977 cricket::MediaDescriptionOptions(
3978 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003979 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003980 } else {
3981 session_options->media_description_options.push_back(
3982 cricket::MediaDescriptionOptions(
3983 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003984 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003985 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003986 }
3987 } else if (IsVideoContent(&content)) {
3988 // If we already have an video m= section, reject this extra one.
3989 if (*video_index) {
3990 session_options->media_description_options.push_back(
3991 cricket::MediaDescriptionOptions(
3992 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003993 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003994 } else {
3995 session_options->media_description_options.push_back(
3996 cricket::MediaDescriptionOptions(
3997 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003998 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003999 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004000 }
4001 } else {
4002 RTC_DCHECK(IsDataContent(&content));
4003 // If we already have an data m= section, reject this extra one.
4004 if (*data_index) {
4005 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004006 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004007 } else {
4008 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004009 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004010 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004011 }
4012 }
htaa2a49d92016-03-04 02:51:39 -08004013 }
deadbeefab9b2d12015-10-14 11:33:11 -07004014}
4015
Steve Antonfa2260d2017-12-28 16:38:23 -08004016cricket::MediaDescriptionOptions
4017PeerConnection::GetMediaDescriptionOptionsForActiveData(
4018 const std::string& mid) const {
4019 // Direction for data sections is meaningless, but legacy endpoints might
4020 // expect sendrecv.
4021 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4022 RtpTransceiverDirection::kSendRecv,
4023 /*stopped=*/false);
4024 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4025 return options;
4026}
4027
4028cricket::MediaDescriptionOptions
4029PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4030 const std::string& mid) const {
4031 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4032 RtpTransceiverDirection::kInactive,
4033 /*stopped=*/true);
4034 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4035 return options;
4036}
4037
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004038absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004039 switch (data_channel_type_) {
4040 case cricket::DCT_RTP:
4041 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004042 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004043 }
4044 return rtp_data_channel_->content_name();
4045 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004046 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004047 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004048 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004049 }
4050}
4051
Steve Anton4171afb2017-11-20 10:20:22 -08004052void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4053 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4054 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004055 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004056}
4057
Steve Anton4171afb2017-11-20 10:20:22 -08004058void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004059 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004060 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004061 cricket::MediaType media_type,
4062 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004063 RTC_DCHECK(!IsUnifiedPlan());
4064
Steve Anton4171afb2017-11-20 10:20:22 -08004065 std::vector<RtpSenderInfo>* current_senders =
4066 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004067
Steve Anton4171afb2017-11-20 10:20:22 -08004068 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004069 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004070 for (auto sender_it = current_senders->begin();
4071 sender_it != current_senders->end();
4072 /* incremented manually */) {
4073 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004074 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004075 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004076 std::string params_stream_id;
4077 if (params) {
4078 params_stream_id =
4079 (!params->first_stream_id().empty() ? params->first_stream_id()
4080 : kDefaultStreamId);
4081 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004082 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004083 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004084 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004085 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004086 sender_exists) {
4087 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004088 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004089 OnRemoteSenderRemoved(info, media_type);
4090 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004091 }
4092 }
4093
Steve Anton4171afb2017-11-20 10:20:22 -08004094 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004095 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004096 if (!params.has_ssrcs()) {
4097 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4098 // sender, this means it is coming from a Unified Plan endpoint,so we just
4099 // create a default.
4100 default_sender_needed = true;
4101 break;
4102 }
4103
Seth Hampson845e8782018-03-02 11:34:10 -08004104 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004105 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004106 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4107 // not supported in Plan B, we just take the first here and create the
4108 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004109 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004110 (!params.first_stream_id().empty() ? params.first_stream_id()
4111 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004112 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004113 uint32_t ssrc = params.first_ssrc();
4114
4115 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004116 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004117 if (!stream) {
4118 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004119 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004120 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004121 remote_streams_->AddStream(stream);
4122 new_streams->AddStream(stream);
4123 }
4124
Steve Anton4171afb2017-11-20 10:20:22 -08004125 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004126 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004127 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004128 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004129 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004130 }
4131 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004132
Steve Anton4171afb2017-11-20 10:20:22 -08004133 // Add default sender if necessary.
4134 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004135 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004136 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004137 if (!default_stream) {
4138 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004139 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004140 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004141 remote_streams_->AddStream(default_stream);
4142 new_streams->AddStream(default_stream);
4143 }
Steve Anton4171afb2017-11-20 10:20:22 -08004144 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4145 ? kDefaultAudioSenderId
4146 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004147 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004148 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004149 if (!default_sender_info) {
4150 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004151 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004152 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004153 }
4154 }
deadbeefab9b2d12015-10-14 11:33:11 -07004155}
4156
Steve Anton4171afb2017-11-20 10:20:22 -08004157void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4158 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004159 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4160 << " receiver for track_id=" << sender_info.sender_id
4161 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004162
Steve Anton3d954a62018-04-02 11:27:23 -07004163 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004164 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004165 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004166 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004167 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004168 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004169 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004170 }
4171}
4172
Steve Anton4171afb2017-11-20 10:20:22 -08004173void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4174 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004175 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4176 << " receiver for track_id=" << sender_info.sender_id
4177 << " and stream_id=" << sender_info.stream_id;
4178
Seth Hampson845e8782018-03-02 11:34:10 -08004179 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004180
Henrik Boström933d8b02017-10-10 10:05:16 -07004181 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004182 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004183 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4184 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004185 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004186 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004187 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004188 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004189 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004190 }
4191 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004192 // Stopping or destroying a VideoRtpReceiver will end the
4193 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004194 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004195 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004196 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004197 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004198 // There's no guarantee the track is still available, e.g. the track may
4199 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004200 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004201 }
4202 } else {
nisseede5da42017-01-12 05:15:36 -08004203 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004204 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004205 if (receiver) {
4206 observer_->OnRemoveTrack(receiver);
4207 }
deadbeefab9b2d12015-10-14 11:33:11 -07004208}
4209
4210void PeerConnection::UpdateEndedRemoteMediaStreams() {
4211 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4212 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4213 MediaStreamInterface* stream = remote_streams_->at(i);
4214 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4215 streams_to_remove.push_back(stream);
4216 }
4217 }
4218
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004219 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004220 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004221 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004222 }
4223}
4224
Steve Anton4171afb2017-11-20 10:20:22 -08004225void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004226 const std::vector<cricket::StreamParams>& streams,
4227 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004228 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004229
Seth Hampson845e8782018-03-02 11:34:10 -08004230 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004231 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004232 for (auto sender_it = current_senders->begin();
4233 sender_it != current_senders->end();
4234 /* incremented manually */) {
4235 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004236 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004237 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4238 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004239 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004240 OnLocalSenderRemoved(info, media_type);
4241 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004242 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004243 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004244 }
4245 }
4246
Steve Anton4171afb2017-11-20 10:20:22 -08004247 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004248 for (const cricket::StreamParams& params : streams) {
4249 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004250 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004251 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004252 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004253 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004254 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004255 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004256 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004257 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004258 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004259 }
4260 }
4261}
4262
Steve Anton4171afb2017-11-20 10:20:22 -08004263void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4264 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004265 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004266 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004267 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004268 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4269 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004270 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004271 return;
4272 }
4273
deadbeeffac06552015-11-25 11:26:01 -08004274 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004275 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004276 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004277 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004278 }
deadbeeffac06552015-11-25 11:26:01 -08004279
Seth Hampson5b4f0752018-04-02 16:31:36 -07004280 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004281 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004282}
4283
Steve Anton4171afb2017-11-20 10:20:22 -08004284void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4285 cricket::MediaType media_type) {
4286 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004287 if (!sender) {
4288 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004289 // SessionDescriptions has been renegotiated.
4290 return;
4291 }
deadbeeffac06552015-11-25 11:26:01 -08004292
4293 // A sender has been removed from the SessionDescription but it's still
4294 // associated with the PeerConnection. This only occurs if the SDP doesn't
4295 // match with the calls to CreateSender, AddStream and RemoveStream.
4296 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004297 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004298 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004299 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004300 }
deadbeeffac06552015-11-25 11:26:01 -08004301
Steve Anton4171afb2017-11-20 10:20:22 -08004302 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004303}
4304
4305void PeerConnection::UpdateLocalRtpDataChannels(
4306 const cricket::StreamParamsVec& streams) {
4307 std::vector<std::string> existing_channels;
4308
4309 // Find new and active data channels.
4310 for (const cricket::StreamParams& params : streams) {
4311 // |it->sync_label| is actually the data channel label. The reason is that
4312 // we use the same naming of data channels as we do for
4313 // MediaStreams and Tracks.
4314 // For MediaStreams, the sync_label is the MediaStream label and the
4315 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004316 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004317 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004318 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004319 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004320 continue;
4321 }
4322 // Set the SSRC the data channel should use for sending.
4323 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4324 existing_channels.push_back(data_channel_it->first);
4325 }
4326
4327 UpdateClosingRtpDataChannels(existing_channels, true);
4328}
4329
4330void PeerConnection::UpdateRemoteRtpDataChannels(
4331 const cricket::StreamParamsVec& streams) {
4332 std::vector<std::string> existing_channels;
4333
4334 // Find new and active data channels.
4335 for (const cricket::StreamParams& params : streams) {
4336 // The data channel label is either the mslabel or the SSRC if the mslabel
4337 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004338 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004339 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004340 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004341 auto data_channel_it = rtp_data_channels_.find(label);
4342 if (data_channel_it == rtp_data_channels_.end()) {
4343 // This is a new data channel.
4344 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4345 } else {
4346 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4347 }
4348 existing_channels.push_back(label);
4349 }
4350
4351 UpdateClosingRtpDataChannels(existing_channels, false);
4352}
4353
4354void PeerConnection::UpdateClosingRtpDataChannels(
4355 const std::vector<std::string>& active_channels,
4356 bool is_local_update) {
4357 auto it = rtp_data_channels_.begin();
4358 while (it != rtp_data_channels_.end()) {
4359 DataChannel* data_channel = it->second;
4360 if (std::find(active_channels.begin(), active_channels.end(),
4361 data_channel->label()) != active_channels.end()) {
4362 ++it;
4363 continue;
4364 }
4365
4366 if (is_local_update) {
4367 data_channel->SetSendSsrc(0);
4368 } else {
4369 data_channel->RemotePeerRequestClose();
4370 }
4371
4372 if (data_channel->state() == DataChannel::kClosed) {
4373 rtp_data_channels_.erase(it);
4374 it = rtp_data_channels_.begin();
4375 } else {
4376 ++it;
4377 }
4378 }
4379}
4380
4381void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4382 uint32_t remote_ssrc) {
4383 rtc::scoped_refptr<DataChannel> channel(
4384 InternalCreateDataChannel(label, nullptr));
4385 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004386 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004387 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004388 return;
4389 }
4390 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004391 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4392 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004393 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004394}
4395
4396rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4397 const std::string& label,
4398 const InternalDataChannelInit* config) {
4399 if (IsClosed()) {
4400 return nullptr;
4401 }
Steve Anton75737c02017-11-06 10:37:17 -08004402 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004403 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004404 << "InternalCreateDataChannel: Data is not supported in this call.";
4405 return nullptr;
4406 }
4407 InternalDataChannelInit new_config =
4408 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004409 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004410 if (new_config.id < 0) {
4411 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004412 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004413 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004414 RTC_LOG(LS_ERROR)
4415 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004416 return nullptr;
4417 }
4418 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004419 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004420 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004421 return nullptr;
4422 }
4423 }
4424
Steve Anton75737c02017-11-06 10:37:17 -08004425 rtc::scoped_refptr<DataChannel> channel(
4426 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004427 if (!channel) {
4428 sid_allocator_.ReleaseSid(new_config.id);
4429 return nullptr;
4430 }
4431
4432 if (channel->data_channel_type() == cricket::DCT_RTP) {
4433 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004434 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4435 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004436 return nullptr;
4437 }
4438 rtp_data_channels_[channel->label()] = channel;
4439 } else {
4440 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4441 sctp_data_channels_.push_back(channel);
4442 channel->SignalClosed.connect(this,
4443 &PeerConnection::OnSctpDataChannelClosed);
4444 }
4445
Steve Anton2d8609c2018-01-23 16:38:46 -08004446 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004447 return channel;
4448}
4449
4450bool PeerConnection::HasDataChannels() const {
4451 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4452}
4453
4454void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4455 for (const auto& channel : sctp_data_channels_) {
4456 if (channel->id() < 0) {
4457 int sid;
4458 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004459 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004460 continue;
4461 }
4462 channel->SetSctpSid(sid);
4463 }
4464 }
4465}
4466
4467void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004468 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004469 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4470 ++it) {
4471 if (it->get() == channel) {
4472 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004473 // After the closing procedure is done, it's safe to use this ID for
4474 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004475 sid_allocator_.ReleaseSid(channel->id());
4476 }
deadbeefbd292462015-12-14 18:15:29 -08004477 // Since this method is triggered by a signal from the DataChannel,
4478 // we can't free it directly here; we need to free it asynchronously.
4479 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004480 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004481 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4482 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004483 return;
4484 }
4485 }
4486}
4487
deadbeefab9b2d12015-10-14 11:33:11 -07004488void PeerConnection::OnDataChannelDestroyed() {
4489 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4490 // DataChannel may callback to us and try to modify the list.
4491 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4492 temp_rtp_dcs.swap(rtp_data_channels_);
4493 for (const auto& kv : temp_rtp_dcs) {
4494 kv.second->OnTransportChannelDestroyed();
4495 }
4496
4497 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4498 temp_sctp_dcs.swap(sctp_data_channels_);
4499 for (const auto& channel : temp_sctp_dcs) {
4500 channel->OnTransportChannelDestroyed();
4501 }
4502}
4503
4504void PeerConnection::OnDataChannelOpenMessage(
4505 const std::string& label,
4506 const InternalDataChannelInit& config) {
4507 rtc::scoped_refptr<DataChannel> channel(
4508 InternalCreateDataChannel(label, &config));
4509 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004510 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004511 return;
4512 }
4513
deadbeefa601f5c2016-06-06 14:27:39 -07004514 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4515 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004516 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004517}
4518
Steve Anton4171afb2017-11-20 10:20:22 -08004519rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4520PeerConnection::GetAudioTransceiver() const {
4521 // This method only works with Plan B SDP, where there is a single
4522 // audio/video transceiver.
4523 RTC_DCHECK(!IsUnifiedPlan());
4524 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004525 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004526 return transceiver;
4527 }
4528 }
4529 RTC_NOTREACHED();
4530 return nullptr;
4531}
4532
4533rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4534PeerConnection::GetVideoTransceiver() const {
4535 // This method only works with Plan B SDP, where there is a single
4536 // audio/video transceiver.
4537 RTC_DCHECK(!IsUnifiedPlan());
4538 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004539 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004540 return transceiver;
4541 }
4542 }
4543 RTC_NOTREACHED();
4544 return nullptr;
4545}
4546
4547// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4548// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004549bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004550 switch (type) {
4551 case cricket::MEDIA_TYPE_AUDIO:
4552 return !GetAudioTransceiver()->internal()->senders().empty();
4553 case cricket::MEDIA_TYPE_VIDEO:
4554 return !GetVideoTransceiver()->internal()->senders().empty();
4555 case cricket::MEDIA_TYPE_DATA:
4556 return false;
4557 }
4558 RTC_NOTREACHED();
4559 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004560}
4561
Steve Anton4171afb2017-11-20 10:20:22 -08004562rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4563PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4564 for (auto transceiver : transceivers_) {
4565 for (auto sender : transceiver->internal()->senders()) {
4566 if (sender->track() == track) {
4567 return sender;
4568 }
4569 }
4570 }
4571 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004572}
4573
Steve Anton4171afb2017-11-20 10:20:22 -08004574rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4575PeerConnection::FindSenderById(const std::string& sender_id) const {
4576 for (auto transceiver : transceivers_) {
4577 for (auto sender : transceiver->internal()->senders()) {
4578 if (sender->id() == sender_id) {
4579 return sender;
4580 }
4581 }
4582 }
4583 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004584}
4585
Steve Anton4171afb2017-11-20 10:20:22 -08004586rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4587PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4588 for (auto transceiver : transceivers_) {
4589 for (auto receiver : transceiver->internal()->receivers()) {
4590 if (receiver->id() == receiver_id) {
4591 return receiver;
4592 }
4593 }
4594 }
4595 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004596}
4597
Steve Anton4171afb2017-11-20 10:20:22 -08004598std::vector<PeerConnection::RtpSenderInfo>*
4599PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4600 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4601 media_type == cricket::MEDIA_TYPE_VIDEO);
4602 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4603 ? &remote_audio_sender_infos_
4604 : &remote_video_sender_infos_;
4605}
4606
4607std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004608 cricket::MediaType media_type) {
4609 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4610 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004611 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4612 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004613}
4614
Steve Anton4171afb2017-11-20 10:20:22 -08004615const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4616 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004617 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004618 const std::string sender_id) const {
4619 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004620 if (sender_info.stream_id == stream_id &&
4621 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004622 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004623 }
4624 }
4625 return nullptr;
4626}
4627
4628DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4629 for (const auto& channel : sctp_data_channels_) {
4630 if (channel->id() == sid) {
4631 return channel;
4632 }
4633 }
4634 return nullptr;
4635}
4636
deadbeef91dd5672016-05-18 16:55:30 -07004637bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004638 const RTCConfiguration& configuration) {
4639 cricket::ServerAddresses stun_servers;
4640 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004641 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4642 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004643 return false;
4644 }
4645
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004646 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004647 // To handle both internal and externally created port allocator, we will
4648 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004649 port_allocator_flags_ = port_allocator_->flags();
4650 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4651 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4652 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004653 // If the disable-IPv6 flag was specified, we'll not override it
4654 // by experiment.
4655 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004656 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004657 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4658 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004659 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004660 }
4661
zhihuangb09b3f92017-03-07 14:40:51 -08004662 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004663 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004664 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004665 }
4666
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004667 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004668 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004669 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004670 }
4671
honghaiz60347052016-05-31 18:29:12 -07004672 if (configuration.candidate_network_policy ==
4673 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004674 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004675 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004676 }
4677
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004678 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004679 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004680 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4681 }
4682
Qingsi Wanga2d60672018-04-11 16:57:45 -07004683 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004684 // No step delay is used while allocating ports.
4685 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4686 port_allocator_->set_candidate_filter(
4687 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004688 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004689
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004690 if (tls_cert_verifier_ != nullptr) {
4691 for (auto& turn_server : turn_servers) {
4692 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4693 }
4694 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004695 // Call this last since it may create pooled allocator sessions using the
4696 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004697 port_allocator_->SetConfiguration(
4698 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4699 configuration.prune_turn_ports, configuration.turn_customizer,
4700 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004701 return true;
4702}
4703
deadbeef91dd5672016-05-18 16:55:30 -07004704bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004705 const cricket::ServerAddresses& stun_servers,
4706 const std::vector<cricket::RelayServerConfig>& turn_servers,
4707 IceTransportsType type,
4708 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004709 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004710 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004711 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004712 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004713 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004714 // According to JSEP, after setLocalDescription, changing the candidate pool
4715 // size is not allowed, and changing the set of ICE servers will not result
4716 // in new candidates being gathered.
4717 if (local_description()) {
4718 port_allocator_->FreezeCandidatePool();
4719 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004720 // Call this last since it may create pooled allocator sessions using the
4721 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004722 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004723 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004724 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004725}
4726
Steve Antonba818672017-11-06 10:21:57 -08004727cricket::ChannelManager* PeerConnection::channel_manager() const {
4728 return factory_->channel_manager();
4729}
4730
4731MetricsObserverInterface* PeerConnection::metrics_observer() const {
4732 return uma_observer_;
4733}
4734
Elad Alon99c3fe52017-10-13 16:29:40 +02004735bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004736 std::unique_ptr<RtcEventLogOutput> output,
4737 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004738 if (!event_log_) {
4739 return false;
4740 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004741 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004742}
4743
4744void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004745 if (event_log_) {
4746 event_log_->StopLogging();
4747 }
ivoc14d5dbe2016-07-04 07:06:55 -07004748}
nisseeaabdf62017-05-05 02:23:02 -07004749
Steve Anton75737c02017-11-06 10:37:17 -08004750cricket::BaseChannel* PeerConnection::GetChannel(
4751 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004752 for (auto transceiver : transceivers_) {
4753 cricket::BaseChannel* channel = transceiver->internal()->channel();
4754 if (channel && channel->content_name() == content_name) {
4755 return channel;
4756 }
Steve Anton75737c02017-11-06 10:37:17 -08004757 }
4758 if (rtp_data_channel() &&
4759 rtp_data_channel()->content_name() == content_name) {
4760 return rtp_data_channel();
4761 }
4762 return nullptr;
4763}
4764
4765bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4766 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004767 RTC_LOG(LS_INFO)
4768 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004769 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004770 return false;
4771 }
4772 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004773 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004774 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004775 return false;
4776 }
4777
Zhi Huange830e682018-03-30 10:48:35 -07004778 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4779 if (dtls_role) {
4780 *role = *dtls_role;
4781 return true;
4782 }
4783 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004784}
4785
4786bool PeerConnection::GetSslRole(const std::string& content_name,
4787 rtc::SSLRole* role) {
4788 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004789 RTC_LOG(LS_INFO)
4790 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004791 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004792 return false;
4793 }
4794
Zhi Huange830e682018-03-30 10:48:35 -07004795 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4796 if (dtls_role) {
4797 *role = *dtls_role;
4798 return true;
4799 }
4800 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004801}
4802
Steve Antonf8470812017-12-04 10:46:21 -08004803void PeerConnection::SetSessionError(SessionError error,
4804 const std::string& error_desc) {
4805 RTC_DCHECK_RUN_ON(signaling_thread());
4806 if (error != session_error_) {
4807 session_error_ = error;
4808 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004809 }
4810}
4811
Zhi Huange830e682018-03-30 10:48:35 -07004812RTCError PeerConnection::UpdateSessionState(
4813 SdpType type,
4814 cricket::ContentSource source,
4815 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004816 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004817
4818 // If there's already a pending error then no state transition should happen.
4819 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004820 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004821
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004822 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004823 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004824 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004825 }
4826
4827 // Update the signaling state according to the specified state machine (see
4828 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004829 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004830 ChangeSignalingState(source == cricket::CS_LOCAL
4831 ? PeerConnectionInterface::kHaveLocalOffer
4832 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004833 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004834 ChangeSignalingState(source == cricket::CS_LOCAL
4835 ? PeerConnectionInterface::kHaveLocalPrAnswer
4836 : PeerConnectionInterface::kHaveRemotePrAnswer);
4837 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004838 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004839 ChangeSignalingState(PeerConnectionInterface::kStable);
4840 }
4841
4842 // Update internal objects according to the session description's media
4843 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004844 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004845 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004846 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004847 }
4848
Steve Anton8a006912017-12-04 15:25:56 -08004849 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004850}
4851
Steve Anton8a006912017-12-04 15:25:56 -08004852RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004853 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004854 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004855 const SessionDescriptionInterface* sdesc =
4856 (source == cricket::CS_LOCAL ? local_description()
4857 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004858 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004859
4860 // Push down the new SDP media section for each audio/video transceiver.
4861 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004862 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004863 FindMediaSectionForTransceiver(transceiver, sdesc);
4864 cricket::BaseChannel* channel = transceiver->internal()->channel();
4865 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004866 continue;
4867 }
4868 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004869 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004870 if (!content_desc) {
4871 continue;
4872 }
4873 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004874 bool success = (source == cricket::CS_LOCAL)
4875 ? channel->SetLocalContent(content_desc, type, &error)
4876 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004877 if (!success) {
4878 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4879 }
4880 }
4881
4882 // If using the RtpDataChannel, push down the new SDP section for it too.
4883 if (rtp_data_channel_) {
4884 const ContentInfo* data_content =
4885 cricket::GetFirstDataContent(sdesc->description());
4886 if (data_content && !data_content->rejected) {
4887 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004888 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004889 if (data_desc) {
4890 std::string error;
4891 bool success =
4892 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004893 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004894 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004895 if (!success) {
4896 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4897 std::move(error));
4898 }
Steve Anton75737c02017-11-06 10:37:17 -08004899 }
4900 }
4901 }
Steve Antoned10bd92017-12-05 10:52:59 -08004902
Steve Anton75737c02017-11-06 10:37:17 -08004903 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4904 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4905 if (sctp_transport_ && local_description() && remote_description() &&
4906 cricket::GetFirstDataContent(local_description()->description()) &&
4907 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004908 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004909 RTC_FROM_HERE,
4910 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004911 if (!success) {
4912 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4913 "Failed to push down SCTP parameters.");
4914 }
Steve Anton75737c02017-11-06 10:37:17 -08004915 }
Steve Antoned10bd92017-12-05 10:52:59 -08004916
Steve Anton8a006912017-12-04 15:25:56 -08004917 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004918}
4919
4920bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4921 RTC_DCHECK(network_thread()->IsCurrent());
4922 RTC_DCHECK(local_description());
4923 RTC_DCHECK(remote_description());
4924 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4925 // When we support "max-message-size", that would also be pushed down here.
4926 return sctp_transport_->Start(
4927 GetSctpPort(local_description()->description()),
4928 GetSctpPort(remote_description()->description()));
4929}
4930
Steve Anton8a006912017-12-04 15:25:56 -08004931RTCError PeerConnection::PushdownTransportDescription(
4932 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004933 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004934 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004935
Zhi Huange830e682018-03-30 10:48:35 -07004936 if (source == cricket::CS_LOCAL) {
4937 const SessionDescriptionInterface* sdesc = local_description();
4938 RTC_DCHECK(sdesc);
4939 return transport_controller_->SetLocalDescription(type,
4940 sdesc->description());
4941 } else {
4942 const SessionDescriptionInterface* sdesc = remote_description();
4943 RTC_DCHECK(sdesc);
4944 return transport_controller_->SetRemoteDescription(type,
4945 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004946 }
Steve Anton75737c02017-11-06 10:37:17 -08004947}
4948
4949bool PeerConnection::GetTransportDescription(
4950 const SessionDescription* description,
4951 const std::string& content_name,
4952 cricket::TransportDescription* tdesc) {
4953 if (!description || !tdesc) {
4954 return false;
4955 }
4956 const TransportInfo* transport_info =
4957 description->GetTransportInfoByName(content_name);
4958 if (!transport_info) {
4959 return false;
4960 }
4961 *tdesc = transport_info->description;
4962 return true;
4963}
4964
Steve Anton75737c02017-11-06 10:37:17 -08004965cricket::IceConfig PeerConnection::ParseIceConfig(
4966 const PeerConnectionInterface::RTCConfiguration& config) const {
4967 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004968 switch (config.continual_gathering_policy) {
4969 case PeerConnectionInterface::GATHER_ONCE:
4970 gathering_policy = cricket::GATHER_ONCE;
4971 break;
4972 case PeerConnectionInterface::GATHER_CONTINUALLY:
4973 gathering_policy = cricket::GATHER_CONTINUALLY;
4974 break;
4975 default:
4976 RTC_NOTREACHED();
4977 gathering_policy = cricket::GATHER_ONCE;
4978 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004979
Steve Anton75737c02017-11-06 10:37:17 -08004980 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004981 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4982 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004983 ice_config.prioritize_most_likely_candidate_pairs =
4984 config.prioritize_most_likely_ice_candidate_pairs;
4985 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004986 RTCConfigurationToIceConfigOptionalInt(
4987 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004988 ice_config.continual_gathering_policy = gathering_policy;
4989 ice_config.presume_writable_when_fully_relayed =
4990 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004991 ice_config.ice_check_interval_strong_connectivity =
4992 config.ice_check_interval_strong_connectivity;
4993 ice_config.ice_check_interval_weak_connectivity =
4994 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004995 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004996 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004997 ice_config.regather_all_networks_interval_range =
4998 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004999 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005000 return ice_config;
5001}
5002
Steve Anton75737c02017-11-06 10:37:17 -08005003bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5004 std::string* track_id) {
5005 if (!local_description()) {
5006 return false;
5007 }
5008 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5009 track_id);
5010}
5011
5012bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5013 std::string* track_id) {
5014 if (!remote_description()) {
5015 return false;
5016 }
5017 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5018 track_id);
5019}
5020
5021bool PeerConnection::SendData(const cricket::SendDataParams& params,
5022 const rtc::CopyOnWriteBuffer& payload,
5023 cricket::SendDataResult* result) {
5024 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005025 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005026 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005027 return false;
5028 }
5029 return rtp_data_channel_
5030 ? rtp_data_channel_->SendData(params, payload, result)
5031 : network_thread()->Invoke<bool>(
5032 RTC_FROM_HERE,
5033 Bind(&cricket::SctpTransportInternal::SendData,
5034 sctp_transport_.get(), params, payload, result));
5035}
5036
5037bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5038 if (!rtp_data_channel_ && !sctp_transport_) {
5039 // Don't log an error here, because DataChannels are expected to call
5040 // ConnectDataChannel in this state. It's the only way to initially tell
5041 // whether or not the underlying transport is ready.
5042 return false;
5043 }
5044 if (rtp_data_channel_) {
5045 rtp_data_channel_->SignalReadyToSendData.connect(
5046 webrtc_data_channel, &DataChannel::OnChannelReady);
5047 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5048 &DataChannel::OnDataReceived);
5049 } else {
5050 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5051 &DataChannel::OnChannelReady);
5052 SignalSctpDataReceived.connect(webrtc_data_channel,
5053 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005054 SignalSctpClosingProcedureStartedRemotely.connect(
5055 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5056 SignalSctpClosingProcedureComplete.connect(
5057 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005058 }
5059 return true;
5060}
5061
5062void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5063 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005064 RTC_LOG(LS_ERROR)
5065 << "DisconnectDataChannel called when rtp_data_channel_ and "
5066 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005067 return;
5068 }
5069 if (rtp_data_channel_) {
5070 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5071 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5072 } else {
5073 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5074 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005075 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5076 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005077 }
5078}
5079
5080void PeerConnection::AddSctpDataStream(int sid) {
5081 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005082 RTC_LOG(LS_ERROR)
5083 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005084 return;
5085 }
5086 network_thread()->Invoke<void>(
5087 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5088 sctp_transport_.get(), sid));
5089}
5090
5091void PeerConnection::RemoveSctpDataStream(int sid) {
5092 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005093 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005094 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005095 return;
5096 }
5097 network_thread()->Invoke<void>(
5098 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5099 sctp_transport_.get(), sid));
5100}
5101
5102bool PeerConnection::ReadyToSendData() const {
5103 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5104 sctp_ready_to_send_data_;
5105}
5106
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005107absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005108 if (sctp_mid_ && transport_controller_) {
5109 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5110 if (dtls_transport) {
5111 return dtls_transport->transport_name();
5112 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005113 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005114 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005115 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005116}
5117
Qingsi Wang72a43a12018-02-20 16:03:18 -08005118cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5119 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005120 network_thread()->Invoke<void>(
5121 RTC_FROM_HERE,
5122 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5123 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005124 return candidate_states_list;
5125}
5126
Steve Anton5dfde182018-02-06 10:34:40 -08005127std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5128 const {
5129 std::map<std::string, std::string> transport_names_by_mid;
5130 for (auto transceiver : transceivers_) {
5131 cricket::BaseChannel* channel = transceiver->internal()->channel();
5132 if (channel) {
5133 transport_names_by_mid[channel->content_name()] =
5134 channel->transport_name();
5135 }
Steve Anton75737c02017-11-06 10:37:17 -08005136 }
Steve Anton5dfde182018-02-06 10:34:40 -08005137 if (rtp_data_channel_) {
5138 transport_names_by_mid[rtp_data_channel_->content_name()] =
5139 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005140 }
5141 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005142 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005143 RTC_DCHECK(transport_name);
5144 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005145 }
Steve Anton5dfde182018-02-06 10:34:40 -08005146 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005147}
5148
Steve Anton5dfde182018-02-06 10:34:40 -08005149std::map<std::string, cricket::TransportStats>
5150PeerConnection::GetTransportStatsByNames(
5151 const std::set<std::string>& transport_names) {
5152 if (!network_thread()->IsCurrent()) {
5153 return network_thread()
5154 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5155 RTC_FROM_HERE,
5156 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005157 }
Steve Anton5dfde182018-02-06 10:34:40 -08005158 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5159 for (const std::string& transport_name : transport_names) {
5160 cricket::TransportStats transport_stats;
5161 bool success =
5162 transport_controller_->GetStats(transport_name, &transport_stats);
5163 if (success) {
5164 transport_stats_by_name[transport_name] = std::move(transport_stats);
5165 } else {
5166 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5167 << transport_name;
5168 }
5169 }
5170 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005171}
5172
5173bool PeerConnection::GetLocalCertificate(
5174 const std::string& transport_name,
5175 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005176 if (!certificate) {
5177 return false;
5178 }
5179 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5180 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005181}
5182
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005183std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005184 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005185 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005186}
5187
5188cricket::DataChannelType PeerConnection::data_channel_type() const {
5189 return data_channel_type_;
5190}
5191
5192bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5193 return pending_ice_restarts_.find(content_name) !=
5194 pending_ice_restarts_.end();
5195}
5196
Steve Anton75737c02017-11-06 10:37:17 -08005197bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5198 return transport_controller_->NeedsIceRestart(content_name);
5199}
5200
5201void PeerConnection::OnCertificateReady(
5202 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5203 transport_controller_->SetLocalCertificate(certificate);
5204}
5205
5206void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005207 SetSessionError(SessionError::kTransport,
5208 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005209}
5210
5211void PeerConnection::OnTransportControllerConnectionState(
5212 cricket::IceConnectionState state) {
5213 switch (state) {
5214 case cricket::kIceConnectionConnecting:
5215 // If the current state is Connected or Completed, then there were
5216 // writable channels but now there are not, so the next state must
5217 // be Disconnected.
5218 // kIceConnectionConnecting is currently used as the default,
5219 // un-connected state by the TransportController, so its only use is
5220 // detecting disconnections.
5221 if (ice_connection_state_ ==
5222 PeerConnectionInterface::kIceConnectionConnected ||
5223 ice_connection_state_ ==
5224 PeerConnectionInterface::kIceConnectionCompleted) {
5225 SetIceConnectionState(
5226 PeerConnectionInterface::kIceConnectionDisconnected);
5227 }
5228 break;
5229 case cricket::kIceConnectionFailed:
5230 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5231 break;
5232 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005233 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005234 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005235 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005236 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005237 break;
5238 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005239 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005240 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005241 if (ice_connection_state_ !=
5242 PeerConnectionInterface::kIceConnectionConnected) {
5243 // If jumping directly from "checking" to "connected",
5244 // signal "connected" first.
5245 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5246 }
5247 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005248 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005249 if (metrics_observer()) {
5250 ReportTransportStats();
5251 }
5252 break;
5253 default:
5254 RTC_NOTREACHED();
5255 }
5256}
5257
5258void PeerConnection::OnTransportControllerCandidatesGathered(
5259 const std::string& transport_name,
5260 const cricket::Candidates& candidates) {
5261 RTC_DCHECK(signaling_thread()->IsCurrent());
5262 int sdp_mline_index;
5263 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005264 RTC_LOG(LS_ERROR)
5265 << "OnTransportControllerCandidatesGathered: content name "
5266 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005267 return;
5268 }
5269
5270 for (cricket::Candidates::const_iterator citer = candidates.begin();
5271 citer != candidates.end(); ++citer) {
5272 // Use transport_name as the candidate media id.
5273 std::unique_ptr<JsepIceCandidate> candidate(
5274 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5275 if (local_description()) {
5276 mutable_local_description()->AddCandidate(candidate.get());
5277 }
5278 OnIceCandidate(std::move(candidate));
5279 }
5280}
5281
5282void PeerConnection::OnTransportControllerCandidatesRemoved(
5283 const std::vector<cricket::Candidate>& candidates) {
5284 RTC_DCHECK(signaling_thread()->IsCurrent());
5285 // Sanity check.
5286 for (const cricket::Candidate& candidate : candidates) {
5287 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005288 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005289 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005290 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005291 return;
5292 }
5293 }
5294
5295 if (local_description()) {
5296 mutable_local_description()->RemoveCandidates(candidates);
5297 }
5298 OnIceCandidatesRemoved(candidates);
5299}
5300
5301void PeerConnection::OnTransportControllerDtlsHandshakeError(
5302 rtc::SSLHandshakeError error) {
5303 if (metrics_observer()) {
5304 metrics_observer()->IncrementEnumCounter(
5305 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5306 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5307 }
5308}
5309
Steve Antoned10bd92017-12-05 10:52:59 -08005310void PeerConnection::EnableSending() {
5311 for (auto transceiver : transceivers_) {
5312 cricket::BaseChannel* channel = transceiver->internal()->channel();
5313 if (channel && !channel->enabled()) {
5314 channel->Enable(true);
5315 }
Steve Anton75737c02017-11-06 10:37:17 -08005316 }
5317
Steve Anton4171afb2017-11-20 10:20:22 -08005318 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005319 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005320 }
Steve Anton75737c02017-11-06 10:37:17 -08005321}
5322
5323// Returns the media index for a local ice candidate given the content name.
5324bool PeerConnection::GetLocalCandidateMediaIndex(
5325 const std::string& content_name,
5326 int* sdp_mline_index) {
5327 if (!local_description() || !sdp_mline_index) {
5328 return false;
5329 }
5330
5331 bool content_found = false;
5332 const ContentInfos& contents = local_description()->description()->contents();
5333 for (size_t index = 0; index < contents.size(); ++index) {
5334 if (contents[index].name == content_name) {
5335 *sdp_mline_index = static_cast<int>(index);
5336 content_found = true;
5337 break;
5338 }
5339 }
5340 return content_found;
5341}
5342
5343bool PeerConnection::UseCandidatesInSessionDescription(
5344 const SessionDescriptionInterface* remote_desc) {
5345 if (!remote_desc) {
5346 return true;
5347 }
5348 bool ret = true;
5349
5350 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5351 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5352 for (size_t n = 0; n < candidates->count(); ++n) {
5353 const IceCandidateInterface* candidate = candidates->at(n);
5354 bool valid = false;
5355 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5356 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005357 RTC_LOG(LS_INFO)
5358 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005359 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005360 }
5361 continue;
5362 }
5363 ret = UseCandidate(candidate);
5364 if (!ret) {
5365 break;
5366 }
5367 }
5368 }
5369 return ret;
5370}
5371
5372bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5373 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5374 size_t remote_content_size =
5375 remote_description()->description()->contents().size();
5376 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005377 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005378 return false;
5379 }
5380
5381 cricket::ContentInfo content =
5382 remote_description()->description()->contents()[mediacontent_index];
5383 std::vector<cricket::Candidate> candidates;
5384 candidates.push_back(candidate->candidate());
5385 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005386 RTCError error =
5387 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005388 if (error.ok()) {
5389 // Candidates successfully submitted for checking.
5390 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5391 ice_connection_state_ ==
5392 PeerConnectionInterface::kIceConnectionDisconnected) {
5393 // If state is New, then the session has just gotten its first remote ICE
5394 // candidates, so go to Checking.
5395 // If state is Disconnected, the session is re-using old candidates or
5396 // receiving additional ones, so go to Checking.
5397 // If state is Connected, stay Connected.
5398 // TODO(bemasc): If state is Connected, and the new candidates are for a
5399 // newly added transport, then the state actually _should_ move to
5400 // checking. Add a way to distinguish that case.
5401 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5402 }
5403 // TODO(bemasc): If state is Completed, go back to Connected.
5404 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005405 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005406 }
5407 return true;
5408}
5409
5410void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005411 // Destroy video channel first since it may have a pointer to the
5412 // voice channel.
5413 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005414 if (!video_info || video_info->rejected) {
5415 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005416 }
5417
Steve Anton6fec8802017-12-04 10:37:29 -08005418 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5419 if (!audio_info || audio_info->rejected) {
5420 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005421 }
5422
5423 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5424 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005425 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005426 }
5427}
5428
Steve Antondcc3c022017-12-22 16:02:54 -08005429RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5430 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005431 const cricket::ContentGroup* bundle_group = nullptr;
5432 if (configuration_.bundle_policy ==
5433 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005434 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005435 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005436 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5437 "max-bundle configured but session description "
5438 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005439 }
5440 }
Steve Antondcc3c022017-12-22 16:02:54 -08005441 return std::move(bundle_group);
5442}
5443
5444RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005445 // Creating the media channels. Transports should already have been created
5446 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005447 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005448 if (voice && !voice->rejected &&
5449 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005450 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005451 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005452 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5453 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005454 }
5455 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5456 }
5457
Steve Antondcc3c022017-12-22 16:02:54 -08005458 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005459 if (video && !video->rejected &&
5460 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005461 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005462 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005463 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5464 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005465 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005466 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005467 }
5468
Steve Antondcc3c022017-12-22 16:02:54 -08005469 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005470 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5471 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005472 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005473 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5474 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005475 }
5476 }
5477
Steve Anton8a006912017-12-04 15:25:56 -08005478 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005479}
5480
Steve Anton4171afb2017-11-20 10:20:22 -08005481// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005482cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005483 const std::string& mid) {
5484 RtpTransportInternal* rtp_transport =
5485 transport_controller_->GetRtpTransport(mid);
5486 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005487 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005488 call_.get(), configuration_.media_config, rtp_transport,
5489 signaling_thread(), mid, SrtpRequired(),
5490 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005491 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005492 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005493 }
Steve Anton75737c02017-11-06 10:37:17 -08005494 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5495 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005496 voice_channel->SignalSentPacket.connect(this,
5497 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005498 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005499 if (uma_observer_) {
5500 voice_channel->SetMetricsObserver(uma_observer_);
5501 }
Steve Anton4171afb2017-11-20 10:20:22 -08005502
Steve Antoneda6ccd2017-12-04 10:21:55 -08005503 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005504}
5505
Steve Anton4171afb2017-11-20 10:20:22 -08005506// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005507cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005508 const std::string& mid) {
5509 RtpTransportInternal* rtp_transport =
5510 transport_controller_->GetRtpTransport(mid);
5511 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005512 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005513 call_.get(), configuration_.media_config, rtp_transport,
5514 signaling_thread(), mid, SrtpRequired(),
5515 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005516 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005517 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005518 }
Steve Anton75737c02017-11-06 10:37:17 -08005519 video_channel->SignalDtlsSrtpSetupFailure.connect(
5520 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005521 video_channel->SignalSentPacket.connect(this,
5522 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005523 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005524 if (uma_observer_) {
5525 video_channel->SetMetricsObserver(uma_observer_);
5526 }
Steve Anton4171afb2017-11-20 10:20:22 -08005527
Steve Antoneda6ccd2017-12-04 10:21:55 -08005528 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005529}
5530
Zhi Huange830e682018-03-30 10:48:35 -07005531bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005532 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5533 if (sctp) {
5534 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005535 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005536 << "Trying to create SCTP transport, but didn't compile with "
5537 "SCTP support (HAVE_SCTP)";
5538 return false;
5539 }
5540 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005541 RTC_FROM_HERE,
5542 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005543 return false;
5544 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005545 for (const auto& channel : sctp_data_channels_) {
5546 channel->OnTransportChannelCreated();
5547 }
Steve Anton75737c02017-11-06 10:37:17 -08005548 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005549 RtpTransportInternal* rtp_transport =
5550 transport_controller_->GetRtpTransport(mid);
5551 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005552 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005553 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5554 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005555 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005556 return false;
5557 }
Steve Anton75737c02017-11-06 10:37:17 -08005558 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5559 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5560 rtp_data_channel_->SignalSentPacket.connect(
5561 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005562 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005563 if (uma_observer_) {
5564 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5565 }
Steve Anton75737c02017-11-06 10:37:17 -08005566 }
5567
Steve Anton75737c02017-11-06 10:37:17 -08005568 return true;
5569}
5570
5571Call::Stats PeerConnection::GetCallStats() {
5572 if (!worker_thread()->IsCurrent()) {
5573 return worker_thread()->Invoke<Call::Stats>(
5574 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5575 }
5576 if (call_) {
5577 return call_->GetStats();
5578 } else {
5579 return Call::Stats();
5580 }
5581}
5582
Zhi Huange830e682018-03-30 10:48:35 -07005583bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005584 RTC_DCHECK(network_thread()->IsCurrent());
5585 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005586 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005587 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005588 RTC_DCHECK(dtls_transport);
5589 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005590 RTC_DCHECK(sctp_transport_);
5591 sctp_invoker_.reset(new rtc::AsyncInvoker());
5592 sctp_transport_->SignalReadyToSendData.connect(
5593 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5594 sctp_transport_->SignalDataReceived.connect(
5595 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005596 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5597 // another thread. Would be nice if there was a helper class similar to
5598 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5599 // code.
5600 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5601 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5602 sctp_transport_->SignalClosingProcedureComplete.connect(
5603 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005604 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005605 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005606 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005607}
5608
5609void PeerConnection::DestroySctpTransport_n() {
5610 RTC_DCHECK(network_thread()->IsCurrent());
5611 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005612 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005613 sctp_invoker_.reset(nullptr);
5614 sctp_ready_to_send_data_ = false;
5615}
5616
5617void PeerConnection::OnSctpTransportReadyToSendData_n() {
5618 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5619 RTC_DCHECK(network_thread()->IsCurrent());
5620 // Note: Cannot use rtc::Bind here because it will grab a reference to
5621 // PeerConnection and potentially cause PeerConnection to live longer than
5622 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5623 // be destroyed before PeerConnection is destroyed, and at that point all
5624 // pending tasks will be cleared.
5625 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5626 OnSctpTransportReadyToSendData_s(true);
5627 });
5628}
5629
5630void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5631 RTC_DCHECK(signaling_thread()->IsCurrent());
5632 sctp_ready_to_send_data_ = ready;
5633 SignalSctpReadyToSendData(ready);
5634}
5635
5636void PeerConnection::OnSctpTransportDataReceived_n(
5637 const cricket::ReceiveDataParams& params,
5638 const rtc::CopyOnWriteBuffer& payload) {
5639 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5640 RTC_DCHECK(network_thread()->IsCurrent());
5641 // Note: Cannot use rtc::Bind here because it will grab a reference to
5642 // PeerConnection and potentially cause PeerConnection to live longer than
5643 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5644 // be destroyed before PeerConnection is destroyed, and at that point all
5645 // pending tasks will be cleared.
5646 sctp_invoker_->AsyncInvoke<void>(
5647 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5648 OnSctpTransportDataReceived_s(params, payload);
5649 });
5650}
5651
5652void PeerConnection::OnSctpTransportDataReceived_s(
5653 const cricket::ReceiveDataParams& params,
5654 const rtc::CopyOnWriteBuffer& payload) {
5655 RTC_DCHECK(signaling_thread()->IsCurrent());
5656 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5657 // Received OPEN message; parse and signal that a new data channel should
5658 // be created.
5659 std::string label;
5660 InternalDataChannelInit config;
5661 config.id = params.ssrc;
5662 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005663 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5664 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005665 return;
5666 }
5667 config.open_handshake_role = InternalDataChannelInit::kAcker;
5668 OnDataChannelOpenMessage(label, config);
5669 } else {
5670 // Otherwise just forward the signal.
5671 SignalSctpDataReceived(params, payload);
5672 }
5673}
5674
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005675void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005676 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5677 RTC_DCHECK(network_thread()->IsCurrent());
5678 sctp_invoker_->AsyncInvoke<void>(
5679 RTC_FROM_HERE, signaling_thread(),
5680 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005681 &SignalSctpClosingProcedureStartedRemotely, sid));
5682}
5683
5684void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5685 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5686 RTC_DCHECK(network_thread()->IsCurrent());
5687 sctp_invoker_->AsyncInvoke<void>(
5688 RTC_FROM_HERE, signaling_thread(),
5689 rtc::Bind(&sigslot::signal1<int>::operator(),
5690 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005691}
5692
5693// Returns false if bundle is enabled and rtcp_mux is disabled.
5694bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5695 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5696 if (!bundle_enabled)
5697 return true;
5698
5699 const cricket::ContentGroup* bundle_group =
5700 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5701 RTC_DCHECK(bundle_group != NULL);
5702
5703 const cricket::ContentInfos& contents = desc->contents();
5704 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5705 citer != contents.end(); ++citer) {
5706 const cricket::ContentInfo* content = (&*citer);
5707 RTC_DCHECK(content != NULL);
5708 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005709 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005710 if (!HasRtcpMuxEnabled(content))
5711 return false;
5712 }
5713 }
5714 // RTCP-MUX is enabled in all the contents.
5715 return true;
5716}
5717
5718bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005719 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005720}
5721
Steve Anton8a006912017-12-04 15:25:56 -08005722RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005723 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005724 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005725 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005726 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005727 }
5728
5729 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005730 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005731 }
5732
Steve Anton3828c062017-12-06 10:34:51 -08005733 SdpType type = sdesc->GetType();
5734 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5735 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005736 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005737 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005738 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005739 }
5740
5741 // Verify crypto settings.
5742 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005743 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5744 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005745 RTCError crypto_error =
5746 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005747 if (!crypto_error.ok()) {
5748 return crypto_error;
5749 }
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
5751
5752 // Verify ice-ufrag and ice-pwd.
5753 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005754 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5755 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
5757
5758 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005759 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5760 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005761 }
5762
5763 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5764 // m-lines that do not rtcp-mux enabled.
5765
5766 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005767 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005768 // With an answer we want to compare the new answer session description with
5769 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005770 const cricket::SessionDescription* offer_desc =
5771 (source == cricket::CS_LOCAL) ? remote_description()->description()
5772 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005773 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5774 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5775 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005776 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5777 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005778 }
5779 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005780 // The re-offers should respect the order of m= sections in current
5781 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005782 // With a re-offer, either the current local or current remote descriptions
5783 // could be the most up to date, so we would like to check against both of
5784 // them if they exist. It could be the case that one of them has a 0 port
5785 // for a media section, but the other does not. This is important to check
5786 // against in the case that we are recycling an m= section.
5787 const cricket::SessionDescription* current_desc = nullptr;
5788 const cricket::SessionDescription* secondary_current_desc = nullptr;
5789 if (local_description()) {
5790 current_desc = local_description()->description();
5791 if (remote_description()) {
5792 secondary_current_desc = remote_description()->description();
5793 }
5794 } else if (remote_description()) {
5795 current_desc = remote_description()->description();
5796 }
Steve Anton75737c02017-11-06 10:37:17 -08005797 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005798 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5799 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005800 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5801 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
5803 }
5804
Steve Antonba42e992018-04-09 14:10:01 -07005805 if (IsUnifiedPlan()) {
5806 // Ensure that each audio and video media section has at most one
5807 // "StreamParams". This will return an error if receiving a session
5808 // description from a "Plan B" endpoint which adds multiple tracks of the
5809 // same type. With Unified Plan, there can only be at most one track per
5810 // media section.
5811 for (const ContentInfo& content : sdesc->description()->contents()) {
5812 const MediaContentDescription& desc = *content.description;
5813 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5814 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5815 desc.streams().size() > 1u) {
5816 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5817 "Media section has more than one track specified "
5818 "with a=ssrc lines which is not supported with "
5819 "Unified Plan.");
5820 }
5821 }
5822 }
5823
Steve Anton8a006912017-12-04 15:25:56 -08005824 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005825}
5826
Steve Anton3828c062017-12-06 10:34:51 -08005827bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005828 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005829 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005830 return (state == PeerConnectionInterface::kStable) ||
5831 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005832 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005833 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005834 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5835 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5836 }
5837}
5838
Steve Anton3828c062017-12-06 10:34:51 -08005839bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005840 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005841 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005842 return (state == PeerConnectionInterface::kStable) ||
5843 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005844 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005845 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005846 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5847 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5848 }
5849}
5850
Steve Antonf8470812017-12-04 10:46:21 -08005851const char* PeerConnection::SessionErrorToString(SessionError error) const {
5852 switch (error) {
5853 case SessionError::kNone:
5854 return "ERROR_NONE";
5855 case SessionError::kContent:
5856 return "ERROR_CONTENT";
5857 case SessionError::kTransport:
5858 return "ERROR_TRANSPORT";
5859 }
5860 RTC_NOTREACHED();
5861 return "";
5862}
5863
Steve Anton75737c02017-11-06 10:37:17 -08005864std::string PeerConnection::GetSessionErrorMsg() {
5865 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005866 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5867 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005868 return desc.str();
5869}
5870
Steve Anton8e20f172018-03-06 10:55:04 -08005871void PeerConnection::ReportSdpFormatReceived(
5872 const SessionDescriptionInterface& remote_offer) {
5873 if (!uma_observer_) {
5874 return;
5875 }
5876 int num_audio_mlines = 0;
5877 int num_video_mlines = 0;
5878 int num_audio_tracks = 0;
5879 int num_video_tracks = 0;
5880 for (const ContentInfo& content : remote_offer.description()->contents()) {
5881 cricket::MediaType media_type = content.media_description()->type();
5882 int num_tracks = std::max(
5883 1, static_cast<int>(content.media_description()->streams().size()));
5884 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5885 num_audio_mlines += 1;
5886 num_audio_tracks += num_tracks;
5887 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5888 num_video_mlines += 1;
5889 num_video_tracks += num_tracks;
5890 }
5891 }
5892 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5893 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5894 format = kSdpFormatReceivedComplexUnifiedPlan;
5895 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5896 format = kSdpFormatReceivedComplexPlanB;
5897 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5898 format = kSdpFormatReceivedSimple;
5899 }
5900 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5901 kSdpFormatReceivedMax);
5902}
5903
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005904void PeerConnection::NoteUsageEvent(UsageEvent event) {
5905 RTC_DCHECK_RUN_ON(signaling_thread());
5906 usage_event_accumulator_ |= static_cast<int>(event);
5907}
5908
5909void PeerConnection::ReportUsagePattern() const {
5910 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5911 if (uma_observer_) {
5912 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5913 usage_event_accumulator_);
5914 }
5915}
5916
Steve Anton0ffaaa22018-02-23 10:31:30 -08005917void PeerConnection::ReportNegotiatedSdpSemantics(
5918 const SessionDescriptionInterface& answer) {
5919 if (!uma_observer_) {
5920 return;
5921 }
5922 switch (answer.description()->msid_signaling()) {
5923 case 0:
5924 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5925 kSdpSemanticNegotiatedNone,
5926 kSdpSemanticNegotiatedMax);
5927 break;
5928 case cricket::kMsidSignalingMediaSection:
5929 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5930 kSdpSemanticNegotiatedUnifiedPlan,
5931 kSdpSemanticNegotiatedMax);
5932 break;
5933 case cricket::kMsidSignalingSsrcAttribute:
5934 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5935 kSdpSemanticNegotiatedPlanB,
5936 kSdpSemanticNegotiatedMax);
5937 break;
5938 case cricket::kMsidSignalingMediaSection |
5939 cricket::kMsidSignalingSsrcAttribute:
5940 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5941 kSdpSemanticNegotiatedMixed,
5942 kSdpSemanticNegotiatedMax);
5943 break;
5944 default:
5945 RTC_NOTREACHED();
5946 }
5947}
5948
Steve Anton75737c02017-11-06 10:37:17 -08005949// We need to check the local/remote description for the Transport instead of
5950// the session, because a new Transport added during renegotiation may have
5951// them unset while the session has them set from the previous negotiation.
5952// Not doing so may trigger the auto generation of transport description and
5953// mess up DTLS identity information, ICE credential, etc.
5954bool PeerConnection::ReadyToUseRemoteCandidate(
5955 const IceCandidateInterface* candidate,
5956 const SessionDescriptionInterface* remote_desc,
5957 bool* valid) {
5958 *valid = true;
5959
5960 const SessionDescriptionInterface* current_remote_desc =
5961 remote_desc ? remote_desc : remote_description();
5962
5963 if (!current_remote_desc) {
5964 return false;
5965 }
5966
5967 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5968 size_t remote_content_size =
5969 current_remote_desc->description()->contents().size();
5970 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005971 RTC_LOG(LS_ERROR)
5972 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5973 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005974
5975 *valid = false;
5976 return false;
5977 }
5978
5979 cricket::ContentInfo content =
5980 current_remote_desc->description()->contents()[mediacontent_index];
5981
5982 const std::string transport_name = GetTransportName(content.name);
5983 if (transport_name.empty()) {
5984 return false;
5985 }
Zhi Huange830e682018-03-30 10:48:35 -07005986 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005987}
5988
5989bool PeerConnection::SrtpRequired() const {
5990 return dtls_enabled_ ||
5991 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5992}
5993
5994void PeerConnection::OnTransportControllerGatheringState(
5995 cricket::IceGatheringState state) {
5996 RTC_DCHECK(signaling_thread()->IsCurrent());
5997 if (state == cricket::kIceGatheringGathering) {
5998 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5999 } else if (state == cricket::kIceGatheringComplete) {
6000 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6001 }
6002}
6003
6004void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006005 std::map<std::string, std::set<cricket::MediaType>>
6006 media_types_by_transport_name;
6007 for (auto transceiver : transceivers_) {
6008 if (transceiver->internal()->channel()) {
6009 const std::string& transport_name =
6010 transceiver->internal()->channel()->transport_name();
6011 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006012 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006013 }
Steve Anton75737c02017-11-06 10:37:17 -08006014 }
6015 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006016 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6017 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006018 }
Zhi Huange830e682018-03-30 10:48:35 -07006019
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006020 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006021 if (transport_name) {
6022 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006023 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006024 }
Zhi Huange830e682018-03-30 10:48:35 -07006025
Steve Antonc7b964c2018-02-01 14:39:45 -08006026 for (const auto& entry : media_types_by_transport_name) {
6027 const std::string& transport_name = entry.first;
6028 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006029 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006030 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006031 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006032 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006033 }
6034 }
6035}
6036// Walk through the ConnectionInfos to gather best connection usage
6037// for IPv4 and IPv6.
6038void PeerConnection::ReportBestConnectionState(
6039 const cricket::TransportStats& stats) {
6040 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006041 for (const cricket::TransportChannelStats& channel_stats :
6042 stats.channel_stats) {
6043 for (const cricket::ConnectionInfo& connection_info :
6044 channel_stats.connection_infos) {
6045 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006046 continue;
6047 }
6048
6049 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006050 const cricket::Candidate& local = connection_info.local_candidate;
6051 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006052
6053 // Increment the counter for IceCandidatePairType.
6054 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6055 (local.type() == RELAY_PORT_TYPE &&
6056 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6057 type = kEnumCounterIceCandidatePairTypeTcp;
6058 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6059 type = kEnumCounterIceCandidatePairTypeUdp;
6060 } else {
6061 RTC_CHECK(0);
6062 }
6063 metrics_observer()->IncrementEnumCounter(
6064 type, GetIceCandidatePairCounter(local, remote),
6065 kIceCandidatePairMax);
6066
6067 // Increment the counter for IP type.
6068 if (local.address().family() == AF_INET) {
6069 metrics_observer()->IncrementEnumCounter(
6070 kEnumCounterAddressFamily, kBestConnections_IPv4,
6071 kPeerConnectionAddressFamilyCounter_Max);
6072
6073 } else if (local.address().family() == AF_INET6) {
6074 metrics_observer()->IncrementEnumCounter(
6075 kEnumCounterAddressFamily, kBestConnections_IPv6,
6076 kPeerConnectionAddressFamilyCounter_Max);
6077 } else {
6078 RTC_CHECK(0);
6079 }
6080
6081 return;
6082 }
6083 }
6084}
6085
6086void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006087 const cricket::TransportStats& stats,
6088 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006089 RTC_DCHECK(metrics_observer());
6090 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6091 return;
6092 }
6093
6094 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6095 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6096 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6097 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6098 return;
6099 }
6100
Steve Antonc7b964c2018-02-01 14:39:45 -08006101 for (cricket::MediaType media_type : media_types) {
6102 PeerConnectionEnumCounterType srtp_counter_type;
6103 PeerConnectionEnumCounterType ssl_counter_type;
6104 switch (media_type) {
6105 case cricket::MEDIA_TYPE_AUDIO:
6106 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6107 ssl_counter_type = kEnumCounterAudioSslCipher;
6108 break;
6109 case cricket::MEDIA_TYPE_VIDEO:
6110 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6111 ssl_counter_type = kEnumCounterVideoSslCipher;
6112 break;
6113 case cricket::MEDIA_TYPE_DATA:
6114 srtp_counter_type = kEnumCounterDataSrtpCipher;
6115 ssl_counter_type = kEnumCounterDataSslCipher;
6116 break;
6117 default:
6118 RTC_NOTREACHED();
6119 continue;
6120 }
6121 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6122 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6123 srtp_crypto_suite);
6124 }
6125 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6126 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6127 ssl_cipher_suite);
6128 }
Steve Anton75737c02017-11-06 10:37:17 -08006129 }
6130}
6131
6132void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6133 RTC_DCHECK(worker_thread()->IsCurrent());
6134 RTC_DCHECK(call_);
6135 call_->OnSentPacket(sent_packet);
6136}
6137
6138const std::string PeerConnection::GetTransportName(
6139 const std::string& content_name) {
6140 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006141 if (channel) {
6142 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006143 }
Steve Anton6fec8802017-12-04 10:37:29 -08006144 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006145 RTC_DCHECK(sctp_mid_);
6146 if (content_name == *sctp_mid_) {
6147 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006148 }
6149 }
6150 // Return an empty string if failed to retrieve the transport name.
6151 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006152}
6153
Steve Anton6fec8802017-12-04 10:37:29 -08006154void PeerConnection::DestroyTransceiverChannel(
6155 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6156 transceiver) {
6157 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006158
Steve Anton6fec8802017-12-04 10:37:29 -08006159 cricket::BaseChannel* channel = transceiver->internal()->channel();
6160 if (channel) {
6161 transceiver->internal()->SetChannel(nullptr);
6162 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006163 }
6164}
6165
6166void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006167 if (rtp_data_channel_) {
6168 OnDataChannelDestroyed();
6169 DestroyBaseChannel(rtp_data_channel_);
6170 rtp_data_channel_ = nullptr;
6171 }
6172
6173 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6174 // grab a reference to this PeerConnection. If this is called from the
6175 // PeerConnection destructor, the RefCountedObject vtable will have already
6176 // been destroyed (since it is a subclass of PeerConnection) and using
6177 // rtc::Bind will cause "Pure virtual function called" error to appear.
6178
6179 if (sctp_transport_) {
6180 OnDataChannelDestroyed();
6181 network_thread()->Invoke<void>(RTC_FROM_HERE,
6182 [this] { DestroySctpTransport_n(); });
6183 }
6184}
6185
6186void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6187 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006188 switch (channel->media_type()) {
6189 case cricket::MEDIA_TYPE_AUDIO:
6190 channel_manager()->DestroyVoiceChannel(
6191 static_cast<cricket::VoiceChannel*>(channel));
6192 break;
6193 case cricket::MEDIA_TYPE_VIDEO:
6194 channel_manager()->DestroyVideoChannel(
6195 static_cast<cricket::VideoChannel*>(channel));
6196 break;
6197 case cricket::MEDIA_TYPE_DATA:
6198 channel_manager()->DestroyRtpDataChannel(
6199 static_cast<cricket::RtpDataChannel*>(channel));
6200 break;
6201 default:
6202 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6203 break;
6204 }
Zhi Huange830e682018-03-30 10:48:35 -07006205}
Steve Anton6fec8802017-12-04 10:37:29 -08006206
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006207bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006208 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006209 RtpTransportInternal* rtp_transport,
6210 cricket::DtlsTransportInternal* dtls_transport) {
6211 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006212 auto base_channel = GetChannel(mid);
6213 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006214 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006215 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006216 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006217 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006218 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006219 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006220}
6221
Harald Alvestrand89061872018-01-02 14:08:34 +01006222void PeerConnection::ClearStatsCache() {
6223 if (stats_collector_) {
6224 stats_collector_->ClearCachedStatsReport();
6225 }
6226}
6227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006228} // namespace webrtc