blob: cf56c350f6a862302b233677aa6eb16261421705 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/jsepicecandidate.h"
21#include "api/jsepsessiondescription.h"
22#include "api/mediaconstraintsinterface.h"
23#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
25#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080026#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020027#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080031#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080037#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080040#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080041#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010048#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020049#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
Steve Anton75737c02017-11-06 10:37:17 -080056using cricket::ContentInfo;
57using cricket::ContentInfos;
58using cricket::MediaContentDescription;
59using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080060using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::TransportInfo;
62
63using cricket::LOCAL_PORT_TYPE;
64using cricket::STUN_PORT_TYPE;
65using cricket::RELAY_PORT_TYPE;
66using cricket::PRFLX_PORT_TYPE;
67
Steve Antonba818672017-11-06 10:21:57 -080068namespace webrtc {
69
Steve Anton75737c02017-11-06 10:37:17 -080070// Error messages
71const char kBundleWithoutRtcpMux[] =
72 "rtcp-mux must be enabled when BUNDLE "
73 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080074const char kInvalidCandidates[] = "Description contains invalid candidates.";
75const char kInvalidSdp[] = "Invalid session description.";
76const char kMlineMismatchInAnswer[] =
77 "The order of m-lines in answer doesn't match order in offer. Rejecting "
78 "answer.";
79const char kMlineMismatchInSubsequentOffer[] =
80 "The order of m-lines in subsequent offer doesn't match order from "
81 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080082const char kSdpWithoutDtlsFingerprint[] =
83 "Called with SDP without DTLS fingerprint.";
84const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
85const char kSdpWithoutIceUfragPwd[] =
86 "Called with SDP without ice-ufrag and ice-pwd.";
87const char kSessionError[] = "Session error code: ";
88const char kSessionErrorDesc[] = "Session error description: ";
89const char kDtlsSrtpSetupFailureRtp[] =
90 "Couldn't set up DTLS-SRTP on RTP channel.";
91const char kDtlsSrtpSetupFailureRtcp[] =
92 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100127 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700145 if (current_streams->find(new_stream->id()) != nullptr) {
146 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100385void NoteKeyProtocolAndMedia(
386 KeyExchangeProtocolType protocol_type,
387 cricket::MediaType media_type,
388 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
389 if (!uma_observer)
390 return;
391 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
392 protocol_type,
393 webrtc::kEnumCounterKeyProtocolMax);
394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
412 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
413 it->second,
414 kEnumCounterKeyProtocolMediaTypeMax);
415 }
416}
417
Steve Anton75737c02017-11-06 10:37:17 -0800418// Checks that each non-rejected content has SDES crypto keys or a DTLS
419// fingerprint, unless it's in a BUNDLE group, in which case only the
420// BUNDLE-tag section (first media section/description in the BUNDLE group)
421// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
422// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
423// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100424RTCError VerifyCrypto(const SessionDescription* desc,
425 bool dtls_enabled,
426 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800431 continue;
432 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Seth Hampson5b4f0752018-04-02 16:31:36 -0700603std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
604 std::string output = "streams=[";
605 const char* separator = "";
606 for (const auto& stream_id : stream_ids) {
607 output.append(separator).append(stream_id);
608 separator = ", ";
609 }
610 output.append("]");
611 return output;
612}
613
Qingsi Wang866e08d2018-03-22 17:54:23 -0700614rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
618 return rtc::nullopt;
619 }
620 return rtc_configuration_parameter;
621}
622
Steve Anton75737c02017-11-06 10:37:17 -0800623} // namespace
624
Henrik Boström31638672017-11-23 17:48:32 +0100625// Upon completion, posts a task to execute the callback of the
626// SetSessionDescriptionObserver asynchronously on the same thread. At this
627// point, the state of the peer connection might no longer reflect the effects
628// of the SetRemoteDescription operation, as the peer connection could have been
629// modified during the post.
630// TODO(hbos): Remove this class once we remove the version of
631// PeerConnectionInterface::SetRemoteDescription() that takes a
632// SetSessionDescriptionObserver as an argument.
633class PeerConnection::SetRemoteDescriptionObserverAdapter
634 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
635 public:
636 SetRemoteDescriptionObserverAdapter(
637 rtc::scoped_refptr<PeerConnection> pc,
638 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
639 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
640
641 // SetRemoteDescriptionObserverInterface implementation.
642 void OnSetRemoteDescriptionComplete(RTCError error) override {
643 if (error.ok())
644 pc_->PostSetSessionDescriptionSuccess(wrapper_);
645 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100646 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100647 }
648
649 private:
650 rtc::scoped_refptr<PeerConnection> pc_;
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
652};
653
deadbeef293e9262017-01-11 12:28:30 -0800654bool PeerConnectionInterface::RTCConfiguration::operator==(
655 const PeerConnectionInterface::RTCConfiguration& o) const {
656 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700657 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800658 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000659 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700660 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800661 BundlePolicy bundle_policy;
662 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700663 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
664 int ice_candidate_pool_size;
665 bool disable_ipv6;
666 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700667 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100668 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700669 bool enable_rtp_data_channel;
670 rtc::Optional<int> screencast_min_bitrate;
671 rtc::Optional<bool> combined_audio_video_bwe;
672 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800673 TcpCandidatePolicy tcp_candidate_policy;
674 CandidateNetworkPolicy candidate_network_policy;
675 int audio_jitter_buffer_max_packets;
676 bool audio_jitter_buffer_fast_accelerate;
677 int ice_connection_receiving_timeout;
678 int ice_backup_candidate_pair_ping_interval;
679 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800680 bool prioritize_most_likely_ice_candidate_pairs;
681 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800682 bool prune_turn_ports;
683 bool presume_writable_when_fully_relayed;
684 bool enable_ice_renomination;
685 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800686 rtc::Optional<int> ice_check_interval_strong_connectivity;
687 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800688 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700689 rtc::Optional<int> ice_unwritable_timeout;
690 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800691 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700692 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200693 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800694 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800695 rtc::Optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700696 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800697 };
698 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
699 "Did you add something to RTCConfiguration and forget to "
700 "update operator==?");
701 return type == o.type && servers == o.servers &&
702 bundle_policy == o.bundle_policy &&
703 rtcp_mux_policy == o.rtcp_mux_policy &&
704 tcp_candidate_policy == o.tcp_candidate_policy &&
705 candidate_network_policy == o.candidate_network_policy &&
706 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
707 audio_jitter_buffer_fast_accelerate ==
708 o.audio_jitter_buffer_fast_accelerate &&
709 ice_connection_receiving_timeout ==
710 o.ice_connection_receiving_timeout &&
711 ice_backup_candidate_pair_ping_interval ==
712 o.ice_backup_candidate_pair_ping_interval &&
713 continual_gathering_policy == o.continual_gathering_policy &&
714 certificates == o.certificates &&
715 prioritize_most_likely_ice_candidate_pairs ==
716 o.prioritize_most_likely_ice_candidate_pairs &&
717 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800718 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700719 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100720 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800721 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800722 screencast_min_bitrate == o.screencast_min_bitrate &&
723 combined_audio_video_bwe == o.combined_audio_video_bwe &&
724 enable_dtls_srtp == o.enable_dtls_srtp &&
725 ice_candidate_pool_size == o.ice_candidate_pool_size &&
726 prune_turn_ports == o.prune_turn_ports &&
727 presume_writable_when_fully_relayed ==
728 o.presume_writable_when_fully_relayed &&
729 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800730 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800731 ice_check_interval_strong_connectivity ==
732 o.ice_check_interval_strong_connectivity &&
733 ice_check_interval_weak_connectivity ==
734 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700735 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700736 ice_unwritable_timeout == o.ice_unwritable_timeout &&
737 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800738 stun_candidate_keepalive_interval ==
739 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200740 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800741 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800742 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700743 network_preference == o.network_preference &&
744 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800745}
746
747bool PeerConnectionInterface::RTCConfiguration::operator!=(
748 const PeerConnectionInterface::RTCConfiguration& o) const {
749 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800750}
751
zhihuang8f65cdf2016-05-06 18:40:30 -0700752// Generate a RTCP CNAME when a PeerConnection is created.
753std::string GenerateRtcpCname() {
754 std::string cname;
755 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100756 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800757 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700758 }
759 return cname;
760}
761
zhihuang1c378ed2017-08-17 14:10:50 -0700762bool ValidateOfferAnswerOptions(
763 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
764 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
765 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700766}
767
zhihuang1c378ed2017-08-17 14:10:50 -0700768// From |rtc_options|, fill parts of |session_options| shared by all generated
769// m= sections (in other words, nothing that involves a map/array).
770void ExtractSharedMediaSessionOptions(
771 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
772 cricket::MediaSessionOptions* session_options) {
773 session_options->vad_enabled = rtc_options.voice_activity_detection;
774 session_options->bundle_enabled = rtc_options.use_rtp_mux;
775}
zhihuanga77e6bb2017-08-14 18:17:48 -0700776
zhihuang1c378ed2017-08-17 14:10:50 -0700777bool ConvertConstraintsToOfferAnswerOptions(
778 const MediaConstraintsInterface* constraints,
779 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700780 if (!constraints) {
781 return true;
782 }
zhihuang1c378ed2017-08-17 14:10:50 -0700783
784 bool value = false;
785 size_t mandatory_constraints_satisfied = 0;
786
787 if (FindConstraint(constraints,
788 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
789 &mandatory_constraints_satisfied)) {
790 offer_answer_options->offer_to_receive_audio =
791 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
792 kOfferToReceiveMediaTrue
793 : 0;
794 }
795
796 if (FindConstraint(constraints,
797 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
798 &mandatory_constraints_satisfied)) {
799 offer_answer_options->offer_to_receive_video =
800 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
801 kOfferToReceiveMediaTrue
802 : 0;
803 }
804 if (FindConstraint(constraints,
805 MediaConstraintsInterface::kVoiceActivityDetection, &value,
806 &mandatory_constraints_satisfied)) {
807 offer_answer_options->voice_activity_detection = value;
808 }
809 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
810 &mandatory_constraints_satisfied)) {
811 offer_answer_options->use_rtp_mux = value;
812 }
813 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
814 &value, &mandatory_constraints_satisfied)) {
815 offer_answer_options->ice_restart = value;
816 }
817
deadbeefab9b2d12015-10-14 11:33:11 -0700818 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
819}
820
zhihuang38ede132017-06-15 12:52:32 -0700821PeerConnection::PeerConnection(PeerConnectionFactory* factory,
822 std::unique_ptr<RtcEventLog> event_log,
823 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000824 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700825 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700826 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700827 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700828 remote_streams_(StreamCollection::Create()),
829 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000830
831PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100832 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800833 RTC_DCHECK_RUN_ON(signaling_thread());
834
Steve Anton8af21862017-12-15 11:20:13 -0800835 // Need to stop transceivers before destroying the stats collector because
836 // AudioRtpSender has a reference to the StatsCollector it will update when
837 // stopping.
838 for (auto transceiver : transceivers_) {
839 transceiver->Stop();
840 }
Steve Anton4171afb2017-11-20 10:20:22 -0800841
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700842 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800843 if (stats_collector_) {
844 stats_collector_->WaitForPendingRequest();
845 stats_collector_ = nullptr;
846 }
Steve Anton75737c02017-11-06 10:37:17 -0800847
Steve Anton8af21862017-12-15 11:20:13 -0800848 // Don't destroy BaseChannels until after stats has been cleaned up so that
849 // the last stats request can still read from the channels.
850 DestroyAllChannels();
851
Mirko Bonadei675513b2017-11-09 11:09:25 +0100852 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800853
854 webrtc_session_desc_factory_.reset();
855 sctp_invoker_.reset();
856 sctp_factory_.reset();
857 transport_controller_.reset();
858
deadbeef91dd5672016-05-18 16:55:30 -0700859 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700860 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700861 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700862 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700863 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700864 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800865 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700866 event_log_.reset();
867 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868}
869
Steve Anton8af21862017-12-15 11:20:13 -0800870void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800871 // Destroy video channels first since they may have a pointer to a voice
872 // channel.
873 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800874 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800875 DestroyTransceiverChannel(transceiver);
876 }
877 }
878 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800879 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800880 DestroyTransceiverChannel(transceiver);
881 }
882 }
883 DestroyDataChannel();
884}
885
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000887 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700888 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100889 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700890
891 RTCError config_error = ValidateConfiguration(configuration);
892 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100893 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700894 return false;
895 }
896
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LS_ERROR)
899 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100900 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800901 return false;
902 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200903
Benjamin Wrightcab58882018-05-02 15:12:47 -0700904 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800905 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100906 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100907 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800908 return false;
909 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700910
Benjamin Wrightcab58882018-05-02 15:12:47 -0700911 observer_ = dependencies.observer;
912 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700913 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800914
deadbeef91dd5672016-05-18 16:55:30 -0700915 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700916 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700917 if (!network_thread()->Invoke<bool>(
918 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
919 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920 return false;
921 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922
Zhi Huange830e682018-03-30 10:48:35 -0700923 const PeerConnectionFactoryInterface::Options& options = factory_->options();
924
Steve Anton75737c02017-11-06 10:37:17 -0800925 // RFC 3264: The numeric value of the session id and version in the
926 // o line MUST be representable with a "64 bit signed integer".
927 // Due to this constraint session id |session_id_| is max limited to
928 // LLONG_MAX.
929 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700930 JsepTransportController::Config config;
931 config.redetermine_role_on_ice_restart =
932 configuration.redetermine_role_on_ice_restart;
933 config.ssl_max_version = factory_->options().ssl_max_version;
934 config.disable_encryption = options.disable_encryption;
935 config.bundle_policy = configuration.bundle_policy;
936 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
937 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700938 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700939 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700940#if defined(ENABLE_EXTERNAL_AUTH)
941 config.enable_external_auth = true;
942#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700943 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700944 transport_controller_.reset(new JsepTransportController(
945 signaling_thread(), network_thread(), port_allocator_.get(), config));
946 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800947 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700948 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800949 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700950 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800951 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700952 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800953 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
954 transport_controller_->SignalDtlsHandshakeError.connect(
955 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
956
957 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700958
deadbeefab9b2d12015-10-14 11:33:11 -0700959 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700960 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000961
Steve Antonba818672017-11-06 10:21:57 -0800962 configuration_ = configuration;
963
Steve Anton75737c02017-11-06 10:37:17 -0800964 // Obtain a certificate from RTCConfiguration if any were provided (optional).
965 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
966 if (!configuration.certificates.empty()) {
967 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
968 // just picking the first one. The decision should be made based on the DTLS
969 // handshake. The DTLS negotiations need to know about all certificates.
970 certificate = configuration.certificates[0];
971 }
972
Steve Antond25da372017-11-06 14:50:29 -0800973 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800974
975 if (options.disable_encryption) {
976 dtls_enabled_ = false;
977 } else {
978 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700979 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800980 // |configuration| can override the default |dtls_enabled_| value.
981 if (configuration.enable_dtls_srtp) {
982 dtls_enabled_ = *(configuration.enable_dtls_srtp);
983 }
984 }
985
986 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
987 // It takes precendence over the disable_sctp_data_channels
988 // PeerConnectionFactoryInterface::Options.
989 if (configuration.enable_rtp_data_channel) {
990 data_channel_type_ = cricket::DCT_RTP;
991 } else {
992 // DTLS has to be enabled to use SCTP.
993 if (!options.disable_sctp_data_channels && dtls_enabled_) {
994 data_channel_type_ = cricket::DCT_SCTP;
995 }
996 }
997
998 video_options_.screencast_min_bitrate_kbps =
999 configuration.screencast_min_bitrate;
1000 audio_options_.combined_audio_video_bwe =
1001 configuration.combined_audio_video_bwe;
1002
1003 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001004 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001005
1006 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001007 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001008
1009 // Whether the certificate generator/certificate is null or not determines
1010 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1011 // the right instructions by clearing the variables if needed.
1012 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001013 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001014 certificate = nullptr;
1015 } else if (certificate) {
1016 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001017 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001018 }
1019
1020 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1021 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001022 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001023 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1024 this, &PeerConnection::OnCertificateReady);
1025
1026 if (options.disable_encryption) {
1027 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1028 }
1029
1030 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1031 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032
Steve Anton4171afb2017-11-20 10:20:22 -08001033 // Add default audio/video transceivers for Plan B SDP.
1034 if (!IsUnifiedPlan()) {
1035 transceivers_.push_back(
1036 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1037 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1038 transceivers_.push_back(
1039 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1040 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1041 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042 return true;
1043}
1044
Steve Anton038834f2017-07-14 15:59:59 -07001045RTCError PeerConnection::ValidateConfiguration(
1046 const RTCConfiguration& config) const {
1047 if (config.ice_regather_interval_range &&
1048 config.continual_gathering_policy == GATHER_ONCE) {
1049 return RTCError(RTCErrorType::INVALID_PARAMETER,
1050 "ice_regather_interval_range specified but continual "
1051 "gathering policy is GATHER_ONCE");
1052 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001053 auto result =
1054 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1055 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001056}
1057
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001058rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001059PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001060 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1061 "Plan SdpSemantics. Please use GetSenders "
1062 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001063 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064}
1065
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001066rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001067PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001068 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1069 "Plan SdpSemantics. Please use GetReceivers "
1070 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001071 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072}
1073
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001074bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001075 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1076 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001077 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 if (IsClosed()) {
1079 return false;
1080 }
deadbeefab9b2d12015-10-14 11:33:11 -07001081 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082 return false;
1083 }
deadbeefab9b2d12015-10-14 11:33:11 -07001084
1085 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001086 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1087 observer->SignalAudioTrackAdded.connect(this,
1088 &PeerConnection::OnAudioTrackAdded);
1089 observer->SignalAudioTrackRemoved.connect(
1090 this, &PeerConnection::OnAudioTrackRemoved);
1091 observer->SignalVideoTrackAdded.connect(this,
1092 &PeerConnection::OnVideoTrackAdded);
1093 observer->SignalVideoTrackRemoved.connect(
1094 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001095 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001096
deadbeefab9b2d12015-10-14 11:33:11 -07001097 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001098 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001099 }
1100 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001101 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001102 }
1103
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001104 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105 observer_->OnRenegotiationNeeded();
1106 return true;
1107}
1108
1109void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001110 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1111 "Plan SdpSemantics. Please use RemoveTrack "
1112 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001113 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001114 if (!IsClosed()) {
1115 for (const auto& track : local_stream->GetAudioTracks()) {
1116 RemoveAudioTrack(track.get(), local_stream);
1117 }
1118 for (const auto& track : local_stream->GetVideoTracks()) {
1119 RemoveVideoTrack(track.get(), local_stream);
1120 }
deadbeefab9b2d12015-10-14 11:33:11 -07001121 }
deadbeefab9b2d12015-10-14 11:33:11 -07001122 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001123 stream_observers_.erase(
1124 std::remove_if(
1125 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001126 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001127 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001128 }),
1129 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001130
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001131 if (IsClosed()) {
1132 return;
1133 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001134 observer_->OnRenegotiationNeeded();
1135}
1136
deadbeefe1f9d832016-01-14 15:35:42 -08001137rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1138 MediaStreamTrackInterface* track,
1139 std::vector<MediaStreamInterface*> streams) {
1140 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001141 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001142 for (auto* stream : streams) {
1143 if (!stream) {
1144 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1145 return nullptr;
1146 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001147 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001148 }
Seth Hampson845e8782018-03-02 11:34:10 -08001149 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001150 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001151 return nullptr;
1152 }
Steve Antonf9381f02017-12-14 10:23:57 -08001153 return sender_or_error.MoveValue();
1154}
1155
Steve Anton2d6c76a2018-01-05 17:10:52 -08001156RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001157 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001158 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001159 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001160 if (!track) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1162 }
1163 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1164 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1166 "Track has invalid kind: " + track->kind());
1167 }
Steve Antonf9381f02017-12-14 10:23:57 -08001168 if (IsClosed()) {
1169 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1170 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001171 }
Steve Anton4171afb2017-11-20 10:20:22 -08001172 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001173 LOG_AND_RETURN_ERROR(
1174 RTCErrorType::INVALID_PARAMETER,
1175 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001176 }
Steve Antonf9381f02017-12-14 10:23:57 -08001177 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001178 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1179 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001180 if (sender_or_error.ok()) {
1181 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001182 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001183 }
1184 return sender_or_error;
1185}
deadbeefe1f9d832016-01-14 15:35:42 -08001186
Steve Antonf9381f02017-12-14 10:23:57 -08001187RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1188PeerConnection::AddTrackPlanB(
1189 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001190 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001191 if (stream_ids.size() > 1u) {
1192 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1193 "AddTrack with more than one stream is not "
1194 "supported with Plan B semantics.");
1195 }
1196 std::vector<std::string> adjusted_stream_ids = stream_ids;
1197 if (adjusted_stream_ids.empty()) {
1198 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1199 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001200 cricket::MediaType media_type =
1201 (track->kind() == MediaStreamTrackInterface::kAudioKind
1202 ? cricket::MEDIA_TYPE_AUDIO
1203 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001204 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001205 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001206 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001207 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001208 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001209 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001210 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001211 if (sender_info) {
1212 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001213 }
Steve Antonf9381f02017-12-14 10:23:57 -08001214 } else {
1215 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001216 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001217 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001218 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001219 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001220 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001221 if (sender_info) {
1222 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
deadbeefe1f9d832016-01-14 15:35:42 -08001224 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001225 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001226}
deadbeefe1f9d832016-01-14 15:35:42 -08001227
Steve Antonf9381f02017-12-14 10:23:57 -08001228RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1229PeerConnection::AddTrackUnifiedPlan(
1230 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001231 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001232 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1233 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001234 RTC_LOG(LS_INFO) << "Reusing an existing "
1235 << cricket::MediaTypeToString(transceiver->media_type())
1236 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001237 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001238 transceiver->internal()->set_direction(
1239 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001240 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001241 transceiver->internal()->set_direction(
1242 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001243 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001244 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001245 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001246 } else {
1247 cricket::MediaType media_type =
1248 (track->kind() == MediaStreamTrackInterface::kAudioKind
1249 ? cricket::MEDIA_TYPE_AUDIO
1250 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001251 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1252 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001253 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001254 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1255 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001256 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001257 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001258 }
Steve Antonf9381f02017-12-14 10:23:57 -08001259 return transceiver->sender();
1260}
1261
1262rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1263PeerConnection::FindFirstTransceiverForAddedTrack(
1264 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1265 RTC_DCHECK(track);
1266 for (auto transceiver : transceivers_) {
1267 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001268 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001269 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001270 !transceiver->internal()->has_ever_been_used_to_send() &&
1271 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001272 return transceiver;
1273 }
1274 }
1275 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001276}
1277
1278bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1279 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001280 return RemoveTrackInternal(sender).ok();
1281}
1282
1283RTCError PeerConnection::RemoveTrackInternal(
1284 rtc::scoped_refptr<RtpSenderInterface> sender) {
1285 if (!sender) {
1286 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1287 }
deadbeefe1f9d832016-01-14 15:35:42 -08001288 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001289 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1290 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001291 }
Steve Antonf9381f02017-12-14 10:23:57 -08001292 if (IsUnifiedPlan()) {
1293 auto transceiver = FindTransceiverBySender(sender);
1294 if (!transceiver || !sender->track()) {
1295 return RTCError::OK();
1296 }
1297 sender->SetTrack(nullptr);
1298 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001299 transceiver->internal()->set_direction(
1300 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001301 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001302 transceiver->internal()->set_direction(
1303 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001304 }
Steve Anton4171afb2017-11-20 10:20:22 -08001305 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001306 bool removed;
1307 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1308 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1309 } else {
1310 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1311 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1312 }
1313 if (!removed) {
1314 LOG_AND_RETURN_ERROR(
1315 RTCErrorType::INVALID_PARAMETER,
1316 "Couldn't find sender " + sender->id() + " to remove.");
1317 }
Steve Anton4171afb2017-11-20 10:20:22 -08001318 }
deadbeefe1f9d832016-01-14 15:35:42 -08001319 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001320 return RTCError::OK();
1321}
1322
1323rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1324PeerConnection::FindTransceiverBySender(
1325 rtc::scoped_refptr<RtpSenderInterface> sender) {
1326 for (auto transceiver : transceivers_) {
1327 if (transceiver->sender() == sender) {
1328 return transceiver;
1329 }
1330 }
1331 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001332}
1333
Steve Anton9158ef62017-11-27 13:01:52 -08001334RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1335PeerConnection::AddTransceiver(
1336 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1337 return AddTransceiver(track, RtpTransceiverInit());
1338}
1339
1340RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1341PeerConnection::AddTransceiver(
1342 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1343 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001344 RTC_CHECK(IsUnifiedPlan())
1345 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001346 if (!track) {
1347 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1348 }
1349 cricket::MediaType media_type;
1350 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1351 media_type = cricket::MEDIA_TYPE_AUDIO;
1352 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1353 media_type = cricket::MEDIA_TYPE_VIDEO;
1354 } else {
1355 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1356 "Track kind is not audio or video");
1357 }
1358 return AddTransceiver(media_type, track, init);
1359}
1360
1361RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1362PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1363 return AddTransceiver(media_type, RtpTransceiverInit());
1364}
1365
1366RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1367PeerConnection::AddTransceiver(cricket::MediaType media_type,
1368 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001369 RTC_CHECK(IsUnifiedPlan())
1370 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001371 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1372 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1373 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1374 "media type is not audio or video");
1375 }
1376 return AddTransceiver(media_type, nullptr, init);
1377}
1378
1379RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1380PeerConnection::AddTransceiver(
1381 cricket::MediaType media_type,
1382 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001383 const RtpTransceiverInit& init,
1384 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001385 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1386 media_type == cricket::MEDIA_TYPE_VIDEO));
1387 if (track) {
1388 RTC_DCHECK_EQ(media_type,
1389 (track->kind() == MediaStreamTrackInterface::kAudioKind
1390 ? cricket::MEDIA_TYPE_AUDIO
1391 : cricket::MEDIA_TYPE_VIDEO));
1392 }
1393
1394 // TODO(bugs.webrtc.org/7600): Verify init.
1395
Steve Anton3d954a62018-04-02 11:27:23 -07001396 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1397 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001398 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001399 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1400 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1401 transceiver->internal()->set_direction(init.direction);
1402
Steve Anton22da89f2018-01-25 13:58:07 -08001403 if (fire_callback) {
1404 observer_->OnRenegotiationNeeded();
1405 }
Steve Antonf9381f02017-12-14 10:23:57 -08001406
1407 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1408}
1409
Steve Anton02ee47c2018-01-10 16:26:06 -08001410rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1411PeerConnection::CreateSender(
1412 cricket::MediaType media_type,
1413 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001414 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001415 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001416 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1417 RTC_DCHECK(!track ||
1418 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1419 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1420 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001421 new AudioRtpSender(worker_thread(),
1422 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001423 stream_ids, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001424 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001425 } else {
1426 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1427 RTC_DCHECK(!track ||
1428 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1429 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1430 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001431 new VideoRtpSender(worker_thread(),
1432 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001433 stream_ids));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001434 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001435 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001436 return sender;
1437}
1438
1439rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1440PeerConnection::CreateReceiver(cricket::MediaType media_type,
1441 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001442 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1443 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001444 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001445 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001446 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001447 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001448 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001449 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001450 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001451 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1452 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001453 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001454 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001455 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001456 return receiver;
1457}
1458
1459rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1460PeerConnection::CreateAndAddTransceiver(
1461 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1462 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1463 receiver) {
1464 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1465 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001466 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001467 transceiver->internal()->SignalNegotiationNeeded.connect(
1468 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001469 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001470}
1471
Steve Anton52d86772018-02-20 15:48:12 -08001472void PeerConnection::OnNegotiationNeeded() {
1473 RTC_DCHECK_RUN_ON(signaling_thread());
1474 RTC_DCHECK(!IsClosed());
1475 observer_->OnRenegotiationNeeded();
1476}
1477
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001478rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001480 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001481 if (IsClosed()) {
1482 return nullptr;
1483 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001484 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001485 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001486 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001487 }
Steve Anton4171afb2017-11-20 10:20:22 -08001488 auto track_sender = FindSenderForTrack(track);
1489 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001490 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001491 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001492 }
1493
Steve Anton4171afb2017-11-20 10:20:22 -08001494 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001495}
1496
deadbeeffac06552015-11-25 11:26:01 -08001497rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001498 const std::string& kind,
1499 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001500 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1501 "Plan SdpSemantics. Please use AddTransceiver "
1502 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001503 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001504 if (IsClosed()) {
1505 return nullptr;
1506 }
Steve Anton4171afb2017-11-20 10:20:22 -08001507
Seth Hampson5b4f0752018-04-02 16:31:36 -07001508 // Internally we need to have one stream with Plan B semantics, so we
1509 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001510 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001511 if (stream_id.empty()) {
1512 stream_ids.push_back(rtc::CreateRandomUuid());
1513 RTC_LOG(LS_INFO)
1514 << "No stream_id specified for sender. Generated stream ID: "
1515 << stream_ids[0];
1516 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001517 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001518 }
1519
Steve Anton4171afb2017-11-20 10:20:22 -08001520 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001521 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001522 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001523 auto* audio_sender =
1524 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001525 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001526 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001527 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001528 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001529 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001530 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001531 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001532 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001533 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001534 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001535 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001536 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001537 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001538 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001539 }
Steve Anton4171afb2017-11-20 10:20:22 -08001540
deadbeefe1f9d832016-01-14 15:35:42 -08001541 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001542}
1543
deadbeef70ab1a12015-09-28 16:53:55 -07001544std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1545 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001546 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001547 for (auto sender : GetSendersInternal()) {
1548 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001549 }
1550 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001551}
1552
Steve Anton4171afb2017-11-20 10:20:22 -08001553std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1554PeerConnection::GetSendersInternal() const {
1555 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1556 all_senders;
1557 for (auto transceiver : transceivers_) {
1558 auto senders = transceiver->internal()->senders();
1559 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1560 }
1561 return all_senders;
1562}
1563
deadbeef70ab1a12015-09-28 16:53:55 -07001564std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1565PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001566 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001567 for (const auto& receiver : GetReceiversInternal()) {
1568 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001569 }
1570 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001571}
1572
Steve Anton4171afb2017-11-20 10:20:22 -08001573std::vector<
1574 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1575PeerConnection::GetReceiversInternal() const {
1576 std::vector<
1577 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1578 all_receivers;
1579 for (auto transceiver : transceivers_) {
1580 auto receivers = transceiver->internal()->receivers();
1581 all_receivers.insert(all_receivers.end(), receivers.begin(),
1582 receivers.end());
1583 }
1584 return all_receivers;
1585}
1586
Steve Anton9158ef62017-11-27 13:01:52 -08001587std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1588PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001589 RTC_CHECK(IsUnifiedPlan())
1590 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001591 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1592 for (auto transceiver : transceivers_) {
1593 all_transceivers.push_back(transceiver);
1594 }
1595 return all_transceivers;
1596}
1597
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001598bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001599 MediaStreamTrackInterface* track,
1600 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001601 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001602 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001603 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001604 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001605 return false;
1606 }
1607
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001608 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001609 // The StatsCollector is used to tell if a track is valid because it may
1610 // remember tracks that the PeerConnection previously removed.
1611 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001612 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1613 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001614 return false;
1615 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001616 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001617 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001618 return true;
1619}
1620
hbos74e1a4f2016-09-15 23:33:01 -07001621void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001622 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001623 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001624 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001625 stats_collector_->GetStatsReport(callback);
1626}
1627
Henrik Boström1df1bf82018-03-20 13:24:20 +01001628void PeerConnection::GetStats(
1629 rtc::scoped_refptr<RtpSenderInterface> selector,
1630 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1631 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1632 RTC_DCHECK(callback);
1633 RTC_DCHECK(stats_collector_);
1634 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1635 if (selector) {
1636 for (const auto& proxy_transceiver : transceivers_) {
1637 for (const auto& proxy_sender :
1638 proxy_transceiver->internal()->senders()) {
1639 if (proxy_sender == selector) {
1640 internal_sender = proxy_sender->internal();
1641 break;
1642 }
1643 }
1644 if (internal_sender)
1645 break;
1646 }
1647 }
1648 // If there is no |internal_sender| then |selector| is either null or does not
1649 // belong to the PeerConnection (in Plan B, senders can be removed from the
1650 // PeerConnection). This means that "all the stats objects representing the
1651 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1652 // produces an empty stats report.
1653 stats_collector_->GetStatsReport(internal_sender, callback);
1654}
1655
1656void PeerConnection::GetStats(
1657 rtc::scoped_refptr<RtpReceiverInterface> selector,
1658 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1659 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1660 RTC_DCHECK(callback);
1661 RTC_DCHECK(stats_collector_);
1662 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1663 if (selector) {
1664 for (const auto& proxy_transceiver : transceivers_) {
1665 for (const auto& proxy_receiver :
1666 proxy_transceiver->internal()->receivers()) {
1667 if (proxy_receiver == selector) {
1668 internal_receiver = proxy_receiver->internal();
1669 break;
1670 }
1671 }
1672 if (internal_receiver)
1673 break;
1674 }
1675 }
1676 // If there is no |internal_receiver| then |selector| is either null or does
1677 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1678 // the PeerConnection). This means that "all the stats objects representing
1679 // the selector" is an empty set. Invoking GetStatsReport() with a null
1680 // selector produces an empty stats report.
1681 stats_collector_->GetStatsReport(internal_receiver, callback);
1682}
1683
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001684PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1685 return signaling_state_;
1686}
1687
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688PeerConnectionInterface::IceConnectionState
1689PeerConnection::ice_connection_state() {
1690 return ice_connection_state_;
1691}
1692
1693PeerConnectionInterface::IceGatheringState
1694PeerConnection::ice_gathering_state() {
1695 return ice_gathering_state_;
1696}
1697
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001698rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699PeerConnection::CreateDataChannel(
1700 const std::string& label,
1701 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001702 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001703
deadbeefab9b2d12015-10-14 11:33:11 -07001704 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001705
kwibergd1fe2812016-04-27 06:47:29 -07001706 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001707 if (config) {
1708 internal_config.reset(new InternalDataChannelInit(*config));
1709 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001710 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001711 InternalCreateDataChannel(label, internal_config.get()));
1712 if (!channel.get()) {
1713 return nullptr;
1714 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001715
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001716 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1717 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001718 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001719 observer_->OnRenegotiationNeeded();
1720 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001721 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001722 return DataChannelProxy::Create(signaling_thread(), channel.get());
1723}
1724
1725void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1726 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001727 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001728
zhihuang1c378ed2017-08-17 14:10:50 -07001729 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1730 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1731 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1732 // compares the mandatory fields parsed with the mandatory fields added in the
1733 // |constraints| and some downstream applications might create offers with
1734 // mandatory fields which would not be parsed in the helper method. For
1735 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1736 // |constraints| as a mandatory field but it is not parsed.
1737 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001738
zhihuang1c378ed2017-08-17 14:10:50 -07001739 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001740}
1741
1742void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1743 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001744 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001745
nisse7ce109a2017-01-31 00:57:56 -08001746 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001747 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001748 return;
1749 }
deadbeefab9b2d12015-10-14 11:33:11 -07001750
Steve Anton8d3444d2017-10-20 15:30:51 -07001751 if (IsClosed()) {
1752 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001753 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001754 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001755 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001756 return;
1757 }
1758
zhihuang1c378ed2017-08-17 14:10:50 -07001759 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001760 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001761 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001762 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001763 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001764 return;
1765 }
1766
Steve Anton22da89f2018-01-25 13:58:07 -08001767 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1768 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1769 if (IsUnifiedPlan()) {
1770 RTCError error = HandleLegacyOfferOptions(options);
1771 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001772 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001773 return;
1774 }
1775 }
1776
zhihuang1c378ed2017-08-17 14:10:50 -07001777 cricket::MediaSessionOptions session_options;
1778 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001779 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001780}
1781
Steve Anton22da89f2018-01-25 13:58:07 -08001782RTCError PeerConnection::HandleLegacyOfferOptions(
1783 const RTCOfferAnswerOptions& options) {
1784 RTC_DCHECK(IsUnifiedPlan());
1785
1786 if (options.offer_to_receive_audio == 0) {
1787 RemoveRecvDirectionFromReceivingTransceiversOfType(
1788 cricket::MEDIA_TYPE_AUDIO);
1789 } else if (options.offer_to_receive_audio == 1) {
1790 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1791 } else if (options.offer_to_receive_audio > 1) {
1792 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1793 "offer_to_receive_audio > 1 is not supported.");
1794 }
1795
1796 if (options.offer_to_receive_video == 0) {
1797 RemoveRecvDirectionFromReceivingTransceiversOfType(
1798 cricket::MEDIA_TYPE_VIDEO);
1799 } else if (options.offer_to_receive_video == 1) {
1800 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1801 } else if (options.offer_to_receive_video > 1) {
1802 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1803 "offer_to_receive_video > 1 is not supported.");
1804 }
1805
1806 return RTCError::OK();
1807}
1808
1809void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1810 cricket::MediaType media_type) {
1811 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001812 RtpTransceiverDirection new_direction =
1813 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1814 if (new_direction != transceiver->direction()) {
1815 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1816 << " transceiver (MID="
1817 << transceiver->mid().value_or("<not set>") << ") from "
1818 << RtpTransceiverDirectionToString(
1819 transceiver->direction())
1820 << " to "
1821 << RtpTransceiverDirectionToString(new_direction)
1822 << " since CreateOffer specified offer_to_receive=0";
1823 transceiver->internal()->set_direction(new_direction);
1824 }
Steve Anton22da89f2018-01-25 13:58:07 -08001825 }
1826}
1827
1828void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1829 cricket::MediaType media_type) {
1830 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001831 RTC_LOG(LS_INFO)
1832 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1833 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001834 RtpTransceiverInit init;
1835 init.direction = RtpTransceiverDirection::kRecvOnly;
1836 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1837 }
1838}
1839
1840std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1841PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1842 std::vector<
1843 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1844 receiving_transceivers;
1845 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001846 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001847 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1848 receiving_transceivers.push_back(transceiver);
1849 }
1850 }
1851 return receiving_transceivers;
1852}
1853
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001854void PeerConnection::CreateAnswer(
1855 CreateSessionDescriptionObserver* observer,
1856 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001857 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001858
nisse7ce109a2017-01-31 00:57:56 -08001859 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001860 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861 return;
1862 }
deadbeefab9b2d12015-10-14 11:33:11 -07001863
zhihuang1c378ed2017-08-17 14:10:50 -07001864 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1865 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1866 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001867 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001868 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001869 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001870 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001871 return;
1872 }
1873
Steve Anton8d3444d2017-10-20 15:30:51 -07001874 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001875}
1876
1877void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1878 const RTCOfferAnswerOptions& options) {
1879 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001880 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001881 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001882 return;
1883 }
1884
Steve Antondffead82018-02-06 10:31:29 -08001885 if (!(signaling_state_ == kHaveRemoteOffer ||
1886 signaling_state_ == kHaveLocalPrAnswer)) {
1887 std::string error =
1888 "PeerConnection cannot create an answer in a state other than "
1889 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001890 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001891 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001892 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001893 return;
1894 }
1895
Steve Antondffead82018-02-06 10:31:29 -08001896 // The remote description should be set if we're in the right state.
1897 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001898
Steve Anton22da89f2018-01-25 13:58:07 -08001899 if (IsUnifiedPlan()) {
1900 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1901 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1902 "supported with Unified Plan semantics. Use the "
1903 "RtpTransceiver API instead.";
1904 }
1905 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1906 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1907 "supported with Unified Plan semantics. Use the "
1908 "RtpTransceiver API instead.";
1909 }
1910 }
1911
htaa2a49d92016-03-04 02:51:39 -08001912 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001913 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001914
Steve Antond25da372017-11-06 14:50:29 -08001915 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001916}
1917
1918void PeerConnection::SetLocalDescription(
1919 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001920 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001921 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001922
Steve Anton80dd7b52018-02-16 17:08:42 -08001923 // The SetLocalDescription contract is that we take ownership of the session
1924 // description regardless of the outcome, so wrap it in a unique_ptr right
1925 // away. Ideally, SetLocalDescription's signature will be changed to take the
1926 // description as a unique_ptr argument to formalize this agreement.
1927 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1928
nisse7ce109a2017-01-31 00:57:56 -08001929 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001930 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 return;
1932 }
Steve Anton8a006912017-12-04 15:25:56 -08001933
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001934 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001935 PostSetSessionDescriptionFailure(
1936 observer,
1937 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001938 return;
1939 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001940
Steve Anton80dd7b52018-02-16 17:08:42 -08001941 // If a session error has occurred the PeerConnection is in a possibly
1942 // inconsistent state so fail right away.
1943 if (session_error() != SessionError::kNone) {
1944 std::string error_message = GetSessionErrorMsg();
1945 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001946 PostSetSessionDescriptionFailure(
1947 observer,
1948 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001949 return;
1950 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001951
Steve Anton80dd7b52018-02-16 17:08:42 -08001952 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1953 if (!error.ok()) {
1954 std::string error_message = GetSetDescriptionErrorMessage(
1955 cricket::CS_LOCAL, desc->GetType(), error);
1956 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001957 PostSetSessionDescriptionFailure(
1958 observer,
1959 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001960 return;
1961 }
1962
1963 // Grab the description type before moving ownership to ApplyLocalDescription,
1964 // which may destroy it before returning.
1965 const SdpType type = desc->GetType();
1966
1967 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001968 // |desc| may be destroyed at this point.
1969
1970 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001971 // If ApplyLocalDescription fails, the PeerConnection could be in an
1972 // inconsistent state, so act conservatively here and set the session error
1973 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1974 SetSessionError(SessionError::kContent, error.message());
1975 std::string error_message =
1976 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1977 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001978 PostSetSessionDescriptionFailure(
1979 observer,
1980 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001981 return;
1982 }
Steve Anton8a006912017-12-04 15:25:56 -08001983 RTC_DCHECK(local_description());
1984
1985 PostSetSessionDescriptionSuccess(observer);
1986
Steve Anton8a006912017-12-04 15:25:56 -08001987 // MaybeStartGathering needs to be called after posting
1988 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1989 // before signaling that SetLocalDescription completed.
1990 transport_controller_->MaybeStartGathering();
1991
Steve Antona3a92c22017-12-07 10:27:41 -08001992 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001993 // TODO(deadbeef): We already had to hop to the network thread for
1994 // MaybeStartGathering...
1995 network_thread()->Invoke<void>(
1996 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1997 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001998 // Make UMA notes about what was agreed to.
1999 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002000 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002001 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002002}
2003
2004RTCError PeerConnection::ApplyLocalDescription(
2005 std::unique_ptr<SessionDescriptionInterface> desc) {
2006 RTC_DCHECK_RUN_ON(signaling_thread());
2007 RTC_DCHECK(desc);
2008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 // Update stats here so that we have the most recent stats for tracks and
2010 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002011 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002012
Steve Antondcc3c022017-12-22 16:02:54 -08002013 // Take a reference to the old local description since it's used below to
2014 // compare against the new local description. When setting the new local
2015 // description, grab ownership of the replaced session description in case it
2016 // is the same as |old_local_description|, to keep it alive for the duration
2017 // of the method.
2018 const SessionDescriptionInterface* old_local_description =
2019 local_description();
2020 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002021 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002022 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002023 replaced_local_description = pending_local_description_
2024 ? std::move(pending_local_description_)
2025 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002026 current_local_description_ = std::move(desc);
2027 pending_local_description_ = nullptr;
2028 current_remote_description_ = std::move(pending_remote_description_);
2029 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002030 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002031 pending_local_description_ = std::move(desc);
2032 }
2033 // The session description to apply now must be accessed by
2034 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002035 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002036
Zhi Huange830e682018-03-30 10:48:35 -07002037 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2038 if (!error.ok()) {
2039 return error;
2040 }
2041
Steve Antondcc3c022017-12-22 16:02:54 -08002042 if (IsUnifiedPlan()) {
2043 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002044 cricket::CS_LOCAL, *local_description(), old_local_description,
2045 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002046 if (!error.ok()) {
2047 return error;
2048 }
Steve Antondcc3c022017-12-22 16:02:54 -08002049 for (auto transceiver : transceivers_) {
2050 const ContentInfo* content =
2051 FindMediaSectionForTransceiver(transceiver, local_description());
2052 if (!content) {
2053 continue;
2054 }
2055 const MediaContentDescription* media_desc = content->media_description();
2056 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2057 transceiver->internal()->set_current_direction(media_desc->direction());
2058 }
2059 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002060 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2061 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002062 transceiver->Stop();
2063 }
2064 }
2065 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002066 // Media channels will be created only when offer is set. These may use new
2067 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002068 if (type == SdpType::kOffer) {
2069 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2070 // description is applied. Restore back to old description.
2071 RTCError error = CreateChannels(*local_description()->description());
2072 if (!error.ok()) {
2073 return error;
2074 }
2075 }
Steve Antondcc3c022017-12-22 16:02:54 -08002076 // Remove unused channels if MediaContentDescription is rejected.
2077 RemoveUnusedChannels(local_description()->description());
2078 }
Steve Anton8a006912017-12-04 15:25:56 -08002079
Zhi Huange830e682018-03-30 10:48:35 -07002080 error = UpdateSessionState(type, cricket::CS_LOCAL,
2081 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002082 if (!error.ok()) {
2083 return error;
2084 }
Steve Antondcc3c022017-12-22 16:02:54 -08002085
Steve Anton8a006912017-12-04 15:25:56 -08002086 if (remote_description()) {
2087 // Now that we have a local description, we can push down remote candidates.
2088 UseCandidatesInSessionDescription(remote_description());
2089 }
2090
2091 pending_ice_restarts_.clear();
2092 if (session_error() != SessionError::kNone) {
2093 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2094 }
2095
deadbeefab9b2d12015-10-14 11:33:11 -07002096 // If setting the description decided our SSL role, allocate any necessary
2097 // SCTP sids.
2098 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002099 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002100 AllocateSctpSids(role);
2101 }
2102
Steve Antond3679212018-01-17 17:41:02 -08002103 if (IsUnifiedPlan()) {
2104 for (auto transceiver : transceivers_) {
2105 const ContentInfo* content =
2106 FindMediaSectionForTransceiver(transceiver, local_description());
2107 if (!content) {
2108 continue;
2109 }
Steve Anton74255ff2018-01-24 18:32:57 -08002110 const auto& streams = content->media_description()->streams();
2111 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002112 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002113 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002114 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002115 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002116 }
2117 }
2118 } else {
2119 // Plan B semantics.
2120
Steve Antondcc3c022017-12-22 16:02:54 -08002121 // Update state and SSRC of local MediaStreams and DataChannels based on the
2122 // local session description.
2123 const cricket::ContentInfo* audio_content =
2124 GetFirstAudioContent(local_description()->description());
2125 if (audio_content) {
2126 if (audio_content->rejected) {
2127 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2128 } else {
2129 const cricket::AudioContentDescription* audio_desc =
2130 audio_content->media_description()->as_audio();
2131 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2132 }
deadbeeffaac4972015-11-12 15:33:07 -08002133 }
deadbeefab9b2d12015-10-14 11:33:11 -07002134
Steve Antondcc3c022017-12-22 16:02:54 -08002135 const cricket::ContentInfo* video_content =
2136 GetFirstVideoContent(local_description()->description());
2137 if (video_content) {
2138 if (video_content->rejected) {
2139 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2140 } else {
2141 const cricket::VideoContentDescription* video_desc =
2142 video_content->media_description()->as_video();
2143 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2144 }
deadbeeffaac4972015-11-12 15:33:07 -08002145 }
deadbeefab9b2d12015-10-14 11:33:11 -07002146 }
2147
2148 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002149 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002150 if (data_content) {
2151 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002152 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002153 if (rtc::starts_with(data_desc->protocol().data(),
2154 cricket::kMediaProtocolRtpPrefix)) {
2155 UpdateLocalRtpDataChannels(data_desc->streams());
2156 }
2157 }
2158
Steve Anton8a006912017-12-04 15:25:56 -08002159 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002160}
2161
2162void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002163 SetSessionDescriptionObserver* observer,
2164 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002165 SetRemoteDescription(
2166 std::unique_ptr<SessionDescriptionInterface>(desc),
2167 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2168 new SetRemoteDescriptionObserverAdapter(this, observer)));
2169}
2170
2171void PeerConnection::SetRemoteDescription(
2172 std::unique_ptr<SessionDescriptionInterface> desc,
2173 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002174 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002175
nisse7ce109a2017-01-31 00:57:56 -08002176 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002177 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002178 return;
2179 }
Steve Anton8a006912017-12-04 15:25:56 -08002180
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002182 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002183 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184 return;
2185 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002186
Steve Anton80dd7b52018-02-16 17:08:42 -08002187 // If a session error has occurred the PeerConnection is in a possibly
2188 // inconsistent state so fail right away.
2189 if (session_error() != SessionError::kNone) {
2190 std::string error_message = GetSessionErrorMsg();
2191 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2192 observer->OnSetRemoteDescriptionComplete(
2193 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2194 return;
2195 }
Steve Anton71439a62018-02-15 11:53:06 -08002196
Steve Antonba42e992018-04-09 14:10:01 -07002197 if (desc->GetType() == SdpType::kOffer) {
2198 // Report to UMA the format of the received offer.
2199 ReportSdpFormatReceived(*desc);
2200 }
2201
Steve Anton80dd7b52018-02-16 17:08:42 -08002202 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002203 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002204 std::string error_message = GetSetDescriptionErrorMessage(
2205 cricket::CS_REMOTE, desc->GetType(), error);
2206 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002207 observer->OnSetRemoteDescriptionComplete(
2208 RTCError(error.type(), std::move(error_message)));
2209 return;
2210 }
Steve Anton71439a62018-02-15 11:53:06 -08002211
Steve Anton80dd7b52018-02-16 17:08:42 -08002212 // Grab the description type before moving ownership to
2213 // ApplyRemoteDescription, which may destroy it before returning.
2214 const SdpType type = desc->GetType();
2215
2216 error = ApplyRemoteDescription(std::move(desc));
2217 // |desc| may be destroyed at this point.
2218
2219 if (!error.ok()) {
2220 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2221 // inconsistent state, so act conservatively here and set the session error
2222 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2223 SetSessionError(SessionError::kContent, error.message());
2224 std::string error_message =
2225 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2226 RTC_LOG(LS_ERROR) << error_message;
2227 observer->OnSetRemoteDescriptionComplete(
2228 RTCError(error.type(), std::move(error_message)));
2229 return;
2230 }
2231 RTC_DCHECK(remote_description());
2232
2233 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002234 // TODO(deadbeef): We already had to hop to the network thread for
2235 // MaybeStartGathering...
2236 network_thread()->Invoke<void>(
2237 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2238 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002239 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002240 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002241 }
2242
2243 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002244 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002245}
2246
2247RTCError PeerConnection::ApplyRemoteDescription(
2248 std::unique_ptr<SessionDescriptionInterface> desc) {
2249 RTC_DCHECK_RUN_ON(signaling_thread());
2250 RTC_DCHECK(desc);
2251
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002252 // Update stats here so that we have the most recent stats for tracks and
2253 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002254 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002255
Steve Antondcc3c022017-12-22 16:02:54 -08002256 // Take a reference to the old remote description since it's used below to
2257 // compare against the new remote description. When setting the new remote
2258 // description, grab ownership of the replaced session description in case it
2259 // is the same as |old_remote_description|, to keep it alive for the duration
2260 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002261 const SessionDescriptionInterface* old_remote_description =
2262 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002263 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002264 SdpType type = desc->GetType();
2265 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002266 replaced_remote_description = pending_remote_description_
2267 ? std::move(pending_remote_description_)
2268 : std::move(current_remote_description_);
2269 current_remote_description_ = std::move(desc);
2270 pending_remote_description_ = nullptr;
2271 current_local_description_ = std::move(pending_local_description_);
2272 } else {
2273 replaced_remote_description = std::move(pending_remote_description_);
2274 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002275 }
Steve Anton8a006912017-12-04 15:25:56 -08002276 // The session description to apply now must be accessed by
2277 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002278 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002279
Zhi Huange830e682018-03-30 10:48:35 -07002280 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2281 if (!error.ok()) {
2282 return error;
2283 }
Steve Anton8a006912017-12-04 15:25:56 -08002284 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002285 if (IsUnifiedPlan()) {
2286 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002287 cricket::CS_REMOTE, *remote_description(), local_description(),
2288 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002289 if (!error.ok()) {
2290 return error;
2291 }
Steve Antondcc3c022017-12-22 16:02:54 -08002292 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002293 // Media channels will be created only when offer is set. These may use new
2294 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002295 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002296 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002297 // description is applied. Restore back to old description.
2298 RTCError error = CreateChannels(*remote_description()->description());
2299 if (!error.ok()) {
2300 return error;
2301 }
2302 }
Steve Antondcc3c022017-12-22 16:02:54 -08002303 // Remove unused channels if MediaContentDescription is rejected.
2304 RemoveUnusedChannels(remote_description()->description());
2305 }
Steve Anton8a006912017-12-04 15:25:56 -08002306
Zhi Huange830e682018-03-30 10:48:35 -07002307 // NOTE: Candidates allocation will be initiated only when
2308 // SetLocalDescription is called.
2309 error = UpdateSessionState(type, cricket::CS_REMOTE,
2310 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002311 if (!error.ok()) {
2312 return error;
2313 }
2314
2315 if (local_description() &&
2316 !UseCandidatesInSessionDescription(remote_description())) {
2317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2318 }
2319
2320 if (old_remote_description) {
2321 for (const cricket::ContentInfo& content :
2322 old_remote_description->description()->contents()) {
2323 // Check if this new SessionDescription contains new ICE ufrag and
2324 // password that indicates the remote peer requests an ICE restart.
2325 // TODO(deadbeef): When we start storing both the current and pending
2326 // remote description, this should reset pending_ice_restarts and compare
2327 // against the current description.
2328 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2329 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002330 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002331 pending_ice_restarts_.insert(content.name);
2332 }
2333 } else {
2334 // We retain all received candidates only if ICE is not restarted.
2335 // When ICE is restarted, all previous candidates belong to an old
2336 // generation and should not be kept.
2337 // TODO(deadbeef): This goes against the W3C spec which says the remote
2338 // description should only contain candidates from the last set remote
2339 // description plus any candidates added since then. We should remove
2340 // this once we're sure it won't break anything.
2341 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2342 old_remote_description, content.name, mutable_remote_description());
2343 }
2344 }
2345 }
2346
2347 if (session_error() != SessionError::kNone) {
2348 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2349 }
2350
2351 // Set the the ICE connection state to connecting since the connection may
2352 // become writable with peer reflexive candidates before any remote candidate
2353 // is signaled.
2354 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2355 // is to have a new signal the indicates a change in checking state from the
2356 // transport and expose a new checking() member from transport that can be
2357 // read to determine the current checking state. The existing SignalConnecting
2358 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002359 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002360 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002361 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2362 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2363 }
2364
deadbeefab9b2d12015-10-14 11:33:11 -07002365 // If setting the description decided our SSL role, allocate any necessary
2366 // SCTP sids.
2367 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002368 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002369 AllocateSctpSids(role);
2370 }
2371
Steve Antondcc3c022017-12-22 16:02:54 -08002372 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002373 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002374 now_receiving_transceivers;
2375 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2376 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002377 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002378 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002379 for (auto transceiver : transceivers_) {
2380 const ContentInfo* content =
2381 FindMediaSectionForTransceiver(transceiver, remote_description());
2382 if (!content) {
2383 continue;
2384 }
2385 const MediaContentDescription* media_desc = content->media_description();
2386 RtpTransceiverDirection local_direction =
2387 RtpTransceiverDirectionReversed(media_desc->direction());
2388 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2389 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2390 // transceiver's current direction is neither sendrecv nor recvonly,
2391 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002392 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002393 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002394 // The remote description has signaled the stream IDs.
2395 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002396 }
Steve Antondcc3c022017-12-22 16:02:54 -08002397 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2398 (!transceiver->current_direction() ||
2399 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002400 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002401 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002402 << content->name << " (added to "
2403 << GetStreamIdsString(stream_ids) << ").";
2404
2405 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2406 for (const std::string& stream_id : stream_ids) {
2407 rtc::scoped_refptr<MediaStreamInterface> stream =
2408 remote_streams_->find(stream_id);
2409 if (!stream) {
2410 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2411 MediaStream::Create(stream_id));
2412 remote_streams_->AddStream(stream);
2413 added_streams.push_back(stream);
2414 }
2415 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002416 }
Steve Anton3172c032018-05-03 15:30:18 -07002417 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002418 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002419 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002420 }
2421 // If direction is sendonly or inactive, and transceiver's current
2422 // direction is neither sendonly nor inactive, process the removal of a
2423 // remote track for the media description.
2424 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002425 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002426 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002427 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2428 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002429 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2430 transceiver->internal()->receiver_internal()->streams();
2431 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002432 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002433 no_longer_receiving_transceivers.push_back(transceiver);
2434 // Remove any streams that no longer have tracks.
2435 for (auto stream : media_streams) {
2436 if (stream->GetAudioTracks().empty() &&
2437 stream->GetVideoTracks().empty()) {
2438 remote_streams_->RemoveStream(stream);
2439 removed_streams.push_back(stream);
2440 }
2441 }
Steve Antondcc3c022017-12-22 16:02:54 -08002442 }
2443 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2444 transceiver->internal()->set_current_direction(local_direction);
2445 }
2446 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002447 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2448 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002449 transceiver->Stop();
2450 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002451 if (!content->rejected &&
2452 RtpTransceiverDirectionHasRecv(local_direction)) {
2453 // Set ssrc to 0 in the case of an unsignalled ssrc.
2454 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002455 if (!media_desc->streams().empty() &&
2456 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002457 ssrc = media_desc->streams()[0].first_ssrc();
2458 }
2459 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002460 }
Steve Antondcc3c022017-12-22 16:02:54 -08002461 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002462 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002463 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002464 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002465 observer_->OnTrack(transceiver);
2466 observer_->OnAddTrack(transceiver->receiver(),
2467 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002468 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002469 for (auto stream : added_streams) {
2470 observer_->OnAddStream(stream);
2471 }
Steve Anton3172c032018-05-03 15:30:18 -07002472 for (auto transceiver : no_longer_receiving_transceivers) {
2473 observer_->OnRemoveTrack(transceiver->receiver());
2474 }
2475 for (auto stream : removed_streams) {
2476 observer_->OnRemoveStream(stream);
2477 }
Steve Antondcc3c022017-12-22 16:02:54 -08002478 }
2479
Henrik Boströmfdb92012017-11-09 19:55:44 +01002480 const cricket::ContentInfo* audio_content =
2481 GetFirstAudioContent(remote_description()->description());
2482 const cricket::ContentInfo* video_content =
2483 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002484 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002485 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002486 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002487 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002488 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002489 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002490
2491 // Check if the descriptions include streams, just in case the peer supports
2492 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002493 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002494 (audio_desc && !audio_desc->streams().empty()) ||
2495 (video_desc && !video_desc->streams().empty())) {
2496 remote_peer_supports_msid_ = true;
2497 }
deadbeefab9b2d12015-10-14 11:33:11 -07002498
2499 // We wait to signal new streams until we finish processing the description,
2500 // since only at that point will new streams have all their tracks.
2501 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2502
Steve Antondcc3c022017-12-22 16:02:54 -08002503 if (!IsUnifiedPlan()) {
2504 // TODO(steveanton): When removing RTP senders/receivers in response to a
2505 // rejected media section, there is some cleanup logic that expects the
2506 // voice/ video channel to still be set. But in this method the voice/video
2507 // channel would have been destroyed by the SetRemoteDescription caller
2508 // above so the cleanup that relies on them fails to run. The RemoveSenders
2509 // calls should be moved to right before the DestroyChannel calls to fix
2510 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002511
Steve Antondcc3c022017-12-22 16:02:54 -08002512 // Find all audio rtp streams and create corresponding remote AudioTracks
2513 // and MediaStreams.
2514 if (audio_content) {
2515 if (audio_content->rejected) {
2516 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2517 } else {
2518 bool default_audio_track_needed =
2519 !remote_peer_supports_msid_ &&
2520 RtpTransceiverDirectionHasSend(audio_desc->direction());
2521 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2522 default_audio_track_needed, audio_desc->type(),
2523 new_streams);
2524 }
deadbeeffaac4972015-11-12 15:33:07 -08002525 }
deadbeefab9b2d12015-10-14 11:33:11 -07002526
Steve Antondcc3c022017-12-22 16:02:54 -08002527 // Find all video rtp streams and create corresponding remote VideoTracks
2528 // and MediaStreams.
2529 if (video_content) {
2530 if (video_content->rejected) {
2531 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2532 } else {
2533 bool default_video_track_needed =
2534 !remote_peer_supports_msid_ &&
2535 RtpTransceiverDirectionHasSend(video_desc->direction());
2536 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2537 default_video_track_needed, video_desc->type(),
2538 new_streams);
2539 }
deadbeeffaac4972015-11-12 15:33:07 -08002540 }
deadbeefab9b2d12015-10-14 11:33:11 -07002541
Steve Antondcc3c022017-12-22 16:02:54 -08002542 // Update the DataChannels with the information from the remote peer.
2543 if (data_desc) {
2544 if (rtc::starts_with(data_desc->protocol().data(),
2545 cricket::kMediaProtocolRtpPrefix)) {
2546 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2547 }
deadbeefab9b2d12015-10-14 11:33:11 -07002548 }
deadbeefab9b2d12015-10-14 11:33:11 -07002549
Steve Antondcc3c022017-12-22 16:02:54 -08002550 // Iterate new_streams and notify the observer about new MediaStreams.
2551 for (size_t i = 0; i < new_streams->count(); ++i) {
2552 MediaStreamInterface* new_stream = new_streams->at(i);
2553 stats_->AddStream(new_stream);
2554 observer_->OnAddStream(
2555 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2556 }
deadbeefab9b2d12015-10-14 11:33:11 -07002557
Steve Antondcc3c022017-12-22 16:02:54 -08002558 UpdateEndedRemoteMediaStreams();
2559 }
deadbeefab9b2d12015-10-14 11:33:11 -07002560
Steve Anton8a006912017-12-04 15:25:56 -08002561 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002562}
2563
Steve Antondcc3c022017-12-22 16:02:54 -08002564RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2565 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002566 const SessionDescriptionInterface& new_session,
2567 const SessionDescriptionInterface* old_local_description,
2568 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002569 RTC_DCHECK(IsUnifiedPlan());
2570
Steve Anton7464fca2018-01-19 11:10:37 -08002571 const cricket::ContentGroup* bundle_group = nullptr;
2572 if (new_session.GetType() == SdpType::kOffer) {
2573 auto bundle_group_or_error =
2574 GetEarlyBundleGroup(*new_session.description());
2575 if (!bundle_group_or_error.ok()) {
2576 return bundle_group_or_error.MoveError();
2577 }
2578 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002579 }
Steve Antondcc3c022017-12-22 16:02:54 -08002580
Steve Antondcc3c022017-12-22 16:02:54 -08002581 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002582 for (size_t i = 0; i < new_contents.size(); ++i) {
2583 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002584 cricket::MediaType media_type = new_content.media_description()->type();
2585 seen_mids_.insert(new_content.name);
2586 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2587 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002588 const cricket::ContentInfo* old_local_content = nullptr;
2589 if (old_local_description &&
2590 i < old_local_description->description()->contents().size()) {
2591 old_local_content =
2592 &old_local_description->description()->contents()[i];
2593 }
2594 const cricket::ContentInfo* old_remote_content = nullptr;
2595 if (old_remote_description &&
2596 i < old_remote_description->description()->contents().size()) {
2597 old_remote_content =
2598 &old_remote_description->description()->contents()[i];
2599 }
Steve Antondcc3c022017-12-22 16:02:54 -08002600 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002601 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2602 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002603 if (!transceiver_or_error.ok()) {
2604 return transceiver_or_error.MoveError();
2605 }
2606 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002607 RTCError error =
2608 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2609 if (!error.ok()) {
2610 return error;
2611 }
2612 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002613 if (GetDataMid() && new_content.name != *GetDataMid()) {
2614 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002615 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2616 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002617 continue;
2618 }
2619 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2620 if (!error.ok()) {
2621 return error;
2622 }
Steve Antondcc3c022017-12-22 16:02:54 -08002623 } else {
2624 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2625 "Unknown section type.");
2626 }
2627 }
2628
2629 return RTCError::OK();
2630}
2631
2632RTCError PeerConnection::UpdateTransceiverChannel(
2633 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2634 transceiver,
2635 const cricket::ContentInfo& content,
2636 const cricket::ContentGroup* bundle_group) {
2637 RTC_DCHECK(IsUnifiedPlan());
2638 RTC_DCHECK(transceiver);
2639 cricket::BaseChannel* channel = transceiver->internal()->channel();
2640 if (content.rejected) {
2641 if (channel) {
2642 transceiver->internal()->SetChannel(nullptr);
2643 DestroyBaseChannel(channel);
2644 }
2645 } else {
2646 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002647 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002648 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002649 } else {
Steve Anton69470252018-02-09 11:43:08 -08002650 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002651 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002652 }
2653 if (!channel) {
2654 LOG_AND_RETURN_ERROR(
2655 RTCErrorType::INTERNAL_ERROR,
2656 "Failed to create channel for mid=" + content.name);
2657 }
2658 transceiver->internal()->SetChannel(channel);
2659 }
2660 }
2661 return RTCError::OK();
2662}
2663
Steve Antonfa2260d2017-12-28 16:38:23 -08002664RTCError PeerConnection::UpdateDataChannel(
2665 cricket::ContentSource source,
2666 const cricket::ContentInfo& content,
2667 const cricket::ContentGroup* bundle_group) {
2668 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002669 // If data channels are disabled, ignore this media section. CreateAnswer
2670 // will take care of rejecting it.
2671 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002672 }
2673 if (content.rejected) {
2674 DestroyDataChannel();
2675 } else {
2676 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002677 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002678 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2679 "Failed to create data channel.");
2680 }
2681 }
2682 if (source == cricket::CS_REMOTE) {
2683 const MediaContentDescription* data_desc = content.media_description();
2684 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2685 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2686 }
2687 }
2688 }
2689 return RTCError::OK();
2690}
2691
Steve Antondcc3c022017-12-22 16:02:54 -08002692RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2693PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002694 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002695 size_t mline_index,
2696 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002697 const ContentInfo* old_local_content,
2698 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002699 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002700 // If this is an offer then the m= section might be recycled. If the m=
2701 // section is being recycled (defined as: rejected in the current local or
2702 // remote description and not rejected in new description), dissociate the
2703 // currently associated RtpTransceiver by setting its mid property to null,
2704 // and discard the mapping between the transceiver and its m= section index.
2705 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2706 old_remote_content)) {
2707 // We want to dissociate the transceiver that has the rejected mid.
2708 const std::string& old_mid =
2709 (old_local_content && old_local_content->rejected)
2710 ? old_local_content->name
2711 : old_remote_content->name;
2712 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002713 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002714 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2715 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-22 16:02:54 -08002716 old_transceiver->internal()->set_mid(rtc::nullopt);
2717 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2718 }
2719 }
2720 const MediaContentDescription* media_desc = content.media_description();
2721 auto transceiver = GetAssociatedTransceiver(content.name);
2722 if (source == cricket::CS_LOCAL) {
2723 // Find the RtpTransceiver that corresponds to this m= section, using the
2724 // mapping between transceivers and m= section indices established when
2725 // creating the offer.
2726 if (!transceiver) {
2727 transceiver = GetTransceiverByMLineIndex(mline_index);
2728 }
2729 if (!transceiver) {
2730 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2731 "Unknown transceiver");
2732 }
2733 } else {
2734 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2735 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2736 // of the same type...
2737 if (!transceiver &&
2738 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2739 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2740 }
2741 // If no RtpTransceiver was found in the previous step, create one with a
2742 // recvonly direction.
2743 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002744 RTC_LOG(LS_INFO) << "Adding "
2745 << cricket::MediaTypeToString(media_desc->type())
2746 << " transceiver for MID=" << content.name
2747 << " at i=" << mline_index
2748 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002749 auto sender =
2750 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002751 std::string receiver_id;
2752 if (!media_desc->streams().empty()) {
2753 receiver_id = media_desc->streams()[0].id;
2754 } else {
2755 receiver_id = rtc::CreateRandomUuid();
2756 }
2757 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002758 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002759 transceiver->internal()->set_direction(
2760 RtpTransceiverDirection::kRecvOnly);
2761 }
2762 }
2763 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002764 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002765 LOG_AND_RETURN_ERROR(
2766 RTCErrorType::INVALID_PARAMETER,
2767 "Transceiver type does not match media description type.");
2768 }
2769 // Associate the found or created RtpTransceiver with the m= section by
2770 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2771 // section, and establish a mapping between the transceiver and the index of
2772 // the m= section.
2773 transceiver->internal()->set_mid(content.name);
2774 transceiver->internal()->set_mline_index(mline_index);
2775 return std::move(transceiver);
2776}
2777
2778rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2779PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2780 RTC_DCHECK(IsUnifiedPlan());
2781 for (auto transceiver : transceivers_) {
2782 if (transceiver->mid() == mid) {
2783 return transceiver;
2784 }
2785 }
2786 return nullptr;
2787}
2788
2789rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2790PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2791 RTC_DCHECK(IsUnifiedPlan());
2792 for (auto transceiver : transceivers_) {
2793 if (transceiver->internal()->mline_index() == mline_index) {
2794 return transceiver;
2795 }
2796 }
2797 return nullptr;
2798}
2799
2800rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2801PeerConnection::FindAvailableTransceiverToReceive(
2802 cricket::MediaType media_type) const {
2803 RTC_DCHECK(IsUnifiedPlan());
2804 // From JSEP section 5.10 (Applying a Remote Description):
2805 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2806 // the same type that were added to the PeerConnection by addTrack and are not
2807 // associated with any m= section and are not stopped, find the first such
2808 // RtpTransceiver.
2809 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002810 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002811 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2812 !transceiver->stopped()) {
2813 return transceiver;
2814 }
2815 }
2816 return nullptr;
2817}
2818
Steve Antoned10bd92017-12-05 10:52:59 -08002819const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2820 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2821 transceiver,
2822 const SessionDescriptionInterface* sdesc) const {
2823 RTC_DCHECK(transceiver);
2824 RTC_DCHECK(sdesc);
2825 if (IsUnifiedPlan()) {
2826 if (!transceiver->internal()->mid()) {
2827 // This transceiver is not associated with a media section yet.
2828 return nullptr;
2829 }
2830 return sdesc->description()->GetContentByName(
2831 *transceiver->internal()->mid());
2832 } else {
2833 // Plan B only allows at most one audio and one video section, so use the
2834 // first media section of that type.
2835 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002836 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002837 }
2838}
2839
deadbeef46c73892016-11-16 19:42:04 -08002840PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2841 return configuration_;
2842}
2843
deadbeef293e9262017-01-11 12:28:30 -08002844bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2845 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002846 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002847 if (IsClosed()) {
2848 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2849 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2850 }
2851
Qingsi Wanga2d60672018-04-11 16:57:45 -07002852 // According to JSEP, after setLocalDescription, changing the candidate pool
2853 // size is not allowed, and changing the set of ICE servers will not result
2854 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002855 if (local_description() && configuration.ice_candidate_pool_size !=
2856 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002857 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2858 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002859 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002860 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002861
deadbeef293e9262017-01-11 12:28:30 -08002862 // The simplest (and most future-compatible) way to tell if the config was
2863 // modified in an invalid way is to copy each property we do support
2864 // modifying, then use operator==. There are far more properties we don't
2865 // support modifying than those we do, and more could be added.
2866 RTCConfiguration modified_config = configuration_;
2867 modified_config.servers = configuration.servers;
2868 modified_config.type = configuration.type;
2869 modified_config.ice_candidate_pool_size =
2870 configuration.ice_candidate_pool_size;
2871 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002872 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002873 modified_config.ice_check_interval_strong_connectivity =
2874 configuration.ice_check_interval_strong_connectivity;
2875 modified_config.ice_check_interval_weak_connectivity =
2876 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002877 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2878 modified_config.ice_unwritable_min_checks =
2879 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002880 modified_config.stun_candidate_keepalive_interval =
2881 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002882 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002883 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002884 modified_config.active_reset_srtp_params =
2885 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002886 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002887 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002888 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2889 }
2890
Steve Anton038834f2017-07-14 15:59:59 -07002891 // Validate the modified configuration.
2892 RTCError validate_error = ValidateConfiguration(modified_config);
2893 if (!validate_error.ok()) {
2894 return SafeSetError(std::move(validate_error), error);
2895 }
2896
deadbeef293e9262017-01-11 12:28:30 -08002897 // Note that this isn't possible through chromium, since it's an unsigned
2898 // short in WebIDL.
2899 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002900 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002901 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2902 }
2903
2904 // Parse ICE servers before hopping to network thread.
2905 cricket::ServerAddresses stun_servers;
2906 std::vector<cricket::RelayServerConfig> turn_servers;
2907 RTCErrorType parse_error =
2908 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2909 if (parse_error != RTCErrorType::NONE) {
2910 return SafeSetError(parse_error, error);
2911 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002912 // Note if STUN or TURN servers were supplied.
2913 if (!stun_servers.empty()) {
2914 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2915 }
2916 if (!turn_servers.empty()) {
2917 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2918 }
deadbeef293e9262017-01-11 12:28:30 -08002919
2920 // In theory this shouldn't fail.
2921 if (!network_thread()->Invoke<bool>(
2922 RTC_FROM_HERE,
2923 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2924 stun_servers, turn_servers, modified_config.type,
2925 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002926 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002927 modified_config.turn_customizer,
2928 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002929 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002930 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2931 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002932
deadbeefd1a38b52016-12-10 13:15:33 -08002933 // As described in JSEP, calling setConfiguration with new ICE servers or
2934 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2935 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002936 if (modified_config.servers != configuration_.servers ||
2937 modified_config.type != configuration_.type ||
2938 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002939 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002940 }
skvladd1f5fda2017-02-03 16:54:05 -08002941
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002942 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002943
Zhi Huangb57e1692018-06-12 11:41:11 -07002944 if (configuration_.active_reset_srtp_params !=
2945 modified_config.active_reset_srtp_params) {
2946 transport_controller_->SetActiveResetSrtpParams(
2947 modified_config.active_reset_srtp_params);
2948 }
2949
deadbeef293e9262017-01-11 12:28:30 -08002950 configuration_ = modified_config;
2951 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002952}
2953
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002954bool PeerConnection::AddIceCandidate(
2955 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002956 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002957 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002958 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002959 return false;
2960 }
Steve Antond25da372017-11-06 14:50:29 -08002961
2962 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002963 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002964 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002965 return false;
2966 }
2967
2968 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002969 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002970 return false;
2971 }
2972
2973 bool valid = false;
2974 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2975 if (!valid) {
2976 return false;
2977 }
2978
2979 // Add this candidate to the remote session description.
2980 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002981 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002982 return false;
2983 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002984 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002985
2986 if (ready) {
2987 return UseCandidate(ice_candidate);
2988 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002989 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002990 return true;
2991 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002992}
2993
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002994bool PeerConnection::RemoveIceCandidates(
2995 const std::vector<cricket::Candidate>& candidates) {
2996 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002997 if (IsClosed()) {
2998 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2999 return false;
3000 }
3001
Steve Antond25da372017-11-06 14:50:29 -08003002 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003003 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3004 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003005 return false;
3006 }
3007
3008 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003009 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003010 return false;
3011 }
3012
3013 size_t number_removed =
3014 mutable_remote_description()->RemoveCandidates(candidates);
3015 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003016 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003017 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003018 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003019 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003020 }
3021
3022 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003023 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3024 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003025 RTC_LOG(LS_ERROR)
3026 << "RemoveIceCandidates: Error when removing remote candidates: "
3027 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003028 }
3029 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003030}
3031
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003032void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003033 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003034 network_thread()->Invoke<void>(
3035 RTC_FROM_HERE,
3036 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3037 // Send information about IPv4/IPv6 status.
3038 if (uma_observer_) {
3039 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3040 uma_observer_->IncrementEnumCounter(
3041 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3042 kPeerConnectionAddressFamilyCounter_Max);
3043 } else {
3044 uma_observer_->IncrementEnumCounter(
3045 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3046 kPeerConnectionAddressFamilyCounter_Max);
3047 }
3048 }
3049}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003050
Qingsi Wanga2d60672018-04-11 16:57:45 -07003051void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3052 RTC_DCHECK(network_thread()->IsCurrent());
3053 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003054 if (transport_controller_) {
3055 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003056 }
3057
3058 for (auto transceiver : transceivers_) {
3059 auto* channel = transceiver->internal()->channel();
3060 if (channel) {
3061 channel->SetMetricsObserver(uma_observer_);
3062 }
3063 }
3064
deadbeef293e9262017-01-11 12:28:30 -08003065 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003066 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003067 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003068}
3069
Niels Möller0c4f7be2018-05-07 14:01:37 +02003070RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003071 if (!worker_thread()->IsCurrent()) {
3072 return worker_thread()->Invoke<RTCError>(
Niels Möller0c4f7be2018-05-07 14:01:37 +02003073 RTC_FROM_HERE, [&](){ return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003074 }
3075
Niels Möller0c4f7be2018-05-07 14:01:37 +02003076 const bool has_min = bitrate.min_bitrate_bps.has_value();
3077 const bool has_start = bitrate.start_bitrate_bps.has_value();
3078 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003079 if (has_min && *bitrate.min_bitrate_bps < 0) {
3080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3081 "min_bitrate_bps <= 0");
3082 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003083 if (has_start) {
3084 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003085 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003086 "start_bitrate_bps < min_bitrate_bps");
3087 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003088 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3089 "curent_bitrate_bps < 0");
3090 }
3091 }
3092 if (has_max) {
Niels Möller0c4f7be2018-05-07 14:01:37 +02003093 if (has_start &&
3094 *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003095 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003096 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003097 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3098 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3099 "max_bitrate_bps < min_bitrate_bps");
3100 } else if (*bitrate.max_bitrate_bps < 0) {
3101 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3102 "max_bitrate_bps < 0");
3103 }
3104 }
3105
zstein4b979802017-06-02 14:37:37 -07003106 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003107 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003108
3109 return RTCError::OK();
3110}
3111
Alex Narest78609d52017-10-20 10:37:47 +02003112void PeerConnection::SetBitrateAllocationStrategy(
3113 std::unique_ptr<rtc::BitrateAllocationStrategy>
3114 bitrate_allocation_strategy) {
3115 rtc::Thread* worker_thread = factory_->worker_thread();
3116 if (!worker_thread->IsCurrent()) {
3117 rtc::BitrateAllocationStrategy* strategy_raw =
3118 bitrate_allocation_strategy.release();
3119 auto functor = [this, strategy_raw]() {
3120 call_->SetBitrateAllocationStrategy(
3121 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3122 };
3123 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3124 return;
3125 }
3126 RTC_DCHECK(call_.get());
3127 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3128}
3129
henrika5f6bf242017-11-01 11:06:56 +01003130void PeerConnection::SetAudioPlayout(bool playout) {
3131 if (!worker_thread()->IsCurrent()) {
3132 worker_thread()->Invoke<void>(
3133 RTC_FROM_HERE,
3134 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3135 return;
3136 }
3137 auto audio_state =
3138 factory_->channel_manager()->media_engine()->GetAudioState();
3139 audio_state->SetPlayout(playout);
3140}
3141
3142void PeerConnection::SetAudioRecording(bool recording) {
3143 if (!worker_thread()->IsCurrent()) {
3144 worker_thread()->Invoke<void>(
3145 RTC_FROM_HERE,
3146 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3147 return;
3148 }
3149 auto audio_state =
3150 factory_->channel_manager()->media_engine()->GetAudioState();
3151 audio_state->SetRecording(recording);
3152}
3153
Steve Anton8c0f7a72017-10-03 10:03:10 -07003154std::unique_ptr<rtc::SSLCertificate>
3155PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003156 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3157 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003158 return nullptr;
3159 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003160 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003161}
3162
Zhi Huang70b820f2018-01-27 14:16:15 -08003163std::unique_ptr<rtc::SSLCertChain>
3164PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003165 auto audio_transceiver = GetFirstAudioTransceiver();
3166 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003167 return nullptr;
3168 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003169 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003170 audio_transceiver->internal()->channel()->transport_name());
3171}
3172
3173rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3174PeerConnection::GetFirstAudioTransceiver() const {
3175 for (auto transceiver : transceivers_) {
3176 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3177 return transceiver;
3178 }
3179 }
3180 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003181}
3182
ivoc14d5dbe2016-07-04 07:06:55 -07003183bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3184 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003185 // TODO(eladalon): It would be better to not allow negative values into PC.
3186 const size_t max_size = (max_size_bytes < 0)
3187 ? RtcEventLog::kUnlimitedOutput
3188 : rtc::saturated_cast<size_t>(max_size_bytes);
3189 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003190 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3191 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003192}
3193
Bjorn Tereliusde939432017-11-20 17:38:14 +01003194bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3195 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003196 // TODO(eladalon): In C++14, this can be done with a lambda.
3197 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003198 bool operator()() {
3199 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3200 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003201 PeerConnection* const pc;
3202 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003203 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003204 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003205 return worker_thread()->Invoke<bool>(
3206 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003207}
3208
3209void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003210 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003211 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3212}
3213
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003214const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003215 return pending_local_description_ ? pending_local_description_.get()
3216 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217}
3218
3219const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003220 return pending_remote_description_ ? pending_remote_description_.get()
3221 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003222}
3223
deadbeeffe4a8a42016-12-20 17:56:17 -08003224const SessionDescriptionInterface* PeerConnection::current_local_description()
3225 const {
Steve Anton75737c02017-11-06 10:37:17 -08003226 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003227}
3228
3229const SessionDescriptionInterface* PeerConnection::current_remote_description()
3230 const {
Steve Anton75737c02017-11-06 10:37:17 -08003231 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003232}
3233
3234const SessionDescriptionInterface* PeerConnection::pending_local_description()
3235 const {
Steve Anton75737c02017-11-06 10:37:17 -08003236 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003237}
3238
3239const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3240 const {
Steve Anton75737c02017-11-06 10:37:17 -08003241 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003242}
3243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003244void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003245 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246 // Update stats here so that we have the most recent stats for tracks and
3247 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003248 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003249
Steve Anton75737c02017-11-06 10:37:17 -08003250 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003251 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003252
Steve Anton8af21862017-12-15 11:20:13 -08003253 for (auto transceiver : transceivers_) {
3254 transceiver->Stop();
3255 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003256
3257 // Ensure that all asynchronous stats requests are completed before destroying
3258 // the transport controller below.
3259 if (stats_collector_) {
3260 stats_collector_->WaitForPendingRequest();
3261 }
3262
3263 // Don't destroy BaseChannels until after stats has been cleaned up so that
3264 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003265 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003266
Qingsi Wang93a84392018-01-30 17:13:09 -08003267 // The event log is used in the transport controller, which must be outlived
3268 // by the former. CreateOffer by the peer connection is implemented
3269 // asynchronously and if the peer connection is closed without resetting the
3270 // WebRTC session description factory, the session description factory would
3271 // call the transport controller.
3272 webrtc_session_desc_factory_.reset();
3273 transport_controller_.reset();
3274
deadbeef42a42632017-03-10 15:18:00 -08003275 network_thread()->Invoke<void>(
3276 RTC_FROM_HERE,
3277 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3278 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003279
Steve Anton978b8762017-09-29 12:15:02 -07003280 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003281 call_.reset();
3282 // The event log must outlive call (and any other object that uses it).
3283 event_log_.reset();
3284 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003285 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003286}
3287
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003288void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003289 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003290 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3291 SetSessionDescriptionMsg* param =
3292 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3293 param->observer->OnSuccess();
3294 delete param;
3295 break;
3296 }
3297 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3298 SetSessionDescriptionMsg* param =
3299 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003300 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003301 delete param;
3302 break;
3303 }
deadbeefab9b2d12015-10-14 11:33:11 -07003304 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3305 CreateSessionDescriptionMsg* param =
3306 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003307 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003308 delete param;
3309 break;
3310 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003311 case MSG_GETSTATS: {
3312 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003313 StatsReports reports;
3314 stats_->GetStats(param->track, &reports);
3315 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003316 delete param;
3317 break;
3318 }
deadbeefbd292462015-12-14 18:15:29 -08003319 case MSG_FREE_DATACHANNELS: {
3320 sctp_data_channels_to_free_.clear();
3321 break;
3322 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003323 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003324 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003325 break;
3326 }
3327}
3328
Steve Antonafb0bb72018-02-20 11:35:37 -08003329cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3330 RTC_DCHECK(!IsUnifiedPlan());
3331 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3332 GetAudioTransceiver()->internal()->channel());
3333 if (voice_channel) {
3334 return voice_channel->media_channel();
3335 } else {
3336 return nullptr;
3337 }
3338}
3339
3340cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3341 RTC_DCHECK(!IsUnifiedPlan());
3342 auto* video_channel = static_cast<cricket::VideoChannel*>(
3343 GetVideoTransceiver()->internal()->channel());
3344 if (video_channel) {
3345 return video_channel->media_channel();
3346 } else {
3347 return nullptr;
3348 }
3349}
3350
Steve Anton4171afb2017-11-20 10:20:22 -08003351void PeerConnection::CreateAudioReceiver(
3352 MediaStreamInterface* stream,
3353 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003354 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3355 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003356 auto* audio_receiver = new AudioRtpReceiver(
3357 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003358 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003359 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3360 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3361 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003362 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003363 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003364 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365}
3366
Steve Anton4171afb2017-11-20 10:20:22 -08003367void PeerConnection::CreateVideoReceiver(
3368 MediaStreamInterface* stream,
3369 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003370 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3371 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003372 auto* video_receiver = new VideoRtpReceiver(
3373 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003374 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003375 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3376 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3377 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003378 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003379 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003380 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003381}
3382
deadbeef70ab1a12015-09-28 16:53:55 -07003383// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3384// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003385rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003386 const RtpSenderInfo& remote_sender_info) {
3387 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3388 if (!receiver) {
3389 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3390 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003391 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003392 }
Steve Anton4171afb2017-11-20 10:20:22 -08003393 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3394 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3395 } else {
3396 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3397 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003398 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003399}
3400
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003401void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3402 MediaStreamInterface* stream) {
3403 RTC_DCHECK(!IsClosed());
3404 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003405 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003406 // We already have a sender for this track, so just change the stream_id
3407 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003408 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003409 return;
3410 }
3411
3412 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003413 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003414 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003415 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003416 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003417 // If the sender has already been configured in SDP, we call SetSsrc,
3418 // which will connect the sender to the underlying transport. This can
3419 // occur if a local session description that contains the ID of the sender
3420 // is set before AddStream is called. It can also occur if the local
3421 // session description is not changed and RemoveStream is called, and
3422 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003423 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003424 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003425 if (sender_info) {
3426 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003427 }
3428}
3429
3430// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3431// indefinitely, when we have unified plan SDP.
3432void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3433 MediaStreamInterface* stream) {
3434 RTC_DCHECK(!IsClosed());
3435 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003436 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003437 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3438 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003439 return;
3440 }
Steve Anton4171afb2017-11-20 10:20:22 -08003441 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003442}
3443
3444void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3445 MediaStreamInterface* stream) {
3446 RTC_DCHECK(!IsClosed());
3447 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003448 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003449 // We already have a sender for this track, so just change the stream_id
3450 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003451 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003452 return;
3453 }
3454
3455 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003456 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003457 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003458 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003459 GetVideoTransceiver()->internal()->AddSender(new_sender);
3460 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003461 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003462 if (sender_info) {
3463 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003464 }
3465}
3466
3467void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3468 MediaStreamInterface* stream) {
3469 RTC_DCHECK(!IsClosed());
3470 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003471 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003472 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3473 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003474 return;
3475 }
Steve Anton4171afb2017-11-20 10:20:22 -08003476 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003477}
3478
Steve Antonba818672017-11-06 10:21:57 -08003479void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003480 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003481 if (ice_connection_state_ == new_state) {
3482 return;
3483 }
3484
deadbeefcbecd352015-09-23 11:50:27 -07003485 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003486 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003487 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003488 return;
3489 }
Steve Antonba818672017-11-06 10:21:57 -08003490
Mirko Bonadei675513b2017-11-09 11:09:25 +01003491 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3492 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003493 RTC_DCHECK(ice_connection_state_ !=
3494 PeerConnectionInterface::kIceConnectionClosed);
3495
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003497 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003498}
3499
3500void PeerConnection::OnIceGatheringChange(
3501 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003502 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003503 if (IsClosed()) {
3504 return;
3505 }
3506 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003507 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508}
3509
jbauch81bf7b02017-03-25 08:31:12 -07003510void PeerConnection::OnIceCandidate(
3511 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003512 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003513 if (IsClosed()) {
3514 return;
3515 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003516 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003517 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003518}
3519
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003520void PeerConnection::OnIceCandidatesRemoved(
3521 const std::vector<cricket::Candidate>& candidates) {
3522 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003523 if (IsClosed()) {
3524 return;
3525 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003526 observer_->OnIceCandidatesRemoved(candidates);
3527}
3528
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529void PeerConnection::ChangeSignalingState(
3530 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003531 RTC_DCHECK(signaling_thread()->IsCurrent());
3532 if (signaling_state_ == signaling_state) {
3533 return;
3534 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003535 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3536 << GetSignalingStateString(signaling_state_)
3537 << " New state: "
3538 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003539 signaling_state_ = signaling_state;
3540 if (signaling_state == kClosed) {
3541 ice_connection_state_ = kIceConnectionClosed;
3542 observer_->OnIceConnectionChange(ice_connection_state_);
3543 if (ice_gathering_state_ != kIceGatheringComplete) {
3544 ice_gathering_state_ = kIceGatheringComplete;
3545 observer_->OnIceGatheringChange(ice_gathering_state_);
3546 }
3547 }
3548 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003549}
3550
deadbeefeb459812015-12-15 19:24:43 -08003551void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3552 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003553 if (IsClosed()) {
3554 return;
3555 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003556 AddAudioTrack(track, stream);
3557 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003558}
3559
deadbeefeb459812015-12-15 19:24:43 -08003560void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3561 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003562 if (IsClosed()) {
3563 return;
3564 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003565 RemoveAudioTrack(track, stream);
3566 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003567}
3568
3569void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3570 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003571 if (IsClosed()) {
3572 return;
3573 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003574 AddVideoTrack(track, stream);
3575 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003576}
3577
3578void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3579 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003580 if (IsClosed()) {
3581 return;
3582 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003583 RemoveVideoTrack(track, stream);
3584 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003585}
3586
Henrik Boström31638672017-11-23 17:48:32 +01003587void PeerConnection::PostSetSessionDescriptionSuccess(
3588 SetSessionDescriptionObserver* observer) {
3589 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3590 signaling_thread()->Post(RTC_FROM_HERE, this,
3591 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3592}
3593
deadbeefab9b2d12015-10-14 11:33:11 -07003594void PeerConnection::PostSetSessionDescriptionFailure(
3595 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003596 RTCError&& error) {
3597 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003598 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003599 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003600 signaling_thread()->Post(RTC_FROM_HERE, this,
3601 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003602}
3603
3604void PeerConnection::PostCreateSessionDescriptionFailure(
3605 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003606 RTCError error) {
3607 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003608 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003609 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003610 signaling_thread()->Post(RTC_FROM_HERE, this,
3611 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003612}
3613
zhihuang1c378ed2017-08-17 14:10:50 -07003614void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003615 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003616 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003617 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003618
Steve Antondcc3c022017-12-22 16:02:54 -08003619 if (IsUnifiedPlan()) {
3620 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3621 } else {
3622 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3623 }
3624
Steve Antonfa2260d2017-12-28 16:38:23 -08003625 // Intentionally unset the data channel type for RTP data channel with the
3626 // second condition. Otherwise the RTP data channels would be successfully
3627 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3628 // when building with chromium. We want to leave RTP data channels broken, so
3629 // people won't try to use them.
3630 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3631 session_options->data_channel_type = data_channel_type();
3632 }
3633
Steve Antondcc3c022017-12-22 16:02:54 -08003634 // Apply ICE restart flag and renomination flag.
3635 for (auto& options : session_options->media_description_options) {
3636 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3637 options.transport_options.enable_ice_renomination =
3638 configuration_.enable_ice_renomination;
3639 }
3640
3641 session_options->rtcp_cname = rtcp_cname_;
3642 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003643 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003644}
3645
3646void PeerConnection::GetOptionsForPlanBOffer(
3647 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3648 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003649 // Figure out transceiver directional preferences.
3650 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3651 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3652
3653 // By default, generate sendrecv/recvonly m= sections.
3654 bool recv_audio = true;
3655 bool recv_video = true;
3656
3657 // By default, only offer a new m= section if we have media to send with it.
3658 bool offer_new_audio_description = send_audio;
3659 bool offer_new_video_description = send_video;
3660 bool offer_new_data_description = HasDataChannels();
3661
3662 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003663 if (offer_answer_options.offer_to_receive_audio !=
3664 RTCOfferAnswerOptions::kUndefined) {
3665 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003666 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003667 offer_new_audio_description ||
3668 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003669 }
Steve Antondcc3c022017-12-22 16:02:54 -08003670 if (offer_answer_options.offer_to_receive_video !=
3671 RTCOfferAnswerOptions::kUndefined) {
3672 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003673 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003674 offer_new_video_description ||
3675 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003676 }
3677
3678 rtc::Optional<size_t> audio_index;
3679 rtc::Optional<size_t> video_index;
3680 rtc::Optional<size_t> data_index;
3681 // If a current description exists, generate m= sections in the same order,
3682 // using the first audio/video/data section that appears and rejecting
3683 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003684 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003685 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003686 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003687 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3688 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3689 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003690 }
3691
zhihuang1c378ed2017-08-17 14:10:50 -07003692 // Add audio/video/data m= sections to the end if needed.
3693 if (!audio_index && offer_new_audio_description) {
3694 session_options->media_description_options.push_back(
3695 cricket::MediaDescriptionOptions(
3696 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003697 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3698 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003699 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003700 }
zhihuang1c378ed2017-08-17 14:10:50 -07003701 if (!video_index && offer_new_video_description) {
3702 session_options->media_description_options.push_back(
3703 cricket::MediaDescriptionOptions(
3704 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003705 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3706 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003707 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003708 }
zhihuang1c378ed2017-08-17 14:10:50 -07003709 if (!data_index && offer_new_data_description) {
3710 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003711 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003712 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003713 }
3714
3715 cricket::MediaDescriptionOptions* audio_media_description_options =
3716 !audio_index ? nullptr
3717 : &session_options->media_description_options[*audio_index];
3718 cricket::MediaDescriptionOptions* video_media_description_options =
3719 !video_index ? nullptr
3720 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003721
Steve Anton4171afb2017-11-20 10:20:22 -08003722 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003723 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003724}
3725
3726// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3727// and return a reference to it.
3728// Generated MIDs should be no more than 3 bytes long to take up less space in
3729// the RTP packet.
3730static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3731 RTC_DCHECK(used_mids);
3732 // We're boring: just generate MIDs 0, 1, 2, ...
3733 size_t i = 0;
3734 std::set<std::string>::iterator it;
3735 bool inserted;
3736 do {
3737 std::string mid = rtc::ToString(i++);
3738 auto insert_result = used_mids->insert(mid);
3739 it = insert_result.first;
3740 inserted = insert_result.second;
3741 } while (!inserted);
3742 return *it;
3743}
3744
3745static cricket::MediaDescriptionOptions
3746GetMediaDescriptionOptionsForTransceiver(
3747 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3748 transceiver,
3749 const std::string& mid) {
3750 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003751 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003752 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003753 // This behavior is specified in JSEP. The gist is that:
3754 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3755 // sendrecv.
3756 // 2. If the MSID is included, then it must be included in any subsequent
3757 // offer/answer exactly the same until the RtpTransceiver is stopped.
3758 if (!transceiver->stopped() &&
3759 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3760 transceiver->internal()->has_ever_been_used_to_send())) {
3761 cricket::SenderOptions sender_options;
3762 sender_options.track_id = transceiver->sender()->id();
3763 sender_options.stream_ids = transceiver->sender()->stream_ids();
3764 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3765 // set in the RTP parameters when the transceiver was added.
3766 sender_options.num_sim_layers = 1;
3767 media_description_options.sender_options.push_back(sender_options);
3768 }
Steve Antondcc3c022017-12-22 16:02:54 -08003769 return media_description_options;
3770}
3771
3772void PeerConnection::GetOptionsForUnifiedPlanOffer(
3773 const RTCOfferAnswerOptions& offer_answer_options,
3774 cricket::MediaSessionOptions* session_options) {
3775 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3776 // Offers) and 5.2.2 (Subsequent Offers).
3777 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3778 const ContentInfos& local_contents =
3779 (local_description() ? local_description()->description()->contents()
3780 : ContentInfos());
3781 const ContentInfos& remote_contents =
3782 (remote_description() ? remote_description()->description()->contents()
3783 : ContentInfos());
3784 // The mline indices that can be recycled. New transceivers should reuse these
3785 // slots first.
3786 std::queue<size_t> recycleable_mline_indices;
3787 // Track the MIDs used in previous offer/answer exchanges and the current
3788 // offer so that new, unique MIDs are generated.
3789 std::set<std::string> used_mids = seen_mids_;
3790 // First, go through each media section that exists in either the local or
3791 // remote description and generate a media section in this offer for the
3792 // associated transceiver. If a media section can be recycled, generate a
3793 // default, rejected media section here that can be later overwritten.
3794 for (size_t i = 0;
3795 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3796 // Either |local_content| or |remote_content| is non-null.
3797 const ContentInfo* local_content =
3798 (i < local_contents.size() ? &local_contents[i] : nullptr);
3799 const ContentInfo* remote_content =
3800 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3801 bool had_been_rejected = (local_content && local_content->rejected) ||
3802 (remote_content && remote_content->rejected);
3803 const std::string& mid =
3804 (local_content ? local_content->name : remote_content->name);
3805 cricket::MediaType media_type =
3806 (local_content ? local_content->media_description()->type()
3807 : remote_content->media_description()->type());
3808 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3809 media_type == cricket::MEDIA_TYPE_VIDEO) {
3810 auto transceiver = GetAssociatedTransceiver(mid);
3811 RTC_CHECK(transceiver);
3812 // A media section is considered eligible for recycling if it is marked as
3813 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003814 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003815 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003816 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3817 RtpTransceiverDirection::kInactive,
3818 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003819 recycleable_mline_indices.push(i);
3820 } else {
3821 session_options->media_description_options.push_back(
3822 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3823 // CreateOffer shouldn't really cause any state changes in
3824 // PeerConnection, but we need a way to match new transceivers to new
3825 // media sections in SetLocalDescription and JSEP specifies this is done
3826 // by recording the index of the media section generated for the
3827 // transceiver in the offer.
3828 transceiver->internal()->set_mline_index(i);
3829 }
3830 } else {
3831 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003832 RTC_CHECK(GetDataMid());
3833 if (had_been_rejected || mid != *GetDataMid()) {
3834 session_options->media_description_options.push_back(
3835 GetMediaDescriptionOptionsForRejectedData(mid));
3836 } else {
3837 session_options->media_description_options.push_back(
3838 GetMediaDescriptionOptionsForActiveData(mid));
3839 }
Steve Antondcc3c022017-12-22 16:02:54 -08003840 }
3841 }
3842 // Next, look for transceivers that are newly added (that is, are not stopped
3843 // and not associated). Reuse media sections marked as recyclable first,
3844 // otherwise append to the end of the offer. New media sections should be
3845 // added in the order they were added to the PeerConnection.
3846 for (auto transceiver : transceivers_) {
3847 if (transceiver->mid() || transceiver->stopped()) {
3848 continue;
3849 }
3850 size_t mline_index;
3851 if (!recycleable_mline_indices.empty()) {
3852 mline_index = recycleable_mline_indices.front();
3853 recycleable_mline_indices.pop();
3854 session_options->media_description_options[mline_index] =
3855 GetMediaDescriptionOptionsForTransceiver(transceiver,
3856 AllocateMid(&used_mids));
3857 } else {
3858 mline_index = session_options->media_description_options.size();
3859 session_options->media_description_options.push_back(
3860 GetMediaDescriptionOptionsForTransceiver(transceiver,
3861 AllocateMid(&used_mids)));
3862 }
3863 // See comment above for why CreateOffer changes the transceiver's state.
3864 transceiver->internal()->set_mline_index(mline_index);
3865 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003866 // Lastly, add a m-section if we have local data channels and an m section
3867 // does not already exist.
3868 if (!GetDataMid() && HasDataChannels()) {
3869 session_options->media_description_options.push_back(
3870 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3871 }
Steve Antondcc3c022017-12-22 16:02:54 -08003872}
3873
3874void PeerConnection::GetOptionsForAnswer(
3875 const RTCOfferAnswerOptions& offer_answer_options,
3876 cricket::MediaSessionOptions* session_options) {
3877 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3878
3879 if (IsUnifiedPlan()) {
3880 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3881 } else {
3882 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3883 }
3884
Steve Antonfa2260d2017-12-28 16:38:23 -08003885 // Intentionally unset the data channel type for RTP data channel. Otherwise
3886 // the RTP data channels would be successfully negotiated by default and the
3887 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3888 // We want to leave RTP data channels broken, so people won't try to use them.
3889 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3890 session_options->data_channel_type = data_channel_type();
3891 }
3892
Steve Antondcc3c022017-12-22 16:02:54 -08003893 // Apply ICE renomination flag.
3894 for (auto& options : session_options->media_description_options) {
3895 options.transport_options.enable_ice_renomination =
3896 configuration_.enable_ice_renomination;
3897 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003898
3899 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003900 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003901 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003902}
3903
Steve Antondcc3c022017-12-22 16:02:54 -08003904void PeerConnection::GetOptionsForPlanBAnswer(
3905 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003906 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003907 // Figure out transceiver directional preferences.
3908 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3909 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3910
3911 // By default, generate sendrecv/recvonly m= sections. The direction is also
3912 // restricted by the direction in the offer.
3913 bool recv_audio = true;
3914 bool recv_video = true;
3915
3916 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003917 if (offer_answer_options.offer_to_receive_audio !=
3918 RTCOfferAnswerOptions::kUndefined) {
3919 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003920 }
Steve Antondcc3c022017-12-22 16:02:54 -08003921 if (offer_answer_options.offer_to_receive_video !=
3922 RTCOfferAnswerOptions::kUndefined) {
3923 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003924 }
3925
3926 rtc::Optional<size_t> audio_index;
3927 rtc::Optional<size_t> video_index;
3928 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003929
3930 // Generate m= sections that match those in the offer.
3931 // Note that mediasession.cc will handle intersection our preferred
3932 // direction with the offered direction.
3933 GenerateMediaDescriptionOptions(
3934 remote_description(),
3935 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3936 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3937 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003938
3939 cricket::MediaDescriptionOptions* audio_media_description_options =
3940 !audio_index ? nullptr
3941 : &session_options->media_description_options[*audio_index];
3942 cricket::MediaDescriptionOptions* video_media_description_options =
3943 !video_index ? nullptr
3944 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003945
Steve Anton4171afb2017-11-20 10:20:22 -08003946 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003947 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003948}
zhihuangaf388472016-11-02 16:49:48 -07003949
Steve Antondcc3c022017-12-22 16:02:54 -08003950void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3951 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3952 cricket::MediaSessionOptions* session_options) {
3953 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3954 // Answers) and 5.3.2 (Subsequent Answers).
3955 RTC_DCHECK(remote_description());
3956 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3957 for (const ContentInfo& content :
3958 remote_description()->description()->contents()) {
3959 cricket::MediaType media_type = content.media_description()->type();
3960 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3961 media_type == cricket::MEDIA_TYPE_VIDEO) {
3962 auto transceiver = GetAssociatedTransceiver(content.name);
3963 RTC_CHECK(transceiver);
3964 session_options->media_description_options.push_back(
3965 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3966 } else {
3967 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003968 // Reject all data sections if data channels are disabled.
3969 // Reject a data section if it has already been rejected.
3970 // Reject all data sections except for the first one.
3971 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3972 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003973 session_options->media_description_options.push_back(
3974 GetMediaDescriptionOptionsForRejectedData(content.name));
3975 } else {
3976 session_options->media_description_options.push_back(
3977 GetMediaDescriptionOptionsForActiveData(content.name));
3978 }
Steve Antondcc3c022017-12-22 16:02:54 -08003979 }
3980 }
htaa2a49d92016-03-04 02:51:39 -08003981}
3982
zhihuang1c378ed2017-08-17 14:10:50 -07003983void PeerConnection::GenerateMediaDescriptionOptions(
3984 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003985 RtpTransceiverDirection audio_direction,
3986 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003987 rtc::Optional<size_t>* audio_index,
3988 rtc::Optional<size_t>* video_index,
3989 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003990 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003991 for (const cricket::ContentInfo& content :
3992 session_desc->description()->contents()) {
3993 if (IsAudioContent(&content)) {
3994 // If we already have an audio m= section, reject this extra one.
3995 if (*audio_index) {
3996 session_options->media_description_options.push_back(
3997 cricket::MediaDescriptionOptions(
3998 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003999 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004000 } else {
4001 session_options->media_description_options.push_back(
4002 cricket::MediaDescriptionOptions(
4003 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004004 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004005 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004006 }
4007 } else if (IsVideoContent(&content)) {
4008 // If we already have an video m= section, reject this extra one.
4009 if (*video_index) {
4010 session_options->media_description_options.push_back(
4011 cricket::MediaDescriptionOptions(
4012 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004013 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004014 } else {
4015 session_options->media_description_options.push_back(
4016 cricket::MediaDescriptionOptions(
4017 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004018 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004019 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004020 }
4021 } else {
4022 RTC_DCHECK(IsDataContent(&content));
4023 // If we already have an data m= section, reject this extra one.
4024 if (*data_index) {
4025 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004026 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004027 } else {
4028 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004029 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004030 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004031 }
4032 }
htaa2a49d92016-03-04 02:51:39 -08004033 }
deadbeefab9b2d12015-10-14 11:33:11 -07004034}
4035
Steve Antonfa2260d2017-12-28 16:38:23 -08004036cricket::MediaDescriptionOptions
4037PeerConnection::GetMediaDescriptionOptionsForActiveData(
4038 const std::string& mid) const {
4039 // Direction for data sections is meaningless, but legacy endpoints might
4040 // expect sendrecv.
4041 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4042 RtpTransceiverDirection::kSendRecv,
4043 /*stopped=*/false);
4044 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4045 return options;
4046}
4047
4048cricket::MediaDescriptionOptions
4049PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4050 const std::string& mid) const {
4051 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4052 RtpTransceiverDirection::kInactive,
4053 /*stopped=*/true);
4054 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4055 return options;
4056}
4057
4058rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4059 switch (data_channel_type_) {
4060 case cricket::DCT_RTP:
4061 if (!rtp_data_channel_) {
4062 return rtc::nullopt;
4063 }
4064 return rtp_data_channel_->content_name();
4065 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004066 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004067 default:
4068 return rtc::nullopt;
4069 }
4070}
4071
Steve Anton4171afb2017-11-20 10:20:22 -08004072void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4073 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4074 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004075 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004076}
4077
Steve Anton4171afb2017-11-20 10:20:22 -08004078void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004079 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004080 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004081 cricket::MediaType media_type,
4082 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004083 RTC_DCHECK(!IsUnifiedPlan());
4084
Steve Anton4171afb2017-11-20 10:20:22 -08004085 std::vector<RtpSenderInfo>* current_senders =
4086 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004087
Steve Anton4171afb2017-11-20 10:20:22 -08004088 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004089 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004090 for (auto sender_it = current_senders->begin();
4091 sender_it != current_senders->end();
4092 /* incremented manually */) {
4093 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004094 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004095 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004096 std::string params_stream_id;
4097 if (params) {
4098 params_stream_id =
4099 (!params->first_stream_id().empty() ? params->first_stream_id()
4100 : kDefaultStreamId);
4101 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004102 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004103 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004104 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004105 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004106 sender_exists) {
4107 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004108 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004109 OnRemoteSenderRemoved(info, media_type);
4110 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004111 }
4112 }
4113
Steve Anton4171afb2017-11-20 10:20:22 -08004114 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004115 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004116 if (!params.has_ssrcs()) {
4117 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4118 // sender, this means it is coming from a Unified Plan endpoint,so we just
4119 // create a default.
4120 default_sender_needed = true;
4121 break;
4122 }
4123
Seth Hampson845e8782018-03-02 11:34:10 -08004124 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004125 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004126 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4127 // not supported in Plan B, we just take the first here and create the
4128 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004129 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004130 (!params.first_stream_id().empty() ? params.first_stream_id()
4131 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004132 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004133 uint32_t ssrc = params.first_ssrc();
4134
4135 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004136 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004137 if (!stream) {
4138 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004139 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004140 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004141 remote_streams_->AddStream(stream);
4142 new_streams->AddStream(stream);
4143 }
4144
Steve Anton4171afb2017-11-20 10:20:22 -08004145 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004146 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004147 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004148 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004149 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004150 }
4151 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004152
Steve Anton4171afb2017-11-20 10:20:22 -08004153 // Add default sender if necessary.
4154 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004155 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004156 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004157 if (!default_stream) {
4158 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004159 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004160 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004161 remote_streams_->AddStream(default_stream);
4162 new_streams->AddStream(default_stream);
4163 }
Steve Anton4171afb2017-11-20 10:20:22 -08004164 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4165 ? kDefaultAudioSenderId
4166 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004167 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004168 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004169 if (!default_sender_info) {
4170 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004171 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004172 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004173 }
4174 }
deadbeefab9b2d12015-10-14 11:33:11 -07004175}
4176
Steve Anton4171afb2017-11-20 10:20:22 -08004177void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4178 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004179 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4180 << " receiver for track_id=" << sender_info.sender_id
4181 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004182
Steve Anton3d954a62018-04-02 11:27:23 -07004183 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004184 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004185 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004186 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004187 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004188 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004189 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004190 }
4191}
4192
Steve Anton4171afb2017-11-20 10:20:22 -08004193void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4194 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004195 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4196 << " receiver for track_id=" << sender_info.sender_id
4197 << " and stream_id=" << sender_info.stream_id;
4198
Seth Hampson845e8782018-03-02 11:34:10 -08004199 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004200
Henrik Boström933d8b02017-10-10 10:05:16 -07004201 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004202 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004203 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4204 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004205 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004206 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004207 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004208 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004209 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004210 }
4211 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004212 // Stopping or destroying a VideoRtpReceiver will end the
4213 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004214 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004215 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004216 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004217 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004218 // There's no guarantee the track is still available, e.g. the track may
4219 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004220 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004221 }
4222 } else {
nisseede5da42017-01-12 05:15:36 -08004223 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004224 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004225 if (receiver) {
4226 observer_->OnRemoveTrack(receiver);
4227 }
deadbeefab9b2d12015-10-14 11:33:11 -07004228}
4229
4230void PeerConnection::UpdateEndedRemoteMediaStreams() {
4231 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4232 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4233 MediaStreamInterface* stream = remote_streams_->at(i);
4234 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4235 streams_to_remove.push_back(stream);
4236 }
4237 }
4238
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004239 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004240 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004241 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004242 }
4243}
4244
Steve Anton4171afb2017-11-20 10:20:22 -08004245void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004246 const std::vector<cricket::StreamParams>& streams,
4247 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004248 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004249
Seth Hampson845e8782018-03-02 11:34:10 -08004250 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004251 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004252 for (auto sender_it = current_senders->begin();
4253 sender_it != current_senders->end();
4254 /* incremented manually */) {
4255 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004256 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004257 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4258 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004259 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004260 OnLocalSenderRemoved(info, media_type);
4261 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004262 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004263 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004264 }
4265 }
4266
Steve Anton4171afb2017-11-20 10:20:22 -08004267 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004268 for (const cricket::StreamParams& params : streams) {
4269 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004270 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004271 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004272 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004273 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004274 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004275 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004276 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004277 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004278 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004279 }
4280 }
4281}
4282
Steve Anton4171afb2017-11-20 10:20:22 -08004283void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4284 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004285 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004286 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004287 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004288 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4289 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004290 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004291 return;
4292 }
4293
deadbeeffac06552015-11-25 11:26:01 -08004294 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004295 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004296 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004297 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004298 }
deadbeeffac06552015-11-25 11:26:01 -08004299
Seth Hampson5b4f0752018-04-02 16:31:36 -07004300 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004301 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004302}
4303
Steve Anton4171afb2017-11-20 10:20:22 -08004304void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4305 cricket::MediaType media_type) {
4306 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004307 if (!sender) {
4308 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004309 // SessionDescriptions has been renegotiated.
4310 return;
4311 }
deadbeeffac06552015-11-25 11:26:01 -08004312
4313 // A sender has been removed from the SessionDescription but it's still
4314 // associated with the PeerConnection. This only occurs if the SDP doesn't
4315 // match with the calls to CreateSender, AddStream and RemoveStream.
4316 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004317 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004318 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004319 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004320 }
deadbeeffac06552015-11-25 11:26:01 -08004321
Steve Anton4171afb2017-11-20 10:20:22 -08004322 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004323}
4324
4325void PeerConnection::UpdateLocalRtpDataChannels(
4326 const cricket::StreamParamsVec& streams) {
4327 std::vector<std::string> existing_channels;
4328
4329 // Find new and active data channels.
4330 for (const cricket::StreamParams& params : streams) {
4331 // |it->sync_label| is actually the data channel label. The reason is that
4332 // we use the same naming of data channels as we do for
4333 // MediaStreams and Tracks.
4334 // For MediaStreams, the sync_label is the MediaStream label and the
4335 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004336 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004337 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004338 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004339 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004340 continue;
4341 }
4342 // Set the SSRC the data channel should use for sending.
4343 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4344 existing_channels.push_back(data_channel_it->first);
4345 }
4346
4347 UpdateClosingRtpDataChannels(existing_channels, true);
4348}
4349
4350void PeerConnection::UpdateRemoteRtpDataChannels(
4351 const cricket::StreamParamsVec& streams) {
4352 std::vector<std::string> existing_channels;
4353
4354 // Find new and active data channels.
4355 for (const cricket::StreamParams& params : streams) {
4356 // The data channel label is either the mslabel or the SSRC if the mslabel
4357 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004358 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004359 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004360 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004361 auto data_channel_it = rtp_data_channels_.find(label);
4362 if (data_channel_it == rtp_data_channels_.end()) {
4363 // This is a new data channel.
4364 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4365 } else {
4366 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4367 }
4368 existing_channels.push_back(label);
4369 }
4370
4371 UpdateClosingRtpDataChannels(existing_channels, false);
4372}
4373
4374void PeerConnection::UpdateClosingRtpDataChannels(
4375 const std::vector<std::string>& active_channels,
4376 bool is_local_update) {
4377 auto it = rtp_data_channels_.begin();
4378 while (it != rtp_data_channels_.end()) {
4379 DataChannel* data_channel = it->second;
4380 if (std::find(active_channels.begin(), active_channels.end(),
4381 data_channel->label()) != active_channels.end()) {
4382 ++it;
4383 continue;
4384 }
4385
4386 if (is_local_update) {
4387 data_channel->SetSendSsrc(0);
4388 } else {
4389 data_channel->RemotePeerRequestClose();
4390 }
4391
4392 if (data_channel->state() == DataChannel::kClosed) {
4393 rtp_data_channels_.erase(it);
4394 it = rtp_data_channels_.begin();
4395 } else {
4396 ++it;
4397 }
4398 }
4399}
4400
4401void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4402 uint32_t remote_ssrc) {
4403 rtc::scoped_refptr<DataChannel> channel(
4404 InternalCreateDataChannel(label, nullptr));
4405 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004406 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004407 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004408 return;
4409 }
4410 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004411 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4412 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004413 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004414}
4415
4416rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4417 const std::string& label,
4418 const InternalDataChannelInit* config) {
4419 if (IsClosed()) {
4420 return nullptr;
4421 }
Steve Anton75737c02017-11-06 10:37:17 -08004422 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004423 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004424 << "InternalCreateDataChannel: Data is not supported in this call.";
4425 return nullptr;
4426 }
4427 InternalDataChannelInit new_config =
4428 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004429 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004430 if (new_config.id < 0) {
4431 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004432 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004433 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004434 RTC_LOG(LS_ERROR)
4435 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004436 return nullptr;
4437 }
4438 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004439 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004440 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004441 return nullptr;
4442 }
4443 }
4444
Steve Anton75737c02017-11-06 10:37:17 -08004445 rtc::scoped_refptr<DataChannel> channel(
4446 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004447 if (!channel) {
4448 sid_allocator_.ReleaseSid(new_config.id);
4449 return nullptr;
4450 }
4451
4452 if (channel->data_channel_type() == cricket::DCT_RTP) {
4453 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004454 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4455 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004456 return nullptr;
4457 }
4458 rtp_data_channels_[channel->label()] = channel;
4459 } else {
4460 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4461 sctp_data_channels_.push_back(channel);
4462 channel->SignalClosed.connect(this,
4463 &PeerConnection::OnSctpDataChannelClosed);
4464 }
4465
Steve Anton2d8609c2018-01-23 16:38:46 -08004466 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004467 return channel;
4468}
4469
4470bool PeerConnection::HasDataChannels() const {
4471 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4472}
4473
4474void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4475 for (const auto& channel : sctp_data_channels_) {
4476 if (channel->id() < 0) {
4477 int sid;
4478 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004479 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004480 continue;
4481 }
4482 channel->SetSctpSid(sid);
4483 }
4484 }
4485}
4486
4487void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004488 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004489 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4490 ++it) {
4491 if (it->get() == channel) {
4492 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004493 // After the closing procedure is done, it's safe to use this ID for
4494 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004495 sid_allocator_.ReleaseSid(channel->id());
4496 }
deadbeefbd292462015-12-14 18:15:29 -08004497 // Since this method is triggered by a signal from the DataChannel,
4498 // we can't free it directly here; we need to free it asynchronously.
4499 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004500 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004501 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4502 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004503 return;
4504 }
4505 }
4506}
4507
deadbeefab9b2d12015-10-14 11:33:11 -07004508void PeerConnection::OnDataChannelDestroyed() {
4509 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4510 // DataChannel may callback to us and try to modify the list.
4511 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4512 temp_rtp_dcs.swap(rtp_data_channels_);
4513 for (const auto& kv : temp_rtp_dcs) {
4514 kv.second->OnTransportChannelDestroyed();
4515 }
4516
4517 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4518 temp_sctp_dcs.swap(sctp_data_channels_);
4519 for (const auto& channel : temp_sctp_dcs) {
4520 channel->OnTransportChannelDestroyed();
4521 }
4522}
4523
4524void PeerConnection::OnDataChannelOpenMessage(
4525 const std::string& label,
4526 const InternalDataChannelInit& config) {
4527 rtc::scoped_refptr<DataChannel> channel(
4528 InternalCreateDataChannel(label, &config));
4529 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004530 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004531 return;
4532 }
4533
deadbeefa601f5c2016-06-06 14:27:39 -07004534 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4535 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004536 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004537}
4538
Steve Anton4171afb2017-11-20 10:20:22 -08004539rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4540PeerConnection::GetAudioTransceiver() const {
4541 // This method only works with Plan B SDP, where there is a single
4542 // audio/video transceiver.
4543 RTC_DCHECK(!IsUnifiedPlan());
4544 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004545 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004546 return transceiver;
4547 }
4548 }
4549 RTC_NOTREACHED();
4550 return nullptr;
4551}
4552
4553rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4554PeerConnection::GetVideoTransceiver() const {
4555 // This method only works with Plan B SDP, where there is a single
4556 // audio/video transceiver.
4557 RTC_DCHECK(!IsUnifiedPlan());
4558 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004559 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004560 return transceiver;
4561 }
4562 }
4563 RTC_NOTREACHED();
4564 return nullptr;
4565}
4566
4567// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4568// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004569bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004570 switch (type) {
4571 case cricket::MEDIA_TYPE_AUDIO:
4572 return !GetAudioTransceiver()->internal()->senders().empty();
4573 case cricket::MEDIA_TYPE_VIDEO:
4574 return !GetVideoTransceiver()->internal()->senders().empty();
4575 case cricket::MEDIA_TYPE_DATA:
4576 return false;
4577 }
4578 RTC_NOTREACHED();
4579 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004580}
4581
Steve Anton4171afb2017-11-20 10:20:22 -08004582rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4583PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4584 for (auto transceiver : transceivers_) {
4585 for (auto sender : transceiver->internal()->senders()) {
4586 if (sender->track() == track) {
4587 return sender;
4588 }
4589 }
4590 }
4591 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004592}
4593
Steve Anton4171afb2017-11-20 10:20:22 -08004594rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4595PeerConnection::FindSenderById(const std::string& sender_id) const {
4596 for (auto transceiver : transceivers_) {
4597 for (auto sender : transceiver->internal()->senders()) {
4598 if (sender->id() == sender_id) {
4599 return sender;
4600 }
4601 }
4602 }
4603 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004604}
4605
Steve Anton4171afb2017-11-20 10:20:22 -08004606rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4607PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4608 for (auto transceiver : transceivers_) {
4609 for (auto receiver : transceiver->internal()->receivers()) {
4610 if (receiver->id() == receiver_id) {
4611 return receiver;
4612 }
4613 }
4614 }
4615 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004616}
4617
Steve Anton4171afb2017-11-20 10:20:22 -08004618std::vector<PeerConnection::RtpSenderInfo>*
4619PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4620 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4621 media_type == cricket::MEDIA_TYPE_VIDEO);
4622 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4623 ? &remote_audio_sender_infos_
4624 : &remote_video_sender_infos_;
4625}
4626
4627std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004628 cricket::MediaType media_type) {
4629 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4630 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004631 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4632 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004633}
4634
Steve Anton4171afb2017-11-20 10:20:22 -08004635const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4636 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004637 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004638 const std::string sender_id) const {
4639 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004640 if (sender_info.stream_id == stream_id &&
4641 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004642 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004643 }
4644 }
4645 return nullptr;
4646}
4647
4648DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4649 for (const auto& channel : sctp_data_channels_) {
4650 if (channel->id() == sid) {
4651 return channel;
4652 }
4653 }
4654 return nullptr;
4655}
4656
deadbeef91dd5672016-05-18 16:55:30 -07004657bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004658 const RTCConfiguration& configuration) {
4659 cricket::ServerAddresses stun_servers;
4660 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004661 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4662 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004663 return false;
4664 }
4665
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004666 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004667 // To handle both internal and externally created port allocator, we will
4668 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004669 port_allocator_flags_ = port_allocator_->flags();
4670 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4671 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4672 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004673 // If the disable-IPv6 flag was specified, we'll not override it
4674 // by experiment.
4675 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004676 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004677 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4678 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004679 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004680 }
4681
zhihuangb09b3f92017-03-07 14:40:51 -08004682 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004683 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004684 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004685 }
4686
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004687 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004688 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004689 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004690 }
4691
honghaiz60347052016-05-31 18:29:12 -07004692 if (configuration.candidate_network_policy ==
4693 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004694 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004695 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004696 }
4697
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004698 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004699 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004700 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4701 }
4702
Qingsi Wanga2d60672018-04-11 16:57:45 -07004703 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004704 // No step delay is used while allocating ports.
4705 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4706 port_allocator_->set_candidate_filter(
4707 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004708 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004709
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004710 if (tls_cert_verifier_ != nullptr) {
4711 for (auto& turn_server : turn_servers) {
4712 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4713 }
4714 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004715 // Call this last since it may create pooled allocator sessions using the
4716 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004717 port_allocator_->SetConfiguration(
4718 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4719 configuration.prune_turn_ports, configuration.turn_customizer,
4720 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004721 return true;
4722}
4723
deadbeef91dd5672016-05-18 16:55:30 -07004724bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004725 const cricket::ServerAddresses& stun_servers,
4726 const std::vector<cricket::RelayServerConfig>& turn_servers,
4727 IceTransportsType type,
4728 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004729 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004730 webrtc::TurnCustomizer* turn_customizer,
4731 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004732 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004733 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004734 // According to JSEP, after setLocalDescription, changing the candidate pool
4735 // size is not allowed, and changing the set of ICE servers will not result
4736 // in new candidates being gathered.
4737 if (local_description()) {
4738 port_allocator_->FreezeCandidatePool();
4739 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004740 // Call this last since it may create pooled allocator sessions using the
4741 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004742 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004743 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004744 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004745}
4746
Steve Antonba818672017-11-06 10:21:57 -08004747cricket::ChannelManager* PeerConnection::channel_manager() const {
4748 return factory_->channel_manager();
4749}
4750
4751MetricsObserverInterface* PeerConnection::metrics_observer() const {
4752 return uma_observer_;
4753}
4754
Elad Alon99c3fe52017-10-13 16:29:40 +02004755bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004756 std::unique_ptr<RtcEventLogOutput> output,
4757 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004758 if (!event_log_) {
4759 return false;
4760 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004761 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004762}
4763
4764void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004765 if (event_log_) {
4766 event_log_->StopLogging();
4767 }
ivoc14d5dbe2016-07-04 07:06:55 -07004768}
nisseeaabdf62017-05-05 02:23:02 -07004769
Steve Anton75737c02017-11-06 10:37:17 -08004770cricket::BaseChannel* PeerConnection::GetChannel(
4771 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004772 for (auto transceiver : transceivers_) {
4773 cricket::BaseChannel* channel = transceiver->internal()->channel();
4774 if (channel && channel->content_name() == content_name) {
4775 return channel;
4776 }
Steve Anton75737c02017-11-06 10:37:17 -08004777 }
4778 if (rtp_data_channel() &&
4779 rtp_data_channel()->content_name() == content_name) {
4780 return rtp_data_channel();
4781 }
4782 return nullptr;
4783}
4784
4785bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4786 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004787 RTC_LOG(LS_INFO)
4788 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004789 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004790 return false;
4791 }
4792 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004793 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004794 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004795 return false;
4796 }
4797
Zhi Huange830e682018-03-30 10:48:35 -07004798 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4799 if (dtls_role) {
4800 *role = *dtls_role;
4801 return true;
4802 }
4803 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004804}
4805
4806bool PeerConnection::GetSslRole(const std::string& content_name,
4807 rtc::SSLRole* role) {
4808 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004809 RTC_LOG(LS_INFO)
4810 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004811 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004812 return false;
4813 }
4814
Zhi Huange830e682018-03-30 10:48:35 -07004815 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4816 if (dtls_role) {
4817 *role = *dtls_role;
4818 return true;
4819 }
4820 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004821}
4822
Steve Antonf8470812017-12-04 10:46:21 -08004823void PeerConnection::SetSessionError(SessionError error,
4824 const std::string& error_desc) {
4825 RTC_DCHECK_RUN_ON(signaling_thread());
4826 if (error != session_error_) {
4827 session_error_ = error;
4828 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004829 }
4830}
4831
Zhi Huange830e682018-03-30 10:48:35 -07004832RTCError PeerConnection::UpdateSessionState(
4833 SdpType type,
4834 cricket::ContentSource source,
4835 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004836 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004837
4838 // If there's already a pending error then no state transition should happen.
4839 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004840 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004841
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004842 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004843 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004844 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004845 }
4846
4847 // Update the signaling state according to the specified state machine (see
4848 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004849 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004850 ChangeSignalingState(source == cricket::CS_LOCAL
4851 ? PeerConnectionInterface::kHaveLocalOffer
4852 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004853 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004854 ChangeSignalingState(source == cricket::CS_LOCAL
4855 ? PeerConnectionInterface::kHaveLocalPrAnswer
4856 : PeerConnectionInterface::kHaveRemotePrAnswer);
4857 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004858 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004859 ChangeSignalingState(PeerConnectionInterface::kStable);
4860 }
4861
4862 // Update internal objects according to the session description's media
4863 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004864 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004865 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004866 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004867 }
4868
Steve Anton8a006912017-12-04 15:25:56 -08004869 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004870}
4871
Steve Anton8a006912017-12-04 15:25:56 -08004872RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004873 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004874 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004875 const SessionDescriptionInterface* sdesc =
4876 (source == cricket::CS_LOCAL ? local_description()
4877 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004878 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004879
4880 // Push down the new SDP media section for each audio/video transceiver.
4881 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004882 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004883 FindMediaSectionForTransceiver(transceiver, sdesc);
4884 cricket::BaseChannel* channel = transceiver->internal()->channel();
4885 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004886 continue;
4887 }
4888 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004889 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004890 if (!content_desc) {
4891 continue;
4892 }
4893 std::string error;
4894 bool success =
4895 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004896 ? channel->SetLocalContent(content_desc, type, &error)
4897 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004898 if (!success) {
4899 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4900 }
4901 }
4902
4903 // If using the RtpDataChannel, push down the new SDP section for it too.
4904 if (rtp_data_channel_) {
4905 const ContentInfo* data_content =
4906 cricket::GetFirstDataContent(sdesc->description());
4907 if (data_content && !data_content->rejected) {
4908 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004909 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004910 if (data_desc) {
4911 std::string error;
4912 bool success =
4913 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004914 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4915 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004916 &error);
4917 if (!success) {
4918 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4919 std::move(error));
4920 }
Steve Anton75737c02017-11-06 10:37:17 -08004921 }
4922 }
4923 }
Steve Antoned10bd92017-12-05 10:52:59 -08004924
Steve Anton75737c02017-11-06 10:37:17 -08004925 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4926 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4927 if (sctp_transport_ && local_description() && remote_description() &&
4928 cricket::GetFirstDataContent(local_description()->description()) &&
4929 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004930 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004931 RTC_FROM_HERE,
4932 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004933 if (!success) {
4934 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4935 "Failed to push down SCTP parameters.");
4936 }
Steve Anton75737c02017-11-06 10:37:17 -08004937 }
Steve Antoned10bd92017-12-05 10:52:59 -08004938
Steve Anton8a006912017-12-04 15:25:56 -08004939 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004940}
4941
4942bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4943 RTC_DCHECK(network_thread()->IsCurrent());
4944 RTC_DCHECK(local_description());
4945 RTC_DCHECK(remote_description());
4946 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4947 // When we support "max-message-size", that would also be pushed down here.
4948 return sctp_transport_->Start(
4949 GetSctpPort(local_description()->description()),
4950 GetSctpPort(remote_description()->description()));
4951}
4952
Steve Anton8a006912017-12-04 15:25:56 -08004953RTCError PeerConnection::PushdownTransportDescription(
4954 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004955 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004956 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004957
Zhi Huange830e682018-03-30 10:48:35 -07004958 if (source == cricket::CS_LOCAL) {
4959 const SessionDescriptionInterface* sdesc = local_description();
4960 RTC_DCHECK(sdesc);
4961 return transport_controller_->SetLocalDescription(type,
4962 sdesc->description());
4963 } else {
4964 const SessionDescriptionInterface* sdesc = remote_description();
4965 RTC_DCHECK(sdesc);
4966 return transport_controller_->SetRemoteDescription(type,
4967 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004968 }
Steve Anton75737c02017-11-06 10:37:17 -08004969}
4970
4971bool PeerConnection::GetTransportDescription(
4972 const SessionDescription* description,
4973 const std::string& content_name,
4974 cricket::TransportDescription* tdesc) {
4975 if (!description || !tdesc) {
4976 return false;
4977 }
4978 const TransportInfo* transport_info =
4979 description->GetTransportInfoByName(content_name);
4980 if (!transport_info) {
4981 return false;
4982 }
4983 *tdesc = transport_info->description;
4984 return true;
4985}
4986
Steve Anton75737c02017-11-06 10:37:17 -08004987cricket::IceConfig PeerConnection::ParseIceConfig(
4988 const PeerConnectionInterface::RTCConfiguration& config) const {
4989 cricket::ContinualGatheringPolicy gathering_policy;
4990 // TODO(honghaiz): Add the third continual gathering policy in
4991 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4992 switch (config.continual_gathering_policy) {
4993 case PeerConnectionInterface::GATHER_ONCE:
4994 gathering_policy = cricket::GATHER_ONCE;
4995 break;
4996 case PeerConnectionInterface::GATHER_CONTINUALLY:
4997 gathering_policy = cricket::GATHER_CONTINUALLY;
4998 break;
4999 default:
5000 RTC_NOTREACHED();
5001 gathering_policy = cricket::GATHER_ONCE;
5002 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005003
Steve Anton75737c02017-11-06 10:37:17 -08005004 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005005 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5006 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005007 ice_config.prioritize_most_likely_candidate_pairs =
5008 config.prioritize_most_likely_ice_candidate_pairs;
5009 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005010 RTCConfigurationToIceConfigOptionalInt(
5011 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005012 ice_config.continual_gathering_policy = gathering_policy;
5013 ice_config.presume_writable_when_fully_relayed =
5014 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005015 ice_config.ice_check_interval_strong_connectivity =
5016 config.ice_check_interval_strong_connectivity;
5017 ice_config.ice_check_interval_weak_connectivity =
5018 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005019 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005020 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005021 ice_config.regather_all_networks_interval_range =
5022 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005023 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005024 return ice_config;
5025}
5026
Steve Anton75737c02017-11-06 10:37:17 -08005027bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5028 std::string* track_id) {
5029 if (!local_description()) {
5030 return false;
5031 }
5032 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5033 track_id);
5034}
5035
5036bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5037 std::string* track_id) {
5038 if (!remote_description()) {
5039 return false;
5040 }
5041 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5042 track_id);
5043}
5044
5045bool PeerConnection::SendData(const cricket::SendDataParams& params,
5046 const rtc::CopyOnWriteBuffer& payload,
5047 cricket::SendDataResult* result) {
5048 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005049 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005050 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005051 return false;
5052 }
5053 return rtp_data_channel_
5054 ? rtp_data_channel_->SendData(params, payload, result)
5055 : network_thread()->Invoke<bool>(
5056 RTC_FROM_HERE,
5057 Bind(&cricket::SctpTransportInternal::SendData,
5058 sctp_transport_.get(), params, payload, result));
5059}
5060
5061bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5062 if (!rtp_data_channel_ && !sctp_transport_) {
5063 // Don't log an error here, because DataChannels are expected to call
5064 // ConnectDataChannel in this state. It's the only way to initially tell
5065 // whether or not the underlying transport is ready.
5066 return false;
5067 }
5068 if (rtp_data_channel_) {
5069 rtp_data_channel_->SignalReadyToSendData.connect(
5070 webrtc_data_channel, &DataChannel::OnChannelReady);
5071 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5072 &DataChannel::OnDataReceived);
5073 } else {
5074 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5075 &DataChannel::OnChannelReady);
5076 SignalSctpDataReceived.connect(webrtc_data_channel,
5077 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005078 SignalSctpClosingProcedureStartedRemotely.connect(
5079 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5080 SignalSctpClosingProcedureComplete.connect(
5081 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005082 }
5083 return true;
5084}
5085
5086void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5087 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005088 RTC_LOG(LS_ERROR)
5089 << "DisconnectDataChannel called when rtp_data_channel_ and "
5090 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005091 return;
5092 }
5093 if (rtp_data_channel_) {
5094 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5095 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5096 } else {
5097 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5098 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005099 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5100 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005101 }
5102}
5103
5104void PeerConnection::AddSctpDataStream(int sid) {
5105 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005106 RTC_LOG(LS_ERROR)
5107 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005108 return;
5109 }
5110 network_thread()->Invoke<void>(
5111 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5112 sctp_transport_.get(), sid));
5113}
5114
5115void PeerConnection::RemoveSctpDataStream(int sid) {
5116 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005117 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005118 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005119 return;
5120 }
5121 network_thread()->Invoke<void>(
5122 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5123 sctp_transport_.get(), sid));
5124}
5125
5126bool PeerConnection::ReadyToSendData() const {
5127 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5128 sctp_ready_to_send_data_;
5129}
5130
Zhi Huange830e682018-03-30 10:48:35 -07005131rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5132 if (sctp_mid_ && transport_controller_) {
5133 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5134 if (dtls_transport) {
5135 return dtls_transport->transport_name();
5136 }
5137 return rtc::Optional<std::string>();
5138 }
5139 return rtc::Optional<std::string>();
5140}
5141
Qingsi Wang72a43a12018-02-20 16:03:18 -08005142cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5143 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005144 network_thread()->Invoke<void>(
5145 RTC_FROM_HERE,
5146 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5147 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005148 return candidate_states_list;
5149}
5150
Steve Anton5dfde182018-02-06 10:34:40 -08005151std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5152 const {
5153 std::map<std::string, std::string> transport_names_by_mid;
5154 for (auto transceiver : transceivers_) {
5155 cricket::BaseChannel* channel = transceiver->internal()->channel();
5156 if (channel) {
5157 transport_names_by_mid[channel->content_name()] =
5158 channel->transport_name();
5159 }
Steve Anton75737c02017-11-06 10:37:17 -08005160 }
Steve Anton5dfde182018-02-06 10:34:40 -08005161 if (rtp_data_channel_) {
5162 transport_names_by_mid[rtp_data_channel_->content_name()] =
5163 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005164 }
5165 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005166 rtc::Optional<std::string> transport_name = sctp_transport_name();
5167 RTC_DCHECK(transport_name);
5168 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005169 }
Steve Anton5dfde182018-02-06 10:34:40 -08005170 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005171}
5172
Steve Anton5dfde182018-02-06 10:34:40 -08005173std::map<std::string, cricket::TransportStats>
5174PeerConnection::GetTransportStatsByNames(
5175 const std::set<std::string>& transport_names) {
5176 if (!network_thread()->IsCurrent()) {
5177 return network_thread()
5178 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5179 RTC_FROM_HERE,
5180 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005181 }
Steve Anton5dfde182018-02-06 10:34:40 -08005182 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5183 for (const std::string& transport_name : transport_names) {
5184 cricket::TransportStats transport_stats;
5185 bool success =
5186 transport_controller_->GetStats(transport_name, &transport_stats);
5187 if (success) {
5188 transport_stats_by_name[transport_name] = std::move(transport_stats);
5189 } else {
5190 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5191 << transport_name;
5192 }
5193 }
5194 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005195}
5196
5197bool PeerConnection::GetLocalCertificate(
5198 const std::string& transport_name,
5199 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005200 if (!certificate) {
5201 return false;
5202 }
5203 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5204 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005205}
5206
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005207std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005208 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005209 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005210}
5211
5212cricket::DataChannelType PeerConnection::data_channel_type() const {
5213 return data_channel_type_;
5214}
5215
5216bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5217 return pending_ice_restarts_.find(content_name) !=
5218 pending_ice_restarts_.end();
5219}
5220
Steve Anton75737c02017-11-06 10:37:17 -08005221bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5222 return transport_controller_->NeedsIceRestart(content_name);
5223}
5224
5225void PeerConnection::OnCertificateReady(
5226 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5227 transport_controller_->SetLocalCertificate(certificate);
5228}
5229
5230void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005231 SetSessionError(SessionError::kTransport,
5232 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005233}
5234
5235void PeerConnection::OnTransportControllerConnectionState(
5236 cricket::IceConnectionState state) {
5237 switch (state) {
5238 case cricket::kIceConnectionConnecting:
5239 // If the current state is Connected or Completed, then there were
5240 // writable channels but now there are not, so the next state must
5241 // be Disconnected.
5242 // kIceConnectionConnecting is currently used as the default,
5243 // un-connected state by the TransportController, so its only use is
5244 // detecting disconnections.
5245 if (ice_connection_state_ ==
5246 PeerConnectionInterface::kIceConnectionConnected ||
5247 ice_connection_state_ ==
5248 PeerConnectionInterface::kIceConnectionCompleted) {
5249 SetIceConnectionState(
5250 PeerConnectionInterface::kIceConnectionDisconnected);
5251 }
5252 break;
5253 case cricket::kIceConnectionFailed:
5254 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5255 break;
5256 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005257 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005258 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005259 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005260 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005261 break;
5262 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005263 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005264 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005265 if (ice_connection_state_ !=
5266 PeerConnectionInterface::kIceConnectionConnected) {
5267 // If jumping directly from "checking" to "connected",
5268 // signal "connected" first.
5269 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5270 }
5271 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005272 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005273 if (metrics_observer()) {
5274 ReportTransportStats();
5275 }
5276 break;
5277 default:
5278 RTC_NOTREACHED();
5279 }
5280}
5281
5282void PeerConnection::OnTransportControllerCandidatesGathered(
5283 const std::string& transport_name,
5284 const cricket::Candidates& candidates) {
5285 RTC_DCHECK(signaling_thread()->IsCurrent());
5286 int sdp_mline_index;
5287 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005288 RTC_LOG(LS_ERROR)
5289 << "OnTransportControllerCandidatesGathered: content name "
5290 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005291 return;
5292 }
5293
5294 for (cricket::Candidates::const_iterator citer = candidates.begin();
5295 citer != candidates.end(); ++citer) {
5296 // Use transport_name as the candidate media id.
5297 std::unique_ptr<JsepIceCandidate> candidate(
5298 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5299 if (local_description()) {
5300 mutable_local_description()->AddCandidate(candidate.get());
5301 }
5302 OnIceCandidate(std::move(candidate));
5303 }
5304}
5305
5306void PeerConnection::OnTransportControllerCandidatesRemoved(
5307 const std::vector<cricket::Candidate>& candidates) {
5308 RTC_DCHECK(signaling_thread()->IsCurrent());
5309 // Sanity check.
5310 for (const cricket::Candidate& candidate : candidates) {
5311 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005312 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005313 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005314 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005315 return;
5316 }
5317 }
5318
5319 if (local_description()) {
5320 mutable_local_description()->RemoveCandidates(candidates);
5321 }
5322 OnIceCandidatesRemoved(candidates);
5323}
5324
5325void PeerConnection::OnTransportControllerDtlsHandshakeError(
5326 rtc::SSLHandshakeError error) {
5327 if (metrics_observer()) {
5328 metrics_observer()->IncrementEnumCounter(
5329 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5330 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5331 }
5332}
5333
Steve Antoned10bd92017-12-05 10:52:59 -08005334void PeerConnection::EnableSending() {
5335 for (auto transceiver : transceivers_) {
5336 cricket::BaseChannel* channel = transceiver->internal()->channel();
5337 if (channel && !channel->enabled()) {
5338 channel->Enable(true);
5339 }
Steve Anton75737c02017-11-06 10:37:17 -08005340 }
5341
Steve Anton4171afb2017-11-20 10:20:22 -08005342 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005343 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005344 }
Steve Anton75737c02017-11-06 10:37:17 -08005345}
5346
5347// Returns the media index for a local ice candidate given the content name.
5348bool PeerConnection::GetLocalCandidateMediaIndex(
5349 const std::string& content_name,
5350 int* sdp_mline_index) {
5351 if (!local_description() || !sdp_mline_index) {
5352 return false;
5353 }
5354
5355 bool content_found = false;
5356 const ContentInfos& contents = local_description()->description()->contents();
5357 for (size_t index = 0; index < contents.size(); ++index) {
5358 if (contents[index].name == content_name) {
5359 *sdp_mline_index = static_cast<int>(index);
5360 content_found = true;
5361 break;
5362 }
5363 }
5364 return content_found;
5365}
5366
5367bool PeerConnection::UseCandidatesInSessionDescription(
5368 const SessionDescriptionInterface* remote_desc) {
5369 if (!remote_desc) {
5370 return true;
5371 }
5372 bool ret = true;
5373
5374 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5375 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5376 for (size_t n = 0; n < candidates->count(); ++n) {
5377 const IceCandidateInterface* candidate = candidates->at(n);
5378 bool valid = false;
5379 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5380 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005381 RTC_LOG(LS_INFO)
5382 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005383 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005384 }
5385 continue;
5386 }
5387 ret = UseCandidate(candidate);
5388 if (!ret) {
5389 break;
5390 }
5391 }
5392 }
5393 return ret;
5394}
5395
5396bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5397 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5398 size_t remote_content_size =
5399 remote_description()->description()->contents().size();
5400 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005401 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005402 return false;
5403 }
5404
5405 cricket::ContentInfo content =
5406 remote_description()->description()->contents()[mediacontent_index];
5407 std::vector<cricket::Candidate> candidates;
5408 candidates.push_back(candidate->candidate());
5409 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005410 RTCError error =
5411 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005412 if (error.ok()) {
5413 // Candidates successfully submitted for checking.
5414 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5415 ice_connection_state_ ==
5416 PeerConnectionInterface::kIceConnectionDisconnected) {
5417 // If state is New, then the session has just gotten its first remote ICE
5418 // candidates, so go to Checking.
5419 // If state is Disconnected, the session is re-using old candidates or
5420 // receiving additional ones, so go to Checking.
5421 // If state is Connected, stay Connected.
5422 // TODO(bemasc): If state is Connected, and the new candidates are for a
5423 // newly added transport, then the state actually _should_ move to
5424 // checking. Add a way to distinguish that case.
5425 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5426 }
5427 // TODO(bemasc): If state is Completed, go back to Connected.
5428 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005429 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005430 }
5431 return true;
5432}
5433
5434void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005435 // Destroy video channel first since it may have a pointer to the
5436 // voice channel.
5437 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005438 if (!video_info || video_info->rejected) {
5439 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005440 }
5441
Steve Anton6fec8802017-12-04 10:37:29 -08005442 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5443 if (!audio_info || audio_info->rejected) {
5444 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005445 }
5446
5447 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5448 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005449 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005450 }
5451}
5452
Steve Antondcc3c022017-12-22 16:02:54 -08005453RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5454 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005455 const cricket::ContentGroup* bundle_group = nullptr;
5456 if (configuration_.bundle_policy ==
5457 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005458 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005459 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005460 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5461 "max-bundle configured but session description "
5462 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005463 }
5464 }
Steve Antondcc3c022017-12-22 16:02:54 -08005465 return std::move(bundle_group);
5466}
5467
5468RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005469 // Creating the media channels. Transports should already have been created
5470 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005471 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005472 if (voice && !voice->rejected &&
5473 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005474 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005475 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005476 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5477 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005478 }
5479 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5480 }
5481
Steve Antondcc3c022017-12-22 16:02:54 -08005482 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005483 if (video && !video->rejected &&
5484 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005485 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005486 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005487 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5488 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005489 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005490 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005491 }
5492
Steve Antondcc3c022017-12-22 16:02:54 -08005493 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005494 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5495 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005496 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005497 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5498 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005499 }
5500 }
5501
Steve Anton8a006912017-12-04 15:25:56 -08005502 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005503}
5504
Steve Anton4171afb2017-11-20 10:20:22 -08005505// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005506cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005507 const std::string& mid) {
5508 RtpTransportInternal* rtp_transport =
5509 transport_controller_->GetRtpTransport(mid);
5510 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005511 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005512 call_.get(), configuration_.media_config, rtp_transport,
5513 signaling_thread(), mid, SrtpRequired(),
5514 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005515 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005516 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005517 }
Steve Anton75737c02017-11-06 10:37:17 -08005518 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5519 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005520 voice_channel->SignalSentPacket.connect(this,
5521 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005522 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005523 if (uma_observer_) {
5524 voice_channel->SetMetricsObserver(uma_observer_);
5525 }
Steve Anton4171afb2017-11-20 10:20:22 -08005526
Steve Antoneda6ccd2017-12-04 10:21:55 -08005527 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005528}
5529
Steve Anton4171afb2017-11-20 10:20:22 -08005530// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005531cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005532 const std::string& mid) {
5533 RtpTransportInternal* rtp_transport =
5534 transport_controller_->GetRtpTransport(mid);
5535 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005536 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005537 call_.get(), configuration_.media_config, rtp_transport,
5538 signaling_thread(), mid, SrtpRequired(),
5539 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005540 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005541 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005542 }
Steve Anton75737c02017-11-06 10:37:17 -08005543 video_channel->SignalDtlsSrtpSetupFailure.connect(
5544 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005545 video_channel->SignalSentPacket.connect(this,
5546 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005547 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005548 if (uma_observer_) {
5549 video_channel->SetMetricsObserver(uma_observer_);
5550 }
Steve Anton4171afb2017-11-20 10:20:22 -08005551
Steve Antoneda6ccd2017-12-04 10:21:55 -08005552 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005553}
5554
Zhi Huange830e682018-03-30 10:48:35 -07005555bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005556 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5557 if (sctp) {
5558 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005559 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005560 << "Trying to create SCTP transport, but didn't compile with "
5561 "SCTP support (HAVE_SCTP)";
5562 return false;
5563 }
5564 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005565 RTC_FROM_HERE,
5566 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005567 return false;
5568 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005569 for (const auto& channel : sctp_data_channels_) {
5570 channel->OnTransportChannelCreated();
5571 }
Steve Anton75737c02017-11-06 10:37:17 -08005572 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005573 RtpTransportInternal* rtp_transport =
5574 transport_controller_->GetRtpTransport(mid);
5575 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005576 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005577 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5578 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005579 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005580 return false;
5581 }
Steve Anton75737c02017-11-06 10:37:17 -08005582 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5583 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5584 rtp_data_channel_->SignalSentPacket.connect(
5585 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005586 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005587 if (uma_observer_) {
5588 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5589 }
Steve Anton75737c02017-11-06 10:37:17 -08005590 }
5591
Steve Anton75737c02017-11-06 10:37:17 -08005592 return true;
5593}
5594
5595Call::Stats PeerConnection::GetCallStats() {
5596 if (!worker_thread()->IsCurrent()) {
5597 return worker_thread()->Invoke<Call::Stats>(
5598 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5599 }
5600 if (call_) {
5601 return call_->GetStats();
5602 } else {
5603 return Call::Stats();
5604 }
5605}
5606
Zhi Huange830e682018-03-30 10:48:35 -07005607bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005608 RTC_DCHECK(network_thread()->IsCurrent());
5609 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005610 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005611 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005612 RTC_DCHECK(dtls_transport);
5613 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005614 RTC_DCHECK(sctp_transport_);
5615 sctp_invoker_.reset(new rtc::AsyncInvoker());
5616 sctp_transport_->SignalReadyToSendData.connect(
5617 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5618 sctp_transport_->SignalDataReceived.connect(
5619 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005620 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5621 // another thread. Would be nice if there was a helper class similar to
5622 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5623 // code.
5624 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5625 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5626 sctp_transport_->SignalClosingProcedureComplete.connect(
5627 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005628 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005629 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005630 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005631}
5632
5633void PeerConnection::DestroySctpTransport_n() {
5634 RTC_DCHECK(network_thread()->IsCurrent());
5635 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005636 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005637 sctp_invoker_.reset(nullptr);
5638 sctp_ready_to_send_data_ = false;
5639}
5640
5641void PeerConnection::OnSctpTransportReadyToSendData_n() {
5642 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5643 RTC_DCHECK(network_thread()->IsCurrent());
5644 // Note: Cannot use rtc::Bind here because it will grab a reference to
5645 // PeerConnection and potentially cause PeerConnection to live longer than
5646 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5647 // be destroyed before PeerConnection is destroyed, and at that point all
5648 // pending tasks will be cleared.
5649 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5650 OnSctpTransportReadyToSendData_s(true);
5651 });
5652}
5653
5654void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5655 RTC_DCHECK(signaling_thread()->IsCurrent());
5656 sctp_ready_to_send_data_ = ready;
5657 SignalSctpReadyToSendData(ready);
5658}
5659
5660void PeerConnection::OnSctpTransportDataReceived_n(
5661 const cricket::ReceiveDataParams& params,
5662 const rtc::CopyOnWriteBuffer& payload) {
5663 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5664 RTC_DCHECK(network_thread()->IsCurrent());
5665 // Note: Cannot use rtc::Bind here because it will grab a reference to
5666 // PeerConnection and potentially cause PeerConnection to live longer than
5667 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5668 // be destroyed before PeerConnection is destroyed, and at that point all
5669 // pending tasks will be cleared.
5670 sctp_invoker_->AsyncInvoke<void>(
5671 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5672 OnSctpTransportDataReceived_s(params, payload);
5673 });
5674}
5675
5676void PeerConnection::OnSctpTransportDataReceived_s(
5677 const cricket::ReceiveDataParams& params,
5678 const rtc::CopyOnWriteBuffer& payload) {
5679 RTC_DCHECK(signaling_thread()->IsCurrent());
5680 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5681 // Received OPEN message; parse and signal that a new data channel should
5682 // be created.
5683 std::string label;
5684 InternalDataChannelInit config;
5685 config.id = params.ssrc;
5686 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005687 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5688 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005689 return;
5690 }
5691 config.open_handshake_role = InternalDataChannelInit::kAcker;
5692 OnDataChannelOpenMessage(label, config);
5693 } else {
5694 // Otherwise just forward the signal.
5695 SignalSctpDataReceived(params, payload);
5696 }
5697}
5698
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005699void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005700 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5701 RTC_DCHECK(network_thread()->IsCurrent());
5702 sctp_invoker_->AsyncInvoke<void>(
5703 RTC_FROM_HERE, signaling_thread(),
5704 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005705 &SignalSctpClosingProcedureStartedRemotely, sid));
5706}
5707
5708void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5709 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5710 RTC_DCHECK(network_thread()->IsCurrent());
5711 sctp_invoker_->AsyncInvoke<void>(
5712 RTC_FROM_HERE, signaling_thread(),
5713 rtc::Bind(&sigslot::signal1<int>::operator(),
5714 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005715}
5716
5717// Returns false if bundle is enabled and rtcp_mux is disabled.
5718bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5719 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5720 if (!bundle_enabled)
5721 return true;
5722
5723 const cricket::ContentGroup* bundle_group =
5724 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5725 RTC_DCHECK(bundle_group != NULL);
5726
5727 const cricket::ContentInfos& contents = desc->contents();
5728 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5729 citer != contents.end(); ++citer) {
5730 const cricket::ContentInfo* content = (&*citer);
5731 RTC_DCHECK(content != NULL);
5732 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005733 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005734 if (!HasRtcpMuxEnabled(content))
5735 return false;
5736 }
5737 }
5738 // RTCP-MUX is enabled in all the contents.
5739 return true;
5740}
5741
5742bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005743 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005744}
5745
Steve Anton8a006912017-12-04 15:25:56 -08005746RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005747 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005748 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005749 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005750 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005751 }
5752
5753 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005754 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005755 }
5756
Steve Anton3828c062017-12-06 10:34:51 -08005757 SdpType type = sdesc->GetType();
5758 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5759 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005760 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005761 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005762 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005763 }
5764
5765 // Verify crypto settings.
5766 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005767 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5768 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005769 RTCError crypto_error =
5770 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005771 if (!crypto_error.ok()) {
5772 return crypto_error;
5773 }
Steve Anton75737c02017-11-06 10:37:17 -08005774 }
5775
5776 // Verify ice-ufrag and ice-pwd.
5777 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005778 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5779 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005780 }
5781
5782 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005783 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5784 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005785 }
5786
5787 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5788 // m-lines that do not rtcp-mux enabled.
5789
5790 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005791 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005792 // With an answer we want to compare the new answer session description with
5793 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005794 const cricket::SessionDescription* offer_desc =
5795 (source == cricket::CS_LOCAL) ? remote_description()->description()
5796 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005797 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5798 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5799 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005800 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5801 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
5803 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005804 // The re-offers should respect the order of m= sections in current
5805 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005806 // With a re-offer, either the current local or current remote descriptions
5807 // could be the most up to date, so we would like to check against both of
5808 // them if they exist. It could be the case that one of them has a 0 port
5809 // for a media section, but the other does not. This is important to check
5810 // against in the case that we are recycling an m= section.
5811 const cricket::SessionDescription* current_desc = nullptr;
5812 const cricket::SessionDescription* secondary_current_desc = nullptr;
5813 if (local_description()) {
5814 current_desc = local_description()->description();
5815 if (remote_description()) {
5816 secondary_current_desc = remote_description()->description();
5817 }
5818 } else if (remote_description()) {
5819 current_desc = remote_description()->description();
5820 }
Steve Anton75737c02017-11-06 10:37:17 -08005821 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005822 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5823 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005824 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5825 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005826 }
5827 }
5828
Steve Antonba42e992018-04-09 14:10:01 -07005829 if (IsUnifiedPlan()) {
5830 // Ensure that each audio and video media section has at most one
5831 // "StreamParams". This will return an error if receiving a session
5832 // description from a "Plan B" endpoint which adds multiple tracks of the
5833 // same type. With Unified Plan, there can only be at most one track per
5834 // media section.
5835 for (const ContentInfo& content : sdesc->description()->contents()) {
5836 const MediaContentDescription& desc = *content.description;
5837 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5838 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5839 desc.streams().size() > 1u) {
5840 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5841 "Media section has more than one track specified "
5842 "with a=ssrc lines which is not supported with "
5843 "Unified Plan.");
5844 }
5845 }
5846 }
5847
Steve Anton8a006912017-12-04 15:25:56 -08005848 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005849}
5850
Steve Anton3828c062017-12-06 10:34:51 -08005851bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005852 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005853 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005854 return (state == PeerConnectionInterface::kStable) ||
5855 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005856 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005857 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005858 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5859 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5860 }
5861}
5862
Steve Anton3828c062017-12-06 10:34:51 -08005863bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005864 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005865 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005866 return (state == PeerConnectionInterface::kStable) ||
5867 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005868 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005869 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005870 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5871 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5872 }
5873}
5874
Steve Antonf8470812017-12-04 10:46:21 -08005875const char* PeerConnection::SessionErrorToString(SessionError error) const {
5876 switch (error) {
5877 case SessionError::kNone:
5878 return "ERROR_NONE";
5879 case SessionError::kContent:
5880 return "ERROR_CONTENT";
5881 case SessionError::kTransport:
5882 return "ERROR_TRANSPORT";
5883 }
5884 RTC_NOTREACHED();
5885 return "";
5886}
5887
Steve Anton75737c02017-11-06 10:37:17 -08005888std::string PeerConnection::GetSessionErrorMsg() {
5889 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005890 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5891 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005892 return desc.str();
5893}
5894
Steve Anton8e20f172018-03-06 10:55:04 -08005895void PeerConnection::ReportSdpFormatReceived(
5896 const SessionDescriptionInterface& remote_offer) {
5897 if (!uma_observer_) {
5898 return;
5899 }
5900 int num_audio_mlines = 0;
5901 int num_video_mlines = 0;
5902 int num_audio_tracks = 0;
5903 int num_video_tracks = 0;
5904 for (const ContentInfo& content : remote_offer.description()->contents()) {
5905 cricket::MediaType media_type = content.media_description()->type();
5906 int num_tracks = std::max(
5907 1, static_cast<int>(content.media_description()->streams().size()));
5908 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5909 num_audio_mlines += 1;
5910 num_audio_tracks += num_tracks;
5911 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5912 num_video_mlines += 1;
5913 num_video_tracks += num_tracks;
5914 }
5915 }
5916 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5917 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5918 format = kSdpFormatReceivedComplexUnifiedPlan;
5919 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5920 format = kSdpFormatReceivedComplexPlanB;
5921 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5922 format = kSdpFormatReceivedSimple;
5923 }
5924 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5925 kSdpFormatReceivedMax);
5926}
5927
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005928void PeerConnection::NoteUsageEvent(UsageEvent event) {
5929 RTC_DCHECK_RUN_ON(signaling_thread());
5930 usage_event_accumulator_ |= static_cast<int>(event);
5931}
5932
5933void PeerConnection::ReportUsagePattern() const {
5934 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5935 if (uma_observer_) {
5936 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5937 usage_event_accumulator_);
5938 }
5939}
5940
Steve Anton0ffaaa22018-02-23 10:31:30 -08005941void PeerConnection::ReportNegotiatedSdpSemantics(
5942 const SessionDescriptionInterface& answer) {
5943 if (!uma_observer_) {
5944 return;
5945 }
5946 switch (answer.description()->msid_signaling()) {
5947 case 0:
5948 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5949 kSdpSemanticNegotiatedNone,
5950 kSdpSemanticNegotiatedMax);
5951 break;
5952 case cricket::kMsidSignalingMediaSection:
5953 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5954 kSdpSemanticNegotiatedUnifiedPlan,
5955 kSdpSemanticNegotiatedMax);
5956 break;
5957 case cricket::kMsidSignalingSsrcAttribute:
5958 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5959 kSdpSemanticNegotiatedPlanB,
5960 kSdpSemanticNegotiatedMax);
5961 break;
5962 case cricket::kMsidSignalingMediaSection |
5963 cricket::kMsidSignalingSsrcAttribute:
5964 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5965 kSdpSemanticNegotiatedMixed,
5966 kSdpSemanticNegotiatedMax);
5967 break;
5968 default:
5969 RTC_NOTREACHED();
5970 }
5971}
5972
Steve Anton75737c02017-11-06 10:37:17 -08005973// We need to check the local/remote description for the Transport instead of
5974// the session, because a new Transport added during renegotiation may have
5975// them unset while the session has them set from the previous negotiation.
5976// Not doing so may trigger the auto generation of transport description and
5977// mess up DTLS identity information, ICE credential, etc.
5978bool PeerConnection::ReadyToUseRemoteCandidate(
5979 const IceCandidateInterface* candidate,
5980 const SessionDescriptionInterface* remote_desc,
5981 bool* valid) {
5982 *valid = true;
5983
5984 const SessionDescriptionInterface* current_remote_desc =
5985 remote_desc ? remote_desc : remote_description();
5986
5987 if (!current_remote_desc) {
5988 return false;
5989 }
5990
5991 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5992 size_t remote_content_size =
5993 current_remote_desc->description()->contents().size();
5994 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005995 RTC_LOG(LS_ERROR)
5996 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5997 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005998
5999 *valid = false;
6000 return false;
6001 }
6002
6003 cricket::ContentInfo content =
6004 current_remote_desc->description()->contents()[mediacontent_index];
6005
6006 const std::string transport_name = GetTransportName(content.name);
6007 if (transport_name.empty()) {
6008 return false;
6009 }
Zhi Huange830e682018-03-30 10:48:35 -07006010 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006011}
6012
6013bool PeerConnection::SrtpRequired() const {
6014 return dtls_enabled_ ||
6015 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6016}
6017
6018void PeerConnection::OnTransportControllerGatheringState(
6019 cricket::IceGatheringState state) {
6020 RTC_DCHECK(signaling_thread()->IsCurrent());
6021 if (state == cricket::kIceGatheringGathering) {
6022 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6023 } else if (state == cricket::kIceGatheringComplete) {
6024 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6025 }
6026}
6027
6028void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006029 std::map<std::string, std::set<cricket::MediaType>>
6030 media_types_by_transport_name;
6031 for (auto transceiver : transceivers_) {
6032 if (transceiver->internal()->channel()) {
6033 const std::string& transport_name =
6034 transceiver->internal()->channel()->transport_name();
6035 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006036 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006037 }
Steve Anton75737c02017-11-06 10:37:17 -08006038 }
6039 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006040 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6041 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006042 }
Zhi Huange830e682018-03-30 10:48:35 -07006043
6044 rtc::Optional<std::string> transport_name = sctp_transport_name();
6045 if (transport_name) {
6046 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006047 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006048 }
Zhi Huange830e682018-03-30 10:48:35 -07006049
Steve Antonc7b964c2018-02-01 14:39:45 -08006050 for (const auto& entry : media_types_by_transport_name) {
6051 const std::string& transport_name = entry.first;
6052 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006053 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006054 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006055 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006056 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006057 }
6058 }
6059}
6060// Walk through the ConnectionInfos to gather best connection usage
6061// for IPv4 and IPv6.
6062void PeerConnection::ReportBestConnectionState(
6063 const cricket::TransportStats& stats) {
6064 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006065 for (const cricket::TransportChannelStats& channel_stats :
6066 stats.channel_stats) {
6067 for (const cricket::ConnectionInfo& connection_info :
6068 channel_stats.connection_infos) {
6069 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006070 continue;
6071 }
6072
6073 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006074 const cricket::Candidate& local = connection_info.local_candidate;
6075 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006076
6077 // Increment the counter for IceCandidatePairType.
6078 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6079 (local.type() == RELAY_PORT_TYPE &&
6080 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6081 type = kEnumCounterIceCandidatePairTypeTcp;
6082 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6083 type = kEnumCounterIceCandidatePairTypeUdp;
6084 } else {
6085 RTC_CHECK(0);
6086 }
6087 metrics_observer()->IncrementEnumCounter(
6088 type, GetIceCandidatePairCounter(local, remote),
6089 kIceCandidatePairMax);
6090
6091 // Increment the counter for IP type.
6092 if (local.address().family() == AF_INET) {
6093 metrics_observer()->IncrementEnumCounter(
6094 kEnumCounterAddressFamily, kBestConnections_IPv4,
6095 kPeerConnectionAddressFamilyCounter_Max);
6096
6097 } else if (local.address().family() == AF_INET6) {
6098 metrics_observer()->IncrementEnumCounter(
6099 kEnumCounterAddressFamily, kBestConnections_IPv6,
6100 kPeerConnectionAddressFamilyCounter_Max);
6101 } else {
6102 RTC_CHECK(0);
6103 }
6104
6105 return;
6106 }
6107 }
6108}
6109
6110void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006111 const cricket::TransportStats& stats,
6112 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006113 RTC_DCHECK(metrics_observer());
6114 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6115 return;
6116 }
6117
6118 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6119 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6120 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6121 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6122 return;
6123 }
6124
Steve Antonc7b964c2018-02-01 14:39:45 -08006125 for (cricket::MediaType media_type : media_types) {
6126 PeerConnectionEnumCounterType srtp_counter_type;
6127 PeerConnectionEnumCounterType ssl_counter_type;
6128 switch (media_type) {
6129 case cricket::MEDIA_TYPE_AUDIO:
6130 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6131 ssl_counter_type = kEnumCounterAudioSslCipher;
6132 break;
6133 case cricket::MEDIA_TYPE_VIDEO:
6134 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6135 ssl_counter_type = kEnumCounterVideoSslCipher;
6136 break;
6137 case cricket::MEDIA_TYPE_DATA:
6138 srtp_counter_type = kEnumCounterDataSrtpCipher;
6139 ssl_counter_type = kEnumCounterDataSslCipher;
6140 break;
6141 default:
6142 RTC_NOTREACHED();
6143 continue;
6144 }
6145 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6146 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6147 srtp_crypto_suite);
6148 }
6149 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6150 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6151 ssl_cipher_suite);
6152 }
Steve Anton75737c02017-11-06 10:37:17 -08006153 }
6154}
6155
6156void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6157 RTC_DCHECK(worker_thread()->IsCurrent());
6158 RTC_DCHECK(call_);
6159 call_->OnSentPacket(sent_packet);
6160}
6161
6162const std::string PeerConnection::GetTransportName(
6163 const std::string& content_name) {
6164 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006165 if (channel) {
6166 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006167 }
Steve Anton6fec8802017-12-04 10:37:29 -08006168 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006169 RTC_DCHECK(sctp_mid_);
6170 if (content_name == *sctp_mid_) {
6171 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006172 }
6173 }
6174 // Return an empty string if failed to retrieve the transport name.
6175 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006176}
6177
Steve Anton6fec8802017-12-04 10:37:29 -08006178void PeerConnection::DestroyTransceiverChannel(
6179 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6180 transceiver) {
6181 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006182
Steve Anton6fec8802017-12-04 10:37:29 -08006183 cricket::BaseChannel* channel = transceiver->internal()->channel();
6184 if (channel) {
6185 transceiver->internal()->SetChannel(nullptr);
6186 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006187 }
6188}
6189
6190void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006191 if (rtp_data_channel_) {
6192 OnDataChannelDestroyed();
6193 DestroyBaseChannel(rtp_data_channel_);
6194 rtp_data_channel_ = nullptr;
6195 }
6196
6197 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6198 // grab a reference to this PeerConnection. If this is called from the
6199 // PeerConnection destructor, the RefCountedObject vtable will have already
6200 // been destroyed (since it is a subclass of PeerConnection) and using
6201 // rtc::Bind will cause "Pure virtual function called" error to appear.
6202
6203 if (sctp_transport_) {
6204 OnDataChannelDestroyed();
6205 network_thread()->Invoke<void>(RTC_FROM_HERE,
6206 [this] { DestroySctpTransport_n(); });
6207 }
6208}
6209
6210void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6211 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006212 switch (channel->media_type()) {
6213 case cricket::MEDIA_TYPE_AUDIO:
6214 channel_manager()->DestroyVoiceChannel(
6215 static_cast<cricket::VoiceChannel*>(channel));
6216 break;
6217 case cricket::MEDIA_TYPE_VIDEO:
6218 channel_manager()->DestroyVideoChannel(
6219 static_cast<cricket::VideoChannel*>(channel));
6220 break;
6221 case cricket::MEDIA_TYPE_DATA:
6222 channel_manager()->DestroyRtpDataChannel(
6223 static_cast<cricket::RtpDataChannel*>(channel));
6224 break;
6225 default:
6226 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6227 break;
6228 }
Zhi Huange830e682018-03-30 10:48:35 -07006229}
Steve Anton6fec8802017-12-04 10:37:29 -08006230
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006231bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006232 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006233 RtpTransportInternal* rtp_transport,
6234 cricket::DtlsTransportInternal* dtls_transport) {
6235 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006236 auto base_channel = GetChannel(mid);
6237 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006238 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006239 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006240 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006241 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006242 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006243 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006244}
6245
Harald Alvestrand89061872018-01-02 14:08:34 +01006246void PeerConnection::ClearStatsCache() {
6247 if (stats_collector_) {
6248 stats_collector_->ClearCachedStatsReport();
6249 }
6250}
6251
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006252} // namespace webrtc