blob: 58a35c460a2e5b888125469cc89304cbd447edd2 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020020#include "api/jsepicecandidate.h"
21#include "api/jsepsessiondescription.h"
22#include "api/mediaconstraintsinterface.h"
23#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
25#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080026#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020027#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080031#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080037#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080040#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080041#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010048#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020049#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
51#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000055
Steve Anton75737c02017-11-06 10:37:17 -080056using cricket::ContentInfo;
57using cricket::ContentInfos;
58using cricket::MediaContentDescription;
59using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080060using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080061using cricket::TransportInfo;
62
63using cricket::LOCAL_PORT_TYPE;
64using cricket::STUN_PORT_TYPE;
65using cricket::RELAY_PORT_TYPE;
66using cricket::PRFLX_PORT_TYPE;
67
Steve Antonba818672017-11-06 10:21:57 -080068namespace webrtc {
69
Steve Anton75737c02017-11-06 10:37:17 -080070// Error messages
71const char kBundleWithoutRtcpMux[] =
72 "rtcp-mux must be enabled when BUNDLE "
73 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080074const char kInvalidCandidates[] = "Description contains invalid candidates.";
75const char kInvalidSdp[] = "Invalid session description.";
76const char kMlineMismatchInAnswer[] =
77 "The order of m-lines in answer doesn't match order in offer. Rejecting "
78 "answer.";
79const char kMlineMismatchInSubsequentOffer[] =
80 "The order of m-lines in subsequent offer doesn't match order from "
81 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080082const char kSdpWithoutDtlsFingerprint[] =
83 "Called with SDP without DTLS fingerprint.";
84const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
85const char kSdpWithoutIceUfragPwd[] =
86 "Called with SDP without ice-ufrag and ice-pwd.";
87const char kSessionError[] = "Session error code: ";
88const char kSessionErrorDesc[] = "Session error description: ";
89const char kDtlsSrtpSetupFailureRtp[] =
90 "Couldn't set up DTLS-SRTP on RTP channel.";
91const char kDtlsSrtpSetupFailureRtcp[] =
92 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000093
Steve Anton75737c02017-11-06 10:37:17 -080094namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Seth Hampson845e8782018-03-02 11:34:10 -080096static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080097static const char kDefaultAudioSenderId[] = "defaulta0";
98static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070099
zhihuang8f65cdf2016-05-06 18:40:30 -0700100// The length of RTCP CNAMEs.
101static const int kRtcpCnameLength = 16;
102
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000104 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700106 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000107 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800108 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109};
110
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000111struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000112 explicit SetSessionDescriptionMsg(
113 webrtc::SetSessionDescriptionObserver* observer)
114 : observer(observer) {
115 }
116
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000117 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100118 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000119};
120
deadbeefab9b2d12015-10-14 11:33:11 -0700121struct CreateSessionDescriptionMsg : public rtc::MessageData {
122 explicit CreateSessionDescriptionMsg(
123 webrtc::CreateSessionDescriptionObserver* observer)
124 : observer(observer) {}
125
126 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100127 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700128};
129
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000130struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000131 GetStatsMsg(webrtc::StatsObserver* observer,
132 webrtc::MediaStreamTrackInterface* track)
133 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000135 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000136 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000137};
138
deadbeefab9b2d12015-10-14 11:33:11 -0700139// Check if we can send |new_stream| on a PeerConnection.
140bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
141 webrtc::MediaStreamInterface* new_stream) {
142 if (!new_stream || !current_streams) {
143 return false;
144 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700145 if (current_streams->find(new_stream->id()) != nullptr) {
146 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100147 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700148 return false;
149 }
150 return true;
151}
152
deadbeef5e97fb52015-10-15 12:49:08 -0700153// If the direction is "recvonly" or "inactive", treat the description
154// as containing no streams.
155// See: https://code.google.com/p/webrtc/issues/detail?id=5054
156std::vector<cricket::StreamParams> GetActiveStreams(
157 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800158 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700159 ? desc->streams()
160 : std::vector<cricket::StreamParams>();
161}
162
deadbeefab9b2d12015-10-14 11:33:11 -0700163bool IsValidOfferToReceiveMedia(int value) {
164 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
165 return (value >= Options::kUndefined) &&
166 (value <= Options::kMaxOfferToReceiveMedia);
167}
168
zhihuang1c378ed2017-08-17 14:10:50 -0700169// Add options to |[audio/video]_media_description_options| from |senders|.
170void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700171 const std::vector<rtc::scoped_refptr<
172 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700173 cricket::MediaDescriptionOptions* audio_media_description_options,
174 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700175 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700176 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
177 if (audio_media_description_options) {
178 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700179 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700180 }
181 } else {
182 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
183 if (video_media_description_options) {
184 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700185 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700186 }
187 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700188 }
zhihuang1c378ed2017-08-17 14:10:50 -0700189}
olka3c747662017-08-17 06:50:32 -0700190
zhihuang1c378ed2017-08-17 14:10:50 -0700191// Add options to |session_options| from |rtp_data_channels|.
192void AddRtpDataChannelOptions(
193 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
194 rtp_data_channels,
195 cricket::MediaDescriptionOptions* data_media_description_options) {
196 if (!data_media_description_options) {
197 return;
198 }
deadbeefab9b2d12015-10-14 11:33:11 -0700199 // Check for data channels.
200 for (const auto& kv : rtp_data_channels) {
201 const DataChannel* channel = kv.second;
202 if (channel->state() == DataChannel::kConnecting ||
203 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700204 // Legacy RTP data channels are signaled with the track/stream ID set to
205 // the data channel's label.
206 data_media_description_options->AddRtpDataChannel(channel->label(),
207 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700208 }
209 }
210}
211
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700212uint32_t ConvertIceTransportTypeToCandidateFilter(
213 PeerConnectionInterface::IceTransportsType type) {
214 switch (type) {
215 case PeerConnectionInterface::kNone:
216 return cricket::CF_NONE;
217 case PeerConnectionInterface::kRelay:
218 return cricket::CF_RELAY;
219 case PeerConnectionInterface::kNoHost:
220 return (cricket::CF_ALL & ~cricket::CF_HOST);
221 case PeerConnectionInterface::kAll:
222 return cricket::CF_ALL;
223 default:
nissec80e7412017-01-11 05:56:46 -0800224 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700225 }
226 return cricket::CF_NONE;
227}
228
deadbeef293e9262017-01-11 12:28:30 -0800229// Helper to set an error and return from a method.
230bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
231 if (error) {
232 error->set_type(type);
233 }
234 return type == webrtc::RTCErrorType::NONE;
235}
236
Steve Anton038834f2017-07-14 15:59:59 -0700237bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
238 if (error_out) {
239 *error_out = std::move(error);
240 }
241 return error.ok();
242}
243
Steve Antonba818672017-11-06 10:21:57 -0800244std::string GetSignalingStateString(
245 PeerConnectionInterface::SignalingState state) {
246 switch (state) {
247 case PeerConnectionInterface::kStable:
248 return "kStable";
249 case PeerConnectionInterface::kHaveLocalOffer:
250 return "kHaveLocalOffer";
251 case PeerConnectionInterface::kHaveLocalPrAnswer:
252 return "kHavePrAnswer";
253 case PeerConnectionInterface::kHaveRemoteOffer:
254 return "kHaveRemoteOffer";
255 case PeerConnectionInterface::kHaveRemotePrAnswer:
256 return "kHaveRemotePrAnswer";
257 case PeerConnectionInterface::kClosed:
258 return "kClosed";
259 }
260 RTC_NOTREACHED();
261 return "";
262}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700263
Steve Anton75737c02017-11-06 10:37:17 -0800264IceCandidatePairType GetIceCandidatePairCounter(
265 const cricket::Candidate& local,
266 const cricket::Candidate& remote) {
267 const auto& l = local.type();
268 const auto& r = remote.type();
269 const auto& host = LOCAL_PORT_TYPE;
270 const auto& srflx = STUN_PORT_TYPE;
271 const auto& relay = RELAY_PORT_TYPE;
272 const auto& prflx = PRFLX_PORT_TYPE;
273 if (l == host && r == host) {
274 bool local_private = IPIsPrivate(local.address().ipaddr());
275 bool remote_private = IPIsPrivate(remote.address().ipaddr());
276 if (local_private) {
277 if (remote_private) {
278 return kIceCandidatePairHostPrivateHostPrivate;
279 } else {
280 return kIceCandidatePairHostPrivateHostPublic;
281 }
282 } else {
283 if (remote_private) {
284 return kIceCandidatePairHostPublicHostPrivate;
285 } else {
286 return kIceCandidatePairHostPublicHostPublic;
287 }
288 }
289 }
290 if (l == host && r == srflx)
291 return kIceCandidatePairHostSrflx;
292 if (l == host && r == relay)
293 return kIceCandidatePairHostRelay;
294 if (l == host && r == prflx)
295 return kIceCandidatePairHostPrflx;
296 if (l == srflx && r == host)
297 return kIceCandidatePairSrflxHost;
298 if (l == srflx && r == srflx)
299 return kIceCandidatePairSrflxSrflx;
300 if (l == srflx && r == relay)
301 return kIceCandidatePairSrflxRelay;
302 if (l == srflx && r == prflx)
303 return kIceCandidatePairSrflxPrflx;
304 if (l == relay && r == host)
305 return kIceCandidatePairRelayHost;
306 if (l == relay && r == srflx)
307 return kIceCandidatePairRelaySrflx;
308 if (l == relay && r == relay)
309 return kIceCandidatePairRelayRelay;
310 if (l == relay && r == prflx)
311 return kIceCandidatePairRelayPrflx;
312 if (l == prflx && r == host)
313 return kIceCandidatePairPrflxHost;
314 if (l == prflx && r == srflx)
315 return kIceCandidatePairPrflxSrflx;
316 if (l == prflx && r == relay)
317 return kIceCandidatePairPrflxRelay;
318 return kIceCandidatePairMax;
319}
320
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800321// Logic to decide if an m= section can be recycled. This means that the new
322// m= section is not rejected, but the old local or remote m= section is
323// rejected. |old_content_one| and |old_content_two| refer to the m= section
324// of the old remote and old local descriptions in no particular order.
325// We need to check both the old local and remote because either
326// could be the most current from the latest negotation.
327bool IsMediaSectionBeingRecycled(SdpType type,
328 const ContentInfo& content,
329 const ContentInfo* old_content_one,
330 const ContentInfo* old_content_two) {
331 return type == SdpType::kOffer && !content.rejected &&
332 ((old_content_one && old_content_one->rejected) ||
333 (old_content_two && old_content_two->rejected));
334}
335
Steve Anton75737c02017-11-06 10:37:17 -0800336// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800337// |current_desc|. The number of m= sections in |new_desc| should be no
338// less than |current_desc|. In the case of checking an answer's
339// |new_desc|, the |current_desc| is the last offer that was set as the
340// local or remote. In the case of checking an offer's |new_desc| we
341// check against the local and remote descriptions stored from the last
342// negotiation, because either of these could be the most up to date for
343// possible rejected m sections. These are the |current_desc| and
344// |secondary_current_desc|.
345bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
346 const SessionDescription* secondary_current_desc,
347 const SessionDescription& new_desc,
348 const SdpType type) {
349 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800350 return false;
351 }
352
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800353 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
354 const cricket::ContentInfo* secondary_content_info = nullptr;
355 if (secondary_current_desc &&
356 i < secondary_current_desc->contents().size()) {
357 secondary_content_info = &secondary_current_desc->contents()[i];
358 }
359 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
360 &current_desc.contents()[i],
361 secondary_content_info)) {
362 // For new offer descriptions, if the media section can be recycled, it's
363 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800364 continue;
365 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800366 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800367 return false;
368 }
369 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800370 new_desc.contents()[i].media_description();
371 const MediaContentDescription* current_desc_mdesc =
372 current_desc.contents()[i].media_description();
373 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800374 return false;
375 }
376 }
377 return true;
378}
379
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800380bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
381 const SessionDescription& desc2) {
382 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800383}
384
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100385void NoteKeyProtocolAndMedia(
386 KeyExchangeProtocolType protocol_type,
387 cricket::MediaType media_type,
388 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
389 if (!uma_observer)
390 return;
391 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
392 protocol_type,
393 webrtc::kEnumCounterKeyProtocolMax);
394 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
395 KeyExchangeProtocolMedia>
396 proto_media_counter_map = {
397 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
398 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
399 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
400 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
401 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
402 kEnumCounterKeyProtocolMediaTypeDtlsData},
403 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
404 kEnumCounterKeyProtocolMediaTypeSdesAudio},
405 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
406 kEnumCounterKeyProtocolMediaTypeSdesVideo},
407 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
408 kEnumCounterKeyProtocolMediaTypeSdesData}};
409
410 auto it = proto_media_counter_map.find({protocol_type, media_type});
411 if (it != proto_media_counter_map.end()) {
412 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
413 it->second,
414 kEnumCounterKeyProtocolMediaTypeMax);
415 }
416}
417
Steve Anton75737c02017-11-06 10:37:17 -0800418// Checks that each non-rejected content has SDES crypto keys or a DTLS
419// fingerprint, unless it's in a BUNDLE group, in which case only the
420// BUNDLE-tag section (first media section/description in the BUNDLE group)
421// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
422// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
423// by Channel's |srtp_required| check.
Harald Alvestrand194939b2018-01-24 16:04:13 +0100424RTCError VerifyCrypto(const SessionDescription* desc,
425 bool dtls_enabled,
426 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800427 const cricket::ContentGroup* bundle =
428 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800429 for (const cricket::ContentInfo& content_info : desc->contents()) {
430 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800431 continue;
432 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100433 // Note what media is used with each crypto protocol, for all sections.
434 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
435 : webrtc::kEnumCounterKeyProtocolSdes,
436 content_info.media_description()->type(),
437 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800438 const std::string& mid = content_info.name;
439 if (bundle && bundle->HasContentName(mid) &&
440 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800441 // This isn't the first media section in the BUNDLE group, so it's not
442 // required to have crypto attributes, since only the crypto attributes
443 // from the first section actually get used.
444 continue;
445 }
446
447 // If the content isn't rejected or bundled into another m= section, crypto
448 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800449 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800450 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800451 if (!media || !tinfo) {
452 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800453 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800454 }
455 if (dtls_enabled) {
456 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100457 RTC_LOG(LS_WARNING)
458 << "Session description must have DTLS fingerprint if "
459 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800460 return RTCError(RTCErrorType::INVALID_PARAMETER,
461 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800462 }
463 } else {
464 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100465 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800466 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800467 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800468 }
469 }
470 }
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800472}
473
474// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
475// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
476// media section/description in the BUNDLE group) needs a ufrag and pwd.
477bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
478 const cricket::ContentGroup* bundle =
479 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800480 for (const cricket::ContentInfo& content_info : desc->contents()) {
481 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800482 continue;
483 }
Steve Anton8a006912017-12-04 15:25:56 -0800484 const std::string& mid = content_info.name;
485 if (bundle && bundle->HasContentName(mid) &&
486 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800487 // This isn't the first media section in the BUNDLE group, so it's not
488 // required to have ufrag/password, since only the ufrag/password from
489 // the first section actually get used.
490 continue;
491 }
492
493 // If the content isn't rejected or bundled into another m= section,
494 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800495 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800496 if (!tinfo) {
497 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100498 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800499 return false;
500 }
501 if (tinfo->description.ice_ufrag.empty() ||
502 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100503 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800504 return false;
505 }
506 }
507 return true;
508}
509
510bool GetTrackIdBySsrc(const SessionDescription* session_description,
511 uint32_t ssrc,
512 std::string* track_id) {
513 RTC_DCHECK(track_id != NULL);
514
Steve Antonb1c1de12017-12-21 15:14:30 -0800515 const cricket::AudioContentDescription* audio_desc =
516 cricket::GetFirstAudioContentDescription(session_description);
517 if (audio_desc) {
518 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800519 if (found) {
520 *track_id = found->id;
521 return true;
522 }
523 }
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::VideoContentDescription* video_desc =
526 cricket::GetFirstVideoContentDescription(session_description);
527 if (video_desc) {
528 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534 return false;
535}
536
537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
597 std::ostringstream oss;
598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
600 return oss.str();
601}
602
Seth Hampson5b4f0752018-04-02 16:31:36 -0700603std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
604 std::string output = "streams=[";
605 const char* separator = "";
606 for (const auto& stream_id : stream_ids) {
607 output.append(separator).append(stream_id);
608 separator = ", ";
609 }
610 output.append("]");
611 return output;
612}
613
Qingsi Wang866e08d2018-03-22 17:54:23 -0700614rtc::Optional<int> RTCConfigurationToIceConfigOptionalInt(
615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
618 return rtc::nullopt;
619 }
620 return rtc_configuration_parameter;
621}
622
Steve Anton75737c02017-11-06 10:37:17 -0800623} // namespace
624
Henrik Boström31638672017-11-23 17:48:32 +0100625// Upon completion, posts a task to execute the callback of the
626// SetSessionDescriptionObserver asynchronously on the same thread. At this
627// point, the state of the peer connection might no longer reflect the effects
628// of the SetRemoteDescription operation, as the peer connection could have been
629// modified during the post.
630// TODO(hbos): Remove this class once we remove the version of
631// PeerConnectionInterface::SetRemoteDescription() that takes a
632// SetSessionDescriptionObserver as an argument.
633class PeerConnection::SetRemoteDescriptionObserverAdapter
634 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
635 public:
636 SetRemoteDescriptionObserverAdapter(
637 rtc::scoped_refptr<PeerConnection> pc,
638 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
639 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
640
641 // SetRemoteDescriptionObserverInterface implementation.
642 void OnSetRemoteDescriptionComplete(RTCError error) override {
643 if (error.ok())
644 pc_->PostSetSessionDescriptionSuccess(wrapper_);
645 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100646 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100647 }
648
649 private:
650 rtc::scoped_refptr<PeerConnection> pc_;
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
652};
653
deadbeef293e9262017-01-11 12:28:30 -0800654bool PeerConnectionInterface::RTCConfiguration::operator==(
655 const PeerConnectionInterface::RTCConfiguration& o) const {
656 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700657 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800658 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000659 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700660 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800661 BundlePolicy bundle_policy;
662 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700663 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
664 int ice_candidate_pool_size;
665 bool disable_ipv6;
666 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700667 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100668 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700669 bool enable_rtp_data_channel;
670 rtc::Optional<int> screencast_min_bitrate;
671 rtc::Optional<bool> combined_audio_video_bwe;
672 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800673 TcpCandidatePolicy tcp_candidate_policy;
674 CandidateNetworkPolicy candidate_network_policy;
675 int audio_jitter_buffer_max_packets;
676 bool audio_jitter_buffer_fast_accelerate;
677 int ice_connection_receiving_timeout;
678 int ice_backup_candidate_pair_ping_interval;
679 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800680 bool prioritize_most_likely_ice_candidate_pairs;
681 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800682 bool prune_turn_ports;
683 bool presume_writable_when_fully_relayed;
684 bool enable_ice_renomination;
685 bool redetermine_role_on_ice_restart;
Qingsi Wange6826d22018-03-08 14:55:14 -0800686 rtc::Optional<int> ice_check_interval_strong_connectivity;
687 rtc::Optional<int> ice_check_interval_weak_connectivity;
skvlad51072462017-02-02 11:50:14 -0800688 rtc::Optional<int> ice_check_min_interval;
Qingsi Wang22e623a2018-03-13 10:53:57 -0700689 rtc::Optional<int> ice_unwritable_timeout;
690 rtc::Optional<int> ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800691 rtc::Optional<int> stun_candidate_keepalive_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700692 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200693 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800694 SdpSemantics sdp_semantics;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800695 rtc::Optional<rtc::AdapterType> network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800696 };
697 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
698 "Did you add something to RTCConfiguration and forget to "
699 "update operator==?");
700 return type == o.type && servers == o.servers &&
701 bundle_policy == o.bundle_policy &&
702 rtcp_mux_policy == o.rtcp_mux_policy &&
703 tcp_candidate_policy == o.tcp_candidate_policy &&
704 candidate_network_policy == o.candidate_network_policy &&
705 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
706 audio_jitter_buffer_fast_accelerate ==
707 o.audio_jitter_buffer_fast_accelerate &&
708 ice_connection_receiving_timeout ==
709 o.ice_connection_receiving_timeout &&
710 ice_backup_candidate_pair_ping_interval ==
711 o.ice_backup_candidate_pair_ping_interval &&
712 continual_gathering_policy == o.continual_gathering_policy &&
713 certificates == o.certificates &&
714 prioritize_most_likely_ice_candidate_pairs ==
715 o.prioritize_most_likely_ice_candidate_pairs &&
716 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800717 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700718 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100719 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800720 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800721 screencast_min_bitrate == o.screencast_min_bitrate &&
722 combined_audio_video_bwe == o.combined_audio_video_bwe &&
723 enable_dtls_srtp == o.enable_dtls_srtp &&
724 ice_candidate_pool_size == o.ice_candidate_pool_size &&
725 prune_turn_ports == o.prune_turn_ports &&
726 presume_writable_when_fully_relayed ==
727 o.presume_writable_when_fully_relayed &&
728 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800729 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800730 ice_check_interval_strong_connectivity ==
731 o.ice_check_interval_strong_connectivity &&
732 ice_check_interval_weak_connectivity ==
733 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700734 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700735 ice_unwritable_timeout == o.ice_unwritable_timeout &&
736 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800737 stun_candidate_keepalive_interval ==
738 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200739 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800740 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800741 sdp_semantics == o.sdp_semantics &&
742 network_preference == o.network_preference;
deadbeef293e9262017-01-11 12:28:30 -0800743}
744
745bool PeerConnectionInterface::RTCConfiguration::operator!=(
746 const PeerConnectionInterface::RTCConfiguration& o) const {
747 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800748}
749
zhihuang8f65cdf2016-05-06 18:40:30 -0700750// Generate a RTCP CNAME when a PeerConnection is created.
751std::string GenerateRtcpCname() {
752 std::string cname;
753 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100754 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800755 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700756 }
757 return cname;
758}
759
zhihuang1c378ed2017-08-17 14:10:50 -0700760bool ValidateOfferAnswerOptions(
761 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
762 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
763 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700764}
765
zhihuang1c378ed2017-08-17 14:10:50 -0700766// From |rtc_options|, fill parts of |session_options| shared by all generated
767// m= sections (in other words, nothing that involves a map/array).
768void ExtractSharedMediaSessionOptions(
769 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
770 cricket::MediaSessionOptions* session_options) {
771 session_options->vad_enabled = rtc_options.voice_activity_detection;
772 session_options->bundle_enabled = rtc_options.use_rtp_mux;
773}
zhihuanga77e6bb2017-08-14 18:17:48 -0700774
zhihuang1c378ed2017-08-17 14:10:50 -0700775bool ConvertConstraintsToOfferAnswerOptions(
776 const MediaConstraintsInterface* constraints,
777 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700778 if (!constraints) {
779 return true;
780 }
zhihuang1c378ed2017-08-17 14:10:50 -0700781
782 bool value = false;
783 size_t mandatory_constraints_satisfied = 0;
784
785 if (FindConstraint(constraints,
786 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
787 &mandatory_constraints_satisfied)) {
788 offer_answer_options->offer_to_receive_audio =
789 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
790 kOfferToReceiveMediaTrue
791 : 0;
792 }
793
794 if (FindConstraint(constraints,
795 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
796 &mandatory_constraints_satisfied)) {
797 offer_answer_options->offer_to_receive_video =
798 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
799 kOfferToReceiveMediaTrue
800 : 0;
801 }
802 if (FindConstraint(constraints,
803 MediaConstraintsInterface::kVoiceActivityDetection, &value,
804 &mandatory_constraints_satisfied)) {
805 offer_answer_options->voice_activity_detection = value;
806 }
807 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
808 &mandatory_constraints_satisfied)) {
809 offer_answer_options->use_rtp_mux = value;
810 }
811 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
812 &value, &mandatory_constraints_satisfied)) {
813 offer_answer_options->ice_restart = value;
814 }
815
deadbeefab9b2d12015-10-14 11:33:11 -0700816 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
817}
818
zhihuang38ede132017-06-15 12:52:32 -0700819PeerConnection::PeerConnection(PeerConnectionFactory* factory,
820 std::unique_ptr<RtcEventLog> event_log,
821 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700823 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700824 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700825 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700826 remote_streams_(StreamCollection::Create()),
827 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000828
829PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100830 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800831 RTC_DCHECK_RUN_ON(signaling_thread());
832
Steve Anton8af21862017-12-15 11:20:13 -0800833 // Need to stop transceivers before destroying the stats collector because
834 // AudioRtpSender has a reference to the StatsCollector it will update when
835 // stopping.
836 for (auto transceiver : transceivers_) {
837 transceiver->Stop();
838 }
Steve Anton4171afb2017-11-20 10:20:22 -0800839
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700840 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800841 if (stats_collector_) {
842 stats_collector_->WaitForPendingRequest();
843 stats_collector_ = nullptr;
844 }
Steve Anton75737c02017-11-06 10:37:17 -0800845
Steve Anton8af21862017-12-15 11:20:13 -0800846 // Don't destroy BaseChannels until after stats has been cleaned up so that
847 // the last stats request can still read from the channels.
848 DestroyAllChannels();
849
Mirko Bonadei675513b2017-11-09 11:09:25 +0100850 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800851
852 webrtc_session_desc_factory_.reset();
853 sctp_invoker_.reset();
854 sctp_factory_.reset();
855 transport_controller_.reset();
856
deadbeef91dd5672016-05-18 16:55:30 -0700857 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700858 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700859 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700860 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700861 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700862 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800863 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700864 event_log_.reset();
865 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866}
867
Steve Anton8af21862017-12-15 11:20:13 -0800868void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800869 // Destroy video channels first since they may have a pointer to a voice
870 // channel.
871 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800872 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800873 DestroyTransceiverChannel(transceiver);
874 }
875 }
876 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800877 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800878 DestroyTransceiverChannel(transceiver);
879 }
880 }
881 DestroyDataChannel();
882}
883
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000885 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700886 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100887 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700888
889 RTCError config_error = ValidateConfiguration(configuration);
890 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100891 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700892 return false;
893 }
894
Benjamin Wrightcab58882018-05-02 15:12:47 -0700895 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100896 RTC_LOG(LS_ERROR)
897 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100898 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800899 return false;
900 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200901
Benjamin Wrightcab58882018-05-02 15:12:47 -0700902 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800903 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100905 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800906 return false;
907 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700908
Benjamin Wrightcab58882018-05-02 15:12:47 -0700909 observer_ = dependencies.observer;
910 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700911 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800912
deadbeef91dd5672016-05-18 16:55:30 -0700913 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700914 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700915 if (!network_thread()->Invoke<bool>(
916 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
917 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 return false;
919 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920
Zhi Huange830e682018-03-30 10:48:35 -0700921 const PeerConnectionFactoryInterface::Options& options = factory_->options();
922
Steve Anton75737c02017-11-06 10:37:17 -0800923 // RFC 3264: The numeric value of the session id and version in the
924 // o line MUST be representable with a "64 bit signed integer".
925 // Due to this constraint session id |session_id_| is max limited to
926 // LLONG_MAX.
927 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700928 JsepTransportController::Config config;
929 config.redetermine_role_on_ice_restart =
930 configuration.redetermine_role_on_ice_restart;
931 config.ssl_max_version = factory_->options().ssl_max_version;
932 config.disable_encryption = options.disable_encryption;
933 config.bundle_policy = configuration.bundle_policy;
934 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
935 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700936 config.transport_observer = this;
Zhi Huange830e682018-03-30 10:48:35 -0700937#if defined(ENABLE_EXTERNAL_AUTH)
938 config.enable_external_auth = true;
939#endif
940 transport_controller_.reset(new JsepTransportController(
941 signaling_thread(), network_thread(), port_allocator_.get(), config));
942 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800943 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700944 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800945 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700946 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800947 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700948 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800949 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
950 transport_controller_->SignalDtlsHandshakeError.connect(
951 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
952
953 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700954
deadbeefab9b2d12015-10-14 11:33:11 -0700955 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700956 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957
Steve Antonba818672017-11-06 10:21:57 -0800958 configuration_ = configuration;
959
Steve Anton75737c02017-11-06 10:37:17 -0800960 // Obtain a certificate from RTCConfiguration if any were provided (optional).
961 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
962 if (!configuration.certificates.empty()) {
963 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
964 // just picking the first one. The decision should be made based on the DTLS
965 // handshake. The DTLS negotiations need to know about all certificates.
966 certificate = configuration.certificates[0];
967 }
968
Steve Antond25da372017-11-06 14:50:29 -0800969 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800970
971 if (options.disable_encryption) {
972 dtls_enabled_ = false;
973 } else {
974 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700975 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800976 // |configuration| can override the default |dtls_enabled_| value.
977 if (configuration.enable_dtls_srtp) {
978 dtls_enabled_ = *(configuration.enable_dtls_srtp);
979 }
980 }
981
982 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
983 // It takes precendence over the disable_sctp_data_channels
984 // PeerConnectionFactoryInterface::Options.
985 if (configuration.enable_rtp_data_channel) {
986 data_channel_type_ = cricket::DCT_RTP;
987 } else {
988 // DTLS has to be enabled to use SCTP.
989 if (!options.disable_sctp_data_channels && dtls_enabled_) {
990 data_channel_type_ = cricket::DCT_SCTP;
991 }
992 }
993
994 video_options_.screencast_min_bitrate_kbps =
995 configuration.screencast_min_bitrate;
996 audio_options_.combined_audio_video_bwe =
997 configuration.combined_audio_video_bwe;
998
999 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001000 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001001
1002 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001003 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001004
1005 // Whether the certificate generator/certificate is null or not determines
1006 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1007 // the right instructions by clearing the variables if needed.
1008 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001009 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001010 certificate = nullptr;
1011 } else if (certificate) {
1012 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001013 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001014 }
1015
1016 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1017 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001018 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001019 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1020 this, &PeerConnection::OnCertificateReady);
1021
1022 if (options.disable_encryption) {
1023 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1024 }
1025
1026 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1027 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028
Steve Anton4171afb2017-11-20 10:20:22 -08001029 // Add default audio/video transceivers for Plan B SDP.
1030 if (!IsUnifiedPlan()) {
1031 transceivers_.push_back(
1032 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1033 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1037 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001038 return true;
1039}
1040
Steve Anton038834f2017-07-14 15:59:59 -07001041RTCError PeerConnection::ValidateConfiguration(
1042 const RTCConfiguration& config) const {
1043 if (config.ice_regather_interval_range &&
1044 config.continual_gathering_policy == GATHER_ONCE) {
1045 return RTCError(RTCErrorType::INVALID_PARAMETER,
1046 "ice_regather_interval_range specified but continual "
1047 "gathering policy is GATHER_ONCE");
1048 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001049 auto result =
1050 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1051 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001052}
1053
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001054rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001055PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001056 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1057 "Plan SdpSemantics. Please use GetSenders "
1058 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001059 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001060}
1061
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001062rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001064 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1065 "Plan SdpSemantics. Please use GetReceivers "
1066 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001067 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001068}
1069
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001070bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001071 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1072 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001073 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001074 if (IsClosed()) {
1075 return false;
1076 }
deadbeefab9b2d12015-10-14 11:33:11 -07001077 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078 return false;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080
1081 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001082 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1083 observer->SignalAudioTrackAdded.connect(this,
1084 &PeerConnection::OnAudioTrackAdded);
1085 observer->SignalAudioTrackRemoved.connect(
1086 this, &PeerConnection::OnAudioTrackRemoved);
1087 observer->SignalVideoTrackAdded.connect(this,
1088 &PeerConnection::OnVideoTrackAdded);
1089 observer->SignalVideoTrackRemoved.connect(
1090 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001091 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001092
deadbeefab9b2d12015-10-14 11:33:11 -07001093 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001094 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001095 }
1096 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001097 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001100 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001101 observer_->OnRenegotiationNeeded();
1102 return true;
1103}
1104
1105void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001106 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1107 "Plan SdpSemantics. Please use RemoveTrack "
1108 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001109 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001110 if (!IsClosed()) {
1111 for (const auto& track : local_stream->GetAudioTracks()) {
1112 RemoveAudioTrack(track.get(), local_stream);
1113 }
1114 for (const auto& track : local_stream->GetVideoTracks()) {
1115 RemoveVideoTrack(track.get(), local_stream);
1116 }
deadbeefab9b2d12015-10-14 11:33:11 -07001117 }
deadbeefab9b2d12015-10-14 11:33:11 -07001118 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001119 stream_observers_.erase(
1120 std::remove_if(
1121 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001122 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001123 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001124 }),
1125 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001126
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001127 if (IsClosed()) {
1128 return;
1129 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 observer_->OnRenegotiationNeeded();
1131}
1132
deadbeefe1f9d832016-01-14 15:35:42 -08001133rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1134 MediaStreamTrackInterface* track,
1135 std::vector<MediaStreamInterface*> streams) {
1136 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001137 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001138 for (auto* stream : streams) {
1139 if (!stream) {
1140 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1141 return nullptr;
1142 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001143 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001144 }
Seth Hampson845e8782018-03-02 11:34:10 -08001145 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001146 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001147 return nullptr;
1148 }
Steve Antonf9381f02017-12-14 10:23:57 -08001149 return sender_or_error.MoveValue();
1150}
1151
Steve Anton2d6c76a2018-01-05 17:10:52 -08001152RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001153 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001154 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001155 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001156 if (!track) {
1157 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1158 }
1159 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1160 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1161 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1162 "Track has invalid kind: " + track->kind());
1163 }
Steve Antonf9381f02017-12-14 10:23:57 -08001164 if (IsClosed()) {
1165 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1166 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001167 }
Steve Anton4171afb2017-11-20 10:20:22 -08001168 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001169 LOG_AND_RETURN_ERROR(
1170 RTCErrorType::INVALID_PARAMETER,
1171 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001172 }
Steve Antonf9381f02017-12-14 10:23:57 -08001173 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001174 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1175 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001176 if (sender_or_error.ok()) {
1177 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001178 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001179 }
1180 return sender_or_error;
1181}
deadbeefe1f9d832016-01-14 15:35:42 -08001182
Steve Antonf9381f02017-12-14 10:23:57 -08001183RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1184PeerConnection::AddTrackPlanB(
1185 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001186 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001187 if (stream_ids.size() > 1u) {
1188 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1189 "AddTrack with more than one stream is not "
1190 "supported with Plan B semantics.");
1191 }
1192 std::vector<std::string> adjusted_stream_ids = stream_ids;
1193 if (adjusted_stream_ids.empty()) {
1194 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1195 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001196 cricket::MediaType media_type =
1197 (track->kind() == MediaStreamTrackInterface::kAudioKind
1198 ? cricket::MEDIA_TYPE_AUDIO
1199 : cricket::MEDIA_TYPE_VIDEO);
Seth Hampson5b4f0752018-04-02 16:31:36 -07001200 auto new_sender = CreateSender(media_type, track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001201 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001202 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001203 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001204 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001205 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001206 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001207 if (sender_info) {
1208 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001209 }
Steve Antonf9381f02017-12-14 10:23:57 -08001210 } else {
1211 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001212 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001213 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001214 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001215 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001216 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001217 if (sender_info) {
1218 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001219 }
deadbeefe1f9d832016-01-14 15:35:42 -08001220 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001221 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001222}
deadbeefe1f9d832016-01-14 15:35:42 -08001223
Steve Antonf9381f02017-12-14 10:23:57 -08001224RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1225PeerConnection::AddTrackUnifiedPlan(
1226 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001227 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001228 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1229 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001230 RTC_LOG(LS_INFO) << "Reusing an existing "
1231 << cricket::MediaTypeToString(transceiver->media_type())
1232 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001233 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001234 transceiver->internal()->set_direction(
1235 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001236 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001239 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001240 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001241 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001242 } else {
1243 cricket::MediaType media_type =
1244 (track->kind() == MediaStreamTrackInterface::kAudioKind
1245 ? cricket::MEDIA_TYPE_AUDIO
1246 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001247 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1248 << " transceiver in response to a call to AddTrack.";
Seth Hampson845e8782018-03-02 11:34:10 -08001249 auto sender = CreateSender(media_type, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001250 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1251 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001252 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001253 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001254 }
Steve Antonf9381f02017-12-14 10:23:57 -08001255 return transceiver->sender();
1256}
1257
1258rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1259PeerConnection::FindFirstTransceiverForAddedTrack(
1260 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1261 RTC_DCHECK(track);
1262 for (auto transceiver : transceivers_) {
1263 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001264 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001265 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001266 !transceiver->internal()->has_ever_been_used_to_send() &&
1267 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001268 return transceiver;
1269 }
1270 }
1271 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001272}
1273
1274bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1275 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001276 return RemoveTrackInternal(sender).ok();
1277}
1278
1279RTCError PeerConnection::RemoveTrackInternal(
1280 rtc::scoped_refptr<RtpSenderInterface> sender) {
1281 if (!sender) {
1282 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1283 }
deadbeefe1f9d832016-01-14 15:35:42 -08001284 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001285 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1286 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001287 }
Steve Antonf9381f02017-12-14 10:23:57 -08001288 if (IsUnifiedPlan()) {
1289 auto transceiver = FindTransceiverBySender(sender);
1290 if (!transceiver || !sender->track()) {
1291 return RTCError::OK();
1292 }
1293 sender->SetTrack(nullptr);
1294 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001295 transceiver->internal()->set_direction(
1296 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001297 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001298 transceiver->internal()->set_direction(
1299 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001300 }
Steve Anton4171afb2017-11-20 10:20:22 -08001301 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001302 bool removed;
1303 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1304 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1305 } else {
1306 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1307 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1308 }
1309 if (!removed) {
1310 LOG_AND_RETURN_ERROR(
1311 RTCErrorType::INVALID_PARAMETER,
1312 "Couldn't find sender " + sender->id() + " to remove.");
1313 }
Steve Anton4171afb2017-11-20 10:20:22 -08001314 }
deadbeefe1f9d832016-01-14 15:35:42 -08001315 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001316 return RTCError::OK();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindTransceiverBySender(
1321 rtc::scoped_refptr<RtpSenderInterface> sender) {
1322 for (auto transceiver : transceivers_) {
1323 if (transceiver->sender() == sender) {
1324 return transceiver;
1325 }
1326 }
1327 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001328}
1329
Steve Anton9158ef62017-11-27 13:01:52 -08001330RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1331PeerConnection::AddTransceiver(
1332 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1333 return AddTransceiver(track, RtpTransceiverInit());
1334}
1335
1336RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1337PeerConnection::AddTransceiver(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1339 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001340 RTC_CHECK(IsUnifiedPlan())
1341 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001342 if (!track) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1344 }
1345 cricket::MediaType media_type;
1346 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1347 media_type = cricket::MEDIA_TYPE_AUDIO;
1348 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1349 media_type = cricket::MEDIA_TYPE_VIDEO;
1350 } else {
1351 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1352 "Track kind is not audio or video");
1353 }
1354 return AddTransceiver(media_type, track, init);
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1359 return AddTransceiver(media_type, RtpTransceiverInit());
1360}
1361
1362RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1363PeerConnection::AddTransceiver(cricket::MediaType media_type,
1364 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001365 RTC_CHECK(IsUnifiedPlan())
1366 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001367 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1368 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1369 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1370 "media type is not audio or video");
1371 }
1372 return AddTransceiver(media_type, nullptr, init);
1373}
1374
1375RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1376PeerConnection::AddTransceiver(
1377 cricket::MediaType media_type,
1378 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001379 const RtpTransceiverInit& init,
1380 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001381 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1382 media_type == cricket::MEDIA_TYPE_VIDEO));
1383 if (track) {
1384 RTC_DCHECK_EQ(media_type,
1385 (track->kind() == MediaStreamTrackInterface::kAudioKind
1386 ? cricket::MEDIA_TYPE_AUDIO
1387 : cricket::MEDIA_TYPE_VIDEO));
1388 }
1389
1390 // TODO(bugs.webrtc.org/7600): Verify init.
1391
Steve Anton3d954a62018-04-02 11:27:23 -07001392 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1393 << " transceiver in response to a call to AddTransceiver.";
Seth Hampson5b4f0752018-04-02 16:31:36 -07001394 auto sender = CreateSender(media_type, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001395 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1396 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1397 transceiver->internal()->set_direction(init.direction);
1398
Steve Anton22da89f2018-01-25 13:58:07 -08001399 if (fire_callback) {
1400 observer_->OnRenegotiationNeeded();
1401 }
Steve Antonf9381f02017-12-14 10:23:57 -08001402
1403 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1404}
1405
Steve Anton02ee47c2018-01-10 16:26:06 -08001406rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1407PeerConnection::CreateSender(
1408 cricket::MediaType media_type,
1409 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001410 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001411 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001412 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1413 RTC_DCHECK(!track ||
1414 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1415 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1416 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001417 new AudioRtpSender(worker_thread(),
1418 static_cast<AudioTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001419 stream_ids, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001420 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001421 } else {
1422 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1423 RTC_DCHECK(!track ||
1424 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1425 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1426 signaling_thread(),
Steve Anton47136dd2018-01-12 10:49:35 -08001427 new VideoRtpSender(worker_thread(),
1428 static_cast<VideoTrackInterface*>(track.get()),
Seth Hampson845e8782018-03-02 11:34:10 -08001429 stream_ids));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001430 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 }
Seth Hampson845e8782018-03-02 11:34:10 -08001432 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001433 return sender;
1434}
1435
1436rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1437PeerConnection::CreateReceiver(cricket::MediaType media_type,
1438 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001439 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1440 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001441 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001442 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton60776752018-01-10 11:51:34 -08001443 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001444 new AudioRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001445 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001446 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001448 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1449 signaling_thread(),
Steve Antond3679212018-01-17 17:41:02 -08001450 new VideoRtpReceiver(worker_thread(), receiver_id, {}));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001451 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001452 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001453 return receiver;
1454}
1455
1456rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1457PeerConnection::CreateAndAddTransceiver(
1458 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1459 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1460 receiver) {
1461 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1462 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001463 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001464 transceiver->internal()->SignalNegotiationNeeded.connect(
1465 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001466 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001467}
1468
Steve Anton52d86772018-02-20 15:48:12 -08001469void PeerConnection::OnNegotiationNeeded() {
1470 RTC_DCHECK_RUN_ON(signaling_thread());
1471 RTC_DCHECK(!IsClosed());
1472 observer_->OnRenegotiationNeeded();
1473}
1474
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001475rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001477 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001478 if (IsClosed()) {
1479 return nullptr;
1480 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001481 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001482 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001483 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001484 }
Steve Anton4171afb2017-11-20 10:20:22 -08001485 auto track_sender = FindSenderForTrack(track);
1486 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001487 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001488 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001489 }
1490
Steve Anton4171afb2017-11-20 10:20:22 -08001491 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001492}
1493
deadbeeffac06552015-11-25 11:26:01 -08001494rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001495 const std::string& kind,
1496 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001497 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1498 "Plan SdpSemantics. Please use AddTransceiver "
1499 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001500 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001501 if (IsClosed()) {
1502 return nullptr;
1503 }
Steve Anton4171afb2017-11-20 10:20:22 -08001504
Seth Hampson5b4f0752018-04-02 16:31:36 -07001505 // Internally we need to have one stream with Plan B semantics, so we
1506 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001507 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001508 if (stream_id.empty()) {
1509 stream_ids.push_back(rtc::CreateRandomUuid());
1510 RTC_LOG(LS_INFO)
1511 << "No stream_id specified for sender. Generated stream ID: "
1512 << stream_ids[0];
1513 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001514 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001515 }
1516
Steve Anton4171afb2017-11-20 10:20:22 -08001517 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001518 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001519 if (kind == MediaStreamTrackInterface::kAudioKind) {
Seth Hampson845e8782018-03-02 11:34:10 -08001520 auto* audio_sender =
1521 new AudioRtpSender(worker_thread(), nullptr, stream_ids, stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001522 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001523 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001524 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001525 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001526 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001527 auto* video_sender =
Seth Hampson845e8782018-03-02 11:34:10 -08001528 new VideoRtpSender(worker_thread(), nullptr, stream_ids);
Steve Anton57858b32018-02-15 15:19:50 -08001529 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001530 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001531 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001532 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001533 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001534 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001535 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001536 }
Steve Anton4171afb2017-11-20 10:20:22 -08001537
deadbeefe1f9d832016-01-14 15:35:42 -08001538 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001539}
1540
deadbeef70ab1a12015-09-28 16:53:55 -07001541std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1542 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001543 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001544 for (auto sender : GetSendersInternal()) {
1545 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001546 }
1547 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001548}
1549
Steve Anton4171afb2017-11-20 10:20:22 -08001550std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1551PeerConnection::GetSendersInternal() const {
1552 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1553 all_senders;
1554 for (auto transceiver : transceivers_) {
1555 auto senders = transceiver->internal()->senders();
1556 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1557 }
1558 return all_senders;
1559}
1560
deadbeef70ab1a12015-09-28 16:53:55 -07001561std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1562PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001563 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001564 for (const auto& receiver : GetReceiversInternal()) {
1565 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001566 }
1567 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001568}
1569
Steve Anton4171afb2017-11-20 10:20:22 -08001570std::vector<
1571 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1572PeerConnection::GetReceiversInternal() const {
1573 std::vector<
1574 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1575 all_receivers;
1576 for (auto transceiver : transceivers_) {
1577 auto receivers = transceiver->internal()->receivers();
1578 all_receivers.insert(all_receivers.end(), receivers.begin(),
1579 receivers.end());
1580 }
1581 return all_receivers;
1582}
1583
Steve Anton9158ef62017-11-27 13:01:52 -08001584std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1585PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001586 RTC_CHECK(IsUnifiedPlan())
1587 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001588 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1589 for (auto transceiver : transceivers_) {
1590 all_transceivers.push_back(transceiver);
1591 }
1592 return all_transceivers;
1593}
1594
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001595bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001596 MediaStreamTrackInterface* track,
1597 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001598 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001599 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001600 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001601 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001602 return false;
1603 }
1604
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001605 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001606 // The StatsCollector is used to tell if a track is valid because it may
1607 // remember tracks that the PeerConnection previously removed.
1608 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001609 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1610 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001611 return false;
1612 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001613 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001614 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001615 return true;
1616}
1617
hbos74e1a4f2016-09-15 23:33:01 -07001618void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001619 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001620 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001621 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001622 stats_collector_->GetStatsReport(callback);
1623}
1624
Henrik Boström1df1bf82018-03-20 13:24:20 +01001625void PeerConnection::GetStats(
1626 rtc::scoped_refptr<RtpSenderInterface> selector,
1627 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1628 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1629 RTC_DCHECK(callback);
1630 RTC_DCHECK(stats_collector_);
1631 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1632 if (selector) {
1633 for (const auto& proxy_transceiver : transceivers_) {
1634 for (const auto& proxy_sender :
1635 proxy_transceiver->internal()->senders()) {
1636 if (proxy_sender == selector) {
1637 internal_sender = proxy_sender->internal();
1638 break;
1639 }
1640 }
1641 if (internal_sender)
1642 break;
1643 }
1644 }
1645 // If there is no |internal_sender| then |selector| is either null or does not
1646 // belong to the PeerConnection (in Plan B, senders can be removed from the
1647 // PeerConnection). This means that "all the stats objects representing the
1648 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1649 // produces an empty stats report.
1650 stats_collector_->GetStatsReport(internal_sender, callback);
1651}
1652
1653void PeerConnection::GetStats(
1654 rtc::scoped_refptr<RtpReceiverInterface> selector,
1655 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1656 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1657 RTC_DCHECK(callback);
1658 RTC_DCHECK(stats_collector_);
1659 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1660 if (selector) {
1661 for (const auto& proxy_transceiver : transceivers_) {
1662 for (const auto& proxy_receiver :
1663 proxy_transceiver->internal()->receivers()) {
1664 if (proxy_receiver == selector) {
1665 internal_receiver = proxy_receiver->internal();
1666 break;
1667 }
1668 }
1669 if (internal_receiver)
1670 break;
1671 }
1672 }
1673 // If there is no |internal_receiver| then |selector| is either null or does
1674 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1675 // the PeerConnection). This means that "all the stats objects representing
1676 // the selector" is an empty set. Invoking GetStatsReport() with a null
1677 // selector produces an empty stats report.
1678 stats_collector_->GetStatsReport(internal_receiver, callback);
1679}
1680
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001681PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1682 return signaling_state_;
1683}
1684
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001685PeerConnectionInterface::IceConnectionState
1686PeerConnection::ice_connection_state() {
1687 return ice_connection_state_;
1688}
1689
1690PeerConnectionInterface::IceGatheringState
1691PeerConnection::ice_gathering_state() {
1692 return ice_gathering_state_;
1693}
1694
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001695rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696PeerConnection::CreateDataChannel(
1697 const std::string& label,
1698 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001699 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001700
deadbeefab9b2d12015-10-14 11:33:11 -07001701 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001702
kwibergd1fe2812016-04-27 06:47:29 -07001703 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001704 if (config) {
1705 internal_config.reset(new InternalDataChannelInit(*config));
1706 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001707 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001708 InternalCreateDataChannel(label, internal_config.get()));
1709 if (!channel.get()) {
1710 return nullptr;
1711 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001712
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001713 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1714 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001715 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001716 observer_->OnRenegotiationNeeded();
1717 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001718 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 return DataChannelProxy::Create(signaling_thread(), channel.get());
1720}
1721
1722void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1723 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001724 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001725
zhihuang1c378ed2017-08-17 14:10:50 -07001726 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1727 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1728 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1729 // compares the mandatory fields parsed with the mandatory fields added in the
1730 // |constraints| and some downstream applications might create offers with
1731 // mandatory fields which would not be parsed in the helper method. For
1732 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1733 // |constraints| as a mandatory field but it is not parsed.
1734 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001735
zhihuang1c378ed2017-08-17 14:10:50 -07001736 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001737}
1738
1739void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1740 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001741 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001742
nisse7ce109a2017-01-31 00:57:56 -08001743 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001744 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001745 return;
1746 }
deadbeefab9b2d12015-10-14 11:33:11 -07001747
Steve Anton8d3444d2017-10-20 15:30:51 -07001748 if (IsClosed()) {
1749 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001750 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001751 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001752 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001753 return;
1754 }
1755
zhihuang1c378ed2017-08-17 14:10:50 -07001756 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001757 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001758 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001759 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001760 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001761 return;
1762 }
1763
Steve Anton22da89f2018-01-25 13:58:07 -08001764 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1765 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1766 if (IsUnifiedPlan()) {
1767 RTCError error = HandleLegacyOfferOptions(options);
1768 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001769 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001770 return;
1771 }
1772 }
1773
zhihuang1c378ed2017-08-17 14:10:50 -07001774 cricket::MediaSessionOptions session_options;
1775 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001776 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001777}
1778
Steve Anton22da89f2018-01-25 13:58:07 -08001779RTCError PeerConnection::HandleLegacyOfferOptions(
1780 const RTCOfferAnswerOptions& options) {
1781 RTC_DCHECK(IsUnifiedPlan());
1782
1783 if (options.offer_to_receive_audio == 0) {
1784 RemoveRecvDirectionFromReceivingTransceiversOfType(
1785 cricket::MEDIA_TYPE_AUDIO);
1786 } else if (options.offer_to_receive_audio == 1) {
1787 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1788 } else if (options.offer_to_receive_audio > 1) {
1789 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1790 "offer_to_receive_audio > 1 is not supported.");
1791 }
1792
1793 if (options.offer_to_receive_video == 0) {
1794 RemoveRecvDirectionFromReceivingTransceiversOfType(
1795 cricket::MEDIA_TYPE_VIDEO);
1796 } else if (options.offer_to_receive_video == 1) {
1797 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1798 } else if (options.offer_to_receive_video > 1) {
1799 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1800 "offer_to_receive_video > 1 is not supported.");
1801 }
1802
1803 return RTCError::OK();
1804}
1805
1806void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1807 cricket::MediaType media_type) {
1808 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001809 RtpTransceiverDirection new_direction =
1810 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1811 if (new_direction != transceiver->direction()) {
1812 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1813 << " transceiver (MID="
1814 << transceiver->mid().value_or("<not set>") << ") from "
1815 << RtpTransceiverDirectionToString(
1816 transceiver->direction())
1817 << " to "
1818 << RtpTransceiverDirectionToString(new_direction)
1819 << " since CreateOffer specified offer_to_receive=0";
1820 transceiver->internal()->set_direction(new_direction);
1821 }
Steve Anton22da89f2018-01-25 13:58:07 -08001822 }
1823}
1824
1825void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1826 cricket::MediaType media_type) {
1827 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001828 RTC_LOG(LS_INFO)
1829 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1830 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001831 RtpTransceiverInit init;
1832 init.direction = RtpTransceiverDirection::kRecvOnly;
1833 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1834 }
1835}
1836
1837std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1838PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1839 std::vector<
1840 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1841 receiving_transceivers;
1842 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001843 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001844 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1845 receiving_transceivers.push_back(transceiver);
1846 }
1847 }
1848 return receiving_transceivers;
1849}
1850
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001851void PeerConnection::CreateAnswer(
1852 CreateSessionDescriptionObserver* observer,
1853 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001854 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001855
nisse7ce109a2017-01-31 00:57:56 -08001856 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001857 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001858 return;
1859 }
deadbeefab9b2d12015-10-14 11:33:11 -07001860
zhihuang1c378ed2017-08-17 14:10:50 -07001861 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1862 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1863 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001864 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001865 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001866 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001867 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001868 return;
1869 }
1870
Steve Anton8d3444d2017-10-20 15:30:51 -07001871 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001872}
1873
1874void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1875 const RTCOfferAnswerOptions& options) {
1876 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001877 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001878 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001879 return;
1880 }
1881
Steve Antondffead82018-02-06 10:31:29 -08001882 if (!(signaling_state_ == kHaveRemoteOffer ||
1883 signaling_state_ == kHaveLocalPrAnswer)) {
1884 std::string error =
1885 "PeerConnection cannot create an answer in a state other than "
1886 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001887 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001888 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001889 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001890 return;
1891 }
1892
Steve Antondffead82018-02-06 10:31:29 -08001893 // The remote description should be set if we're in the right state.
1894 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001895
Steve Anton22da89f2018-01-25 13:58:07 -08001896 if (IsUnifiedPlan()) {
1897 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1898 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1899 "supported with Unified Plan semantics. Use the "
1900 "RtpTransceiver API instead.";
1901 }
1902 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1903 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1904 "supported with Unified Plan semantics. Use the "
1905 "RtpTransceiver API instead.";
1906 }
1907 }
1908
htaa2a49d92016-03-04 02:51:39 -08001909 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001910 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001911
Steve Antond25da372017-11-06 14:50:29 -08001912 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001913}
1914
1915void PeerConnection::SetLocalDescription(
1916 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001917 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001918 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001919
Steve Anton80dd7b52018-02-16 17:08:42 -08001920 // The SetLocalDescription contract is that we take ownership of the session
1921 // description regardless of the outcome, so wrap it in a unique_ptr right
1922 // away. Ideally, SetLocalDescription's signature will be changed to take the
1923 // description as a unique_ptr argument to formalize this agreement.
1924 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1925
nisse7ce109a2017-01-31 00:57:56 -08001926 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001927 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 return;
1929 }
Steve Anton8a006912017-12-04 15:25:56 -08001930
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001931 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001932 PostSetSessionDescriptionFailure(
1933 observer,
1934 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935 return;
1936 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001937
Steve Anton80dd7b52018-02-16 17:08:42 -08001938 // If a session error has occurred the PeerConnection is in a possibly
1939 // inconsistent state so fail right away.
1940 if (session_error() != SessionError::kNone) {
1941 std::string error_message = GetSessionErrorMsg();
1942 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001943 PostSetSessionDescriptionFailure(
1944 observer,
1945 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001946 return;
1947 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001948
Steve Anton80dd7b52018-02-16 17:08:42 -08001949 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1950 if (!error.ok()) {
1951 std::string error_message = GetSetDescriptionErrorMessage(
1952 cricket::CS_LOCAL, desc->GetType(), error);
1953 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001954 PostSetSessionDescriptionFailure(
1955 observer,
1956 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001957 return;
1958 }
1959
1960 // Grab the description type before moving ownership to ApplyLocalDescription,
1961 // which may destroy it before returning.
1962 const SdpType type = desc->GetType();
1963
1964 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001965 // |desc| may be destroyed at this point.
1966
1967 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001968 // If ApplyLocalDescription fails, the PeerConnection could be in an
1969 // inconsistent state, so act conservatively here and set the session error
1970 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1971 SetSessionError(SessionError::kContent, error.message());
1972 std::string error_message =
1973 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1974 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001975 PostSetSessionDescriptionFailure(
1976 observer,
1977 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001978 return;
1979 }
Steve Anton8a006912017-12-04 15:25:56 -08001980 RTC_DCHECK(local_description());
1981
1982 PostSetSessionDescriptionSuccess(observer);
1983
Steve Anton8a006912017-12-04 15:25:56 -08001984 // MaybeStartGathering needs to be called after posting
1985 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1986 // before signaling that SetLocalDescription completed.
1987 transport_controller_->MaybeStartGathering();
1988
Steve Antona3a92c22017-12-07 10:27:41 -08001989 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001990 // TODO(deadbeef): We already had to hop to the network thread for
1991 // MaybeStartGathering...
1992 network_thread()->Invoke<void>(
1993 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1994 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001995 // Make UMA notes about what was agreed to.
1996 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001997 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001998 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001999}
2000
2001RTCError PeerConnection::ApplyLocalDescription(
2002 std::unique_ptr<SessionDescriptionInterface> desc) {
2003 RTC_DCHECK_RUN_ON(signaling_thread());
2004 RTC_DCHECK(desc);
2005
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002006 // Update stats here so that we have the most recent stats for tracks and
2007 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002008 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002009
Steve Antondcc3c022017-12-22 16:02:54 -08002010 // Take a reference to the old local description since it's used below to
2011 // compare against the new local description. When setting the new local
2012 // description, grab ownership of the replaced session description in case it
2013 // is the same as |old_local_description|, to keep it alive for the duration
2014 // of the method.
2015 const SessionDescriptionInterface* old_local_description =
2016 local_description();
2017 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002018 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002019 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002020 replaced_local_description = pending_local_description_
2021 ? std::move(pending_local_description_)
2022 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002023 current_local_description_ = std::move(desc);
2024 pending_local_description_ = nullptr;
2025 current_remote_description_ = std::move(pending_remote_description_);
2026 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002027 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002028 pending_local_description_ = std::move(desc);
2029 }
2030 // The session description to apply now must be accessed by
2031 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002032 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002033
Zhi Huange830e682018-03-30 10:48:35 -07002034 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2035 if (!error.ok()) {
2036 return error;
2037 }
2038
Steve Antondcc3c022017-12-22 16:02:54 -08002039 if (IsUnifiedPlan()) {
2040 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002041 cricket::CS_LOCAL, *local_description(), old_local_description,
2042 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002043 if (!error.ok()) {
2044 return error;
2045 }
Steve Antondcc3c022017-12-22 16:02:54 -08002046 for (auto transceiver : transceivers_) {
2047 const ContentInfo* content =
2048 FindMediaSectionForTransceiver(transceiver, local_description());
2049 if (!content) {
2050 continue;
2051 }
2052 const MediaContentDescription* media_desc = content->media_description();
2053 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2054 transceiver->internal()->set_current_direction(media_desc->direction());
2055 }
2056 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002057 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2058 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002059 transceiver->Stop();
2060 }
2061 }
2062 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002063 // Media channels will be created only when offer is set. These may use new
2064 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002065 if (type == SdpType::kOffer) {
2066 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2067 // description is applied. Restore back to old description.
2068 RTCError error = CreateChannels(*local_description()->description());
2069 if (!error.ok()) {
2070 return error;
2071 }
2072 }
Steve Antondcc3c022017-12-22 16:02:54 -08002073 // Remove unused channels if MediaContentDescription is rejected.
2074 RemoveUnusedChannels(local_description()->description());
2075 }
Steve Anton8a006912017-12-04 15:25:56 -08002076
Zhi Huange830e682018-03-30 10:48:35 -07002077 error = UpdateSessionState(type, cricket::CS_LOCAL,
2078 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002079 if (!error.ok()) {
2080 return error;
2081 }
Steve Antondcc3c022017-12-22 16:02:54 -08002082
Steve Anton8a006912017-12-04 15:25:56 -08002083 if (remote_description()) {
2084 // Now that we have a local description, we can push down remote candidates.
2085 UseCandidatesInSessionDescription(remote_description());
2086 }
2087
2088 pending_ice_restarts_.clear();
2089 if (session_error() != SessionError::kNone) {
2090 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2091 }
2092
deadbeefab9b2d12015-10-14 11:33:11 -07002093 // If setting the description decided our SSL role, allocate any necessary
2094 // SCTP sids.
2095 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002096 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002097 AllocateSctpSids(role);
2098 }
2099
Steve Antond3679212018-01-17 17:41:02 -08002100 if (IsUnifiedPlan()) {
2101 for (auto transceiver : transceivers_) {
2102 const ContentInfo* content =
2103 FindMediaSectionForTransceiver(transceiver, local_description());
2104 if (!content) {
2105 continue;
2106 }
Steve Anton74255ff2018-01-24 18:32:57 -08002107 const auto& streams = content->media_description()->streams();
2108 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002109 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002110 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002111 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002112 streams[0].first_ssrc());
Steve Antond3679212018-01-17 17:41:02 -08002113 }
2114 }
2115 } else {
2116 // Plan B semantics.
2117
Steve Antondcc3c022017-12-22 16:02:54 -08002118 // Update state and SSRC of local MediaStreams and DataChannels based on the
2119 // local session description.
2120 const cricket::ContentInfo* audio_content =
2121 GetFirstAudioContent(local_description()->description());
2122 if (audio_content) {
2123 if (audio_content->rejected) {
2124 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2125 } else {
2126 const cricket::AudioContentDescription* audio_desc =
2127 audio_content->media_description()->as_audio();
2128 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2129 }
deadbeeffaac4972015-11-12 15:33:07 -08002130 }
deadbeefab9b2d12015-10-14 11:33:11 -07002131
Steve Antondcc3c022017-12-22 16:02:54 -08002132 const cricket::ContentInfo* video_content =
2133 GetFirstVideoContent(local_description()->description());
2134 if (video_content) {
2135 if (video_content->rejected) {
2136 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2137 } else {
2138 const cricket::VideoContentDescription* video_desc =
2139 video_content->media_description()->as_video();
2140 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2141 }
deadbeeffaac4972015-11-12 15:33:07 -08002142 }
deadbeefab9b2d12015-10-14 11:33:11 -07002143 }
2144
2145 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002146 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002147 if (data_content) {
2148 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002149 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002150 if (rtc::starts_with(data_desc->protocol().data(),
2151 cricket::kMediaProtocolRtpPrefix)) {
2152 UpdateLocalRtpDataChannels(data_desc->streams());
2153 }
2154 }
2155
Steve Anton8a006912017-12-04 15:25:56 -08002156 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002157}
2158
2159void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002160 SetSessionDescriptionObserver* observer,
2161 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002162 SetRemoteDescription(
2163 std::unique_ptr<SessionDescriptionInterface>(desc),
2164 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2165 new SetRemoteDescriptionObserverAdapter(this, observer)));
2166}
2167
2168void PeerConnection::SetRemoteDescription(
2169 std::unique_ptr<SessionDescriptionInterface> desc,
2170 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002171 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002172
nisse7ce109a2017-01-31 00:57:56 -08002173 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002174 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002175 return;
2176 }
Steve Anton8a006912017-12-04 15:25:56 -08002177
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002178 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002179 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002180 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181 return;
2182 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002183
Steve Anton80dd7b52018-02-16 17:08:42 -08002184 // If a session error has occurred the PeerConnection is in a possibly
2185 // inconsistent state so fail right away.
2186 if (session_error() != SessionError::kNone) {
2187 std::string error_message = GetSessionErrorMsg();
2188 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2189 observer->OnSetRemoteDescriptionComplete(
2190 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2191 return;
2192 }
Steve Anton71439a62018-02-15 11:53:06 -08002193
Steve Antonba42e992018-04-09 14:10:01 -07002194 if (desc->GetType() == SdpType::kOffer) {
2195 // Report to UMA the format of the received offer.
2196 ReportSdpFormatReceived(*desc);
2197 }
2198
Steve Anton80dd7b52018-02-16 17:08:42 -08002199 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002200 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002201 std::string error_message = GetSetDescriptionErrorMessage(
2202 cricket::CS_REMOTE, desc->GetType(), error);
2203 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002204 observer->OnSetRemoteDescriptionComplete(
2205 RTCError(error.type(), std::move(error_message)));
2206 return;
2207 }
Steve Anton71439a62018-02-15 11:53:06 -08002208
Steve Anton80dd7b52018-02-16 17:08:42 -08002209 // Grab the description type before moving ownership to
2210 // ApplyRemoteDescription, which may destroy it before returning.
2211 const SdpType type = desc->GetType();
2212
2213 error = ApplyRemoteDescription(std::move(desc));
2214 // |desc| may be destroyed at this point.
2215
2216 if (!error.ok()) {
2217 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2218 // inconsistent state, so act conservatively here and set the session error
2219 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2220 SetSessionError(SessionError::kContent, error.message());
2221 std::string error_message =
2222 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2223 RTC_LOG(LS_ERROR) << error_message;
2224 observer->OnSetRemoteDescriptionComplete(
2225 RTCError(error.type(), std::move(error_message)));
2226 return;
2227 }
2228 RTC_DCHECK(remote_description());
2229
2230 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002231 // TODO(deadbeef): We already had to hop to the network thread for
2232 // MaybeStartGathering...
2233 network_thread()->Invoke<void>(
2234 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2235 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002236 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002237 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002238 }
2239
2240 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002241 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002242}
2243
2244RTCError PeerConnection::ApplyRemoteDescription(
2245 std::unique_ptr<SessionDescriptionInterface> desc) {
2246 RTC_DCHECK_RUN_ON(signaling_thread());
2247 RTC_DCHECK(desc);
2248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 // Update stats here so that we have the most recent stats for tracks and
2250 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002251 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002252
Steve Antondcc3c022017-12-22 16:02:54 -08002253 // Take a reference to the old remote description since it's used below to
2254 // compare against the new remote description. When setting the new remote
2255 // description, grab ownership of the replaced session description in case it
2256 // is the same as |old_remote_description|, to keep it alive for the duration
2257 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002258 const SessionDescriptionInterface* old_remote_description =
2259 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002260 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002261 SdpType type = desc->GetType();
2262 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002263 replaced_remote_description = pending_remote_description_
2264 ? std::move(pending_remote_description_)
2265 : std::move(current_remote_description_);
2266 current_remote_description_ = std::move(desc);
2267 pending_remote_description_ = nullptr;
2268 current_local_description_ = std::move(pending_local_description_);
2269 } else {
2270 replaced_remote_description = std::move(pending_remote_description_);
2271 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002272 }
Steve Anton8a006912017-12-04 15:25:56 -08002273 // The session description to apply now must be accessed by
2274 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002275 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002276
Zhi Huange830e682018-03-30 10:48:35 -07002277 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2278 if (!error.ok()) {
2279 return error;
2280 }
Steve Anton8a006912017-12-04 15:25:56 -08002281 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002282 if (IsUnifiedPlan()) {
2283 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002284 cricket::CS_REMOTE, *remote_description(), local_description(),
2285 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002286 if (!error.ok()) {
2287 return error;
2288 }
Steve Antondcc3c022017-12-22 16:02:54 -08002289 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002290 // Media channels will be created only when offer is set. These may use new
2291 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002292 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002293 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002294 // description is applied. Restore back to old description.
2295 RTCError error = CreateChannels(*remote_description()->description());
2296 if (!error.ok()) {
2297 return error;
2298 }
2299 }
Steve Antondcc3c022017-12-22 16:02:54 -08002300 // Remove unused channels if MediaContentDescription is rejected.
2301 RemoveUnusedChannels(remote_description()->description());
2302 }
Steve Anton8a006912017-12-04 15:25:56 -08002303
Zhi Huange830e682018-03-30 10:48:35 -07002304 // NOTE: Candidates allocation will be initiated only when
2305 // SetLocalDescription is called.
2306 error = UpdateSessionState(type, cricket::CS_REMOTE,
2307 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002308 if (!error.ok()) {
2309 return error;
2310 }
2311
2312 if (local_description() &&
2313 !UseCandidatesInSessionDescription(remote_description())) {
2314 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2315 }
2316
2317 if (old_remote_description) {
2318 for (const cricket::ContentInfo& content :
2319 old_remote_description->description()->contents()) {
2320 // Check if this new SessionDescription contains new ICE ufrag and
2321 // password that indicates the remote peer requests an ICE restart.
2322 // TODO(deadbeef): When we start storing both the current and pending
2323 // remote description, this should reset pending_ice_restarts and compare
2324 // against the current description.
2325 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2326 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002327 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002328 pending_ice_restarts_.insert(content.name);
2329 }
2330 } else {
2331 // We retain all received candidates only if ICE is not restarted.
2332 // When ICE is restarted, all previous candidates belong to an old
2333 // generation and should not be kept.
2334 // TODO(deadbeef): This goes against the W3C spec which says the remote
2335 // description should only contain candidates from the last set remote
2336 // description plus any candidates added since then. We should remove
2337 // this once we're sure it won't break anything.
2338 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2339 old_remote_description, content.name, mutable_remote_description());
2340 }
2341 }
2342 }
2343
2344 if (session_error() != SessionError::kNone) {
2345 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2346 }
2347
2348 // Set the the ICE connection state to connecting since the connection may
2349 // become writable with peer reflexive candidates before any remote candidate
2350 // is signaled.
2351 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2352 // is to have a new signal the indicates a change in checking state from the
2353 // transport and expose a new checking() member from transport that can be
2354 // read to determine the current checking state. The existing SignalConnecting
2355 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002356 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002357 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002358 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2359 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2360 }
2361
deadbeefab9b2d12015-10-14 11:33:11 -07002362 // If setting the description decided our SSL role, allocate any necessary
2363 // SCTP sids.
2364 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002365 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002366 AllocateSctpSids(role);
2367 }
2368
Steve Antondcc3c022017-12-22 16:02:54 -08002369 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002370 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002371 now_receiving_transceivers;
2372 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2373 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002374 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002375 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002376 for (auto transceiver : transceivers_) {
2377 const ContentInfo* content =
2378 FindMediaSectionForTransceiver(transceiver, remote_description());
2379 if (!content) {
2380 continue;
2381 }
2382 const MediaContentDescription* media_desc = content->media_description();
2383 RtpTransceiverDirection local_direction =
2384 RtpTransceiverDirectionReversed(media_desc->direction());
2385 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2386 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2387 // transceiver's current direction is neither sendrecv nor recvonly,
2388 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002389 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002390 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002391 // The remote description has signaled the stream IDs.
2392 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002393 }
Steve Antondcc3c022017-12-22 16:02:54 -08002394 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2395 (!transceiver->current_direction() ||
2396 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002397 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002398 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002399 << content->name << " (added to "
2400 << GetStreamIdsString(stream_ids) << ").";
2401
2402 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2403 for (const std::string& stream_id : stream_ids) {
2404 rtc::scoped_refptr<MediaStreamInterface> stream =
2405 remote_streams_->find(stream_id);
2406 if (!stream) {
2407 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2408 MediaStream::Create(stream_id));
2409 remote_streams_->AddStream(stream);
2410 added_streams.push_back(stream);
2411 }
2412 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002413 }
Steve Anton3172c032018-05-03 15:30:18 -07002414 // This will add the remote track to the streams.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002415 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002416 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002417 }
2418 // If direction is sendonly or inactive, and transceiver's current
2419 // direction is neither sendonly nor inactive, process the removal of a
2420 // remote track for the media description.
2421 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002422 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002423 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002424 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2425 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002426 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2427 transceiver->internal()->receiver_internal()->streams();
2428 // This will remove the remote track from the streams.
Steve Antonef65ef12018-01-10 17:15:20 -08002429 transceiver->internal()->receiver_internal()->SetStreams({});
Steve Anton3172c032018-05-03 15:30:18 -07002430 no_longer_receiving_transceivers.push_back(transceiver);
2431 // Remove any streams that no longer have tracks.
2432 for (auto stream : media_streams) {
2433 if (stream->GetAudioTracks().empty() &&
2434 stream->GetVideoTracks().empty()) {
2435 remote_streams_->RemoveStream(stream);
2436 removed_streams.push_back(stream);
2437 }
2438 }
Steve Antondcc3c022017-12-22 16:02:54 -08002439 }
2440 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2441 transceiver->internal()->set_current_direction(local_direction);
2442 }
2443 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002444 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2445 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002446 transceiver->Stop();
2447 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002448 if (!content->rejected &&
2449 RtpTransceiverDirectionHasRecv(local_direction)) {
2450 // Set ssrc to 0 in the case of an unsignalled ssrc.
2451 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002452 if (!media_desc->streams().empty() &&
2453 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002454 ssrc = media_desc->streams()[0].first_ssrc();
2455 }
2456 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002457 }
Steve Antondcc3c022017-12-22 16:02:54 -08002458 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002459 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002460 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002461 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002462 observer_->OnTrack(transceiver);
2463 observer_->OnAddTrack(transceiver->receiver(),
2464 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002465 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002466 for (auto stream : added_streams) {
2467 observer_->OnAddStream(stream);
2468 }
Steve Anton3172c032018-05-03 15:30:18 -07002469 for (auto transceiver : no_longer_receiving_transceivers) {
2470 observer_->OnRemoveTrack(transceiver->receiver());
2471 }
2472 for (auto stream : removed_streams) {
2473 observer_->OnRemoveStream(stream);
2474 }
Steve Antondcc3c022017-12-22 16:02:54 -08002475 }
2476
Henrik Boströmfdb92012017-11-09 19:55:44 +01002477 const cricket::ContentInfo* audio_content =
2478 GetFirstAudioContent(remote_description()->description());
2479 const cricket::ContentInfo* video_content =
2480 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002481 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002482 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002483 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002484 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002485 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002486 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002487
2488 // Check if the descriptions include streams, just in case the peer supports
2489 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002490 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002491 (audio_desc && !audio_desc->streams().empty()) ||
2492 (video_desc && !video_desc->streams().empty())) {
2493 remote_peer_supports_msid_ = true;
2494 }
deadbeefab9b2d12015-10-14 11:33:11 -07002495
2496 // We wait to signal new streams until we finish processing the description,
2497 // since only at that point will new streams have all their tracks.
2498 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2499
Steve Antondcc3c022017-12-22 16:02:54 -08002500 if (!IsUnifiedPlan()) {
2501 // TODO(steveanton): When removing RTP senders/receivers in response to a
2502 // rejected media section, there is some cleanup logic that expects the
2503 // voice/ video channel to still be set. But in this method the voice/video
2504 // channel would have been destroyed by the SetRemoteDescription caller
2505 // above so the cleanup that relies on them fails to run. The RemoveSenders
2506 // calls should be moved to right before the DestroyChannel calls to fix
2507 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002508
Steve Antondcc3c022017-12-22 16:02:54 -08002509 // Find all audio rtp streams and create corresponding remote AudioTracks
2510 // and MediaStreams.
2511 if (audio_content) {
2512 if (audio_content->rejected) {
2513 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2514 } else {
2515 bool default_audio_track_needed =
2516 !remote_peer_supports_msid_ &&
2517 RtpTransceiverDirectionHasSend(audio_desc->direction());
2518 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2519 default_audio_track_needed, audio_desc->type(),
2520 new_streams);
2521 }
deadbeeffaac4972015-11-12 15:33:07 -08002522 }
deadbeefab9b2d12015-10-14 11:33:11 -07002523
Steve Antondcc3c022017-12-22 16:02:54 -08002524 // Find all video rtp streams and create corresponding remote VideoTracks
2525 // and MediaStreams.
2526 if (video_content) {
2527 if (video_content->rejected) {
2528 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2529 } else {
2530 bool default_video_track_needed =
2531 !remote_peer_supports_msid_ &&
2532 RtpTransceiverDirectionHasSend(video_desc->direction());
2533 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2534 default_video_track_needed, video_desc->type(),
2535 new_streams);
2536 }
deadbeeffaac4972015-11-12 15:33:07 -08002537 }
deadbeefab9b2d12015-10-14 11:33:11 -07002538
Steve Antondcc3c022017-12-22 16:02:54 -08002539 // Update the DataChannels with the information from the remote peer.
2540 if (data_desc) {
2541 if (rtc::starts_with(data_desc->protocol().data(),
2542 cricket::kMediaProtocolRtpPrefix)) {
2543 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2544 }
deadbeefab9b2d12015-10-14 11:33:11 -07002545 }
deadbeefab9b2d12015-10-14 11:33:11 -07002546
Steve Antondcc3c022017-12-22 16:02:54 -08002547 // Iterate new_streams and notify the observer about new MediaStreams.
2548 for (size_t i = 0; i < new_streams->count(); ++i) {
2549 MediaStreamInterface* new_stream = new_streams->at(i);
2550 stats_->AddStream(new_stream);
2551 observer_->OnAddStream(
2552 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2553 }
deadbeefab9b2d12015-10-14 11:33:11 -07002554
Steve Antondcc3c022017-12-22 16:02:54 -08002555 UpdateEndedRemoteMediaStreams();
2556 }
deadbeefab9b2d12015-10-14 11:33:11 -07002557
Steve Anton8a006912017-12-04 15:25:56 -08002558 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002559}
2560
Steve Antondcc3c022017-12-22 16:02:54 -08002561RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2562 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002563 const SessionDescriptionInterface& new_session,
2564 const SessionDescriptionInterface* old_local_description,
2565 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002566 RTC_DCHECK(IsUnifiedPlan());
2567
Steve Anton7464fca2018-01-19 11:10:37 -08002568 const cricket::ContentGroup* bundle_group = nullptr;
2569 if (new_session.GetType() == SdpType::kOffer) {
2570 auto bundle_group_or_error =
2571 GetEarlyBundleGroup(*new_session.description());
2572 if (!bundle_group_or_error.ok()) {
2573 return bundle_group_or_error.MoveError();
2574 }
2575 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002576 }
Steve Antondcc3c022017-12-22 16:02:54 -08002577
Steve Antondcc3c022017-12-22 16:02:54 -08002578 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002579 for (size_t i = 0; i < new_contents.size(); ++i) {
2580 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002581 cricket::MediaType media_type = new_content.media_description()->type();
2582 seen_mids_.insert(new_content.name);
2583 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2584 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002585 const cricket::ContentInfo* old_local_content = nullptr;
2586 if (old_local_description &&
2587 i < old_local_description->description()->contents().size()) {
2588 old_local_content =
2589 &old_local_description->description()->contents()[i];
2590 }
2591 const cricket::ContentInfo* old_remote_content = nullptr;
2592 if (old_remote_description &&
2593 i < old_remote_description->description()->contents().size()) {
2594 old_remote_content =
2595 &old_remote_description->description()->contents()[i];
2596 }
Steve Antondcc3c022017-12-22 16:02:54 -08002597 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002598 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2599 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002600 if (!transceiver_or_error.ok()) {
2601 return transceiver_or_error.MoveError();
2602 }
2603 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002604 RTCError error =
2605 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2606 if (!error.ok()) {
2607 return error;
2608 }
2609 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002610 if (GetDataMid() && new_content.name != *GetDataMid()) {
2611 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002612 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2613 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002614 continue;
2615 }
2616 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2617 if (!error.ok()) {
2618 return error;
2619 }
Steve Antondcc3c022017-12-22 16:02:54 -08002620 } else {
2621 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2622 "Unknown section type.");
2623 }
2624 }
2625
2626 return RTCError::OK();
2627}
2628
2629RTCError PeerConnection::UpdateTransceiverChannel(
2630 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2631 transceiver,
2632 const cricket::ContentInfo& content,
2633 const cricket::ContentGroup* bundle_group) {
2634 RTC_DCHECK(IsUnifiedPlan());
2635 RTC_DCHECK(transceiver);
2636 cricket::BaseChannel* channel = transceiver->internal()->channel();
2637 if (content.rejected) {
2638 if (channel) {
2639 transceiver->internal()->SetChannel(nullptr);
2640 DestroyBaseChannel(channel);
2641 }
2642 } else {
2643 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002644 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002645 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002646 } else {
Steve Anton69470252018-02-09 11:43:08 -08002647 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002648 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002649 }
2650 if (!channel) {
2651 LOG_AND_RETURN_ERROR(
2652 RTCErrorType::INTERNAL_ERROR,
2653 "Failed to create channel for mid=" + content.name);
2654 }
2655 transceiver->internal()->SetChannel(channel);
2656 }
2657 }
2658 return RTCError::OK();
2659}
2660
Steve Antonfa2260d2017-12-28 16:38:23 -08002661RTCError PeerConnection::UpdateDataChannel(
2662 cricket::ContentSource source,
2663 const cricket::ContentInfo& content,
2664 const cricket::ContentGroup* bundle_group) {
2665 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002666 // If data channels are disabled, ignore this media section. CreateAnswer
2667 // will take care of rejecting it.
2668 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002669 }
2670 if (content.rejected) {
2671 DestroyDataChannel();
2672 } else {
2673 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002674 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002675 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2676 "Failed to create data channel.");
2677 }
2678 }
2679 if (source == cricket::CS_REMOTE) {
2680 const MediaContentDescription* data_desc = content.media_description();
2681 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2682 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2683 }
2684 }
2685 }
2686 return RTCError::OK();
2687}
2688
Steve Antondcc3c022017-12-22 16:02:54 -08002689RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2690PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002691 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002692 size_t mline_index,
2693 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002694 const ContentInfo* old_local_content,
2695 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002696 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002697 // If this is an offer then the m= section might be recycled. If the m=
2698 // section is being recycled (defined as: rejected in the current local or
2699 // remote description and not rejected in new description), dissociate the
2700 // currently associated RtpTransceiver by setting its mid property to null,
2701 // and discard the mapping between the transceiver and its m= section index.
2702 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2703 old_remote_content)) {
2704 // We want to dissociate the transceiver that has the rejected mid.
2705 const std::string& old_mid =
2706 (old_local_content && old_local_content->rejected)
2707 ? old_local_content->name
2708 : old_remote_content->name;
2709 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002710 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002711 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2712 << " since the media section is being recycled.";
Steve Antondcc3c022017-12-22 16:02:54 -08002713 old_transceiver->internal()->set_mid(rtc::nullopt);
2714 old_transceiver->internal()->set_mline_index(rtc::nullopt);
2715 }
2716 }
2717 const MediaContentDescription* media_desc = content.media_description();
2718 auto transceiver = GetAssociatedTransceiver(content.name);
2719 if (source == cricket::CS_LOCAL) {
2720 // Find the RtpTransceiver that corresponds to this m= section, using the
2721 // mapping between transceivers and m= section indices established when
2722 // creating the offer.
2723 if (!transceiver) {
2724 transceiver = GetTransceiverByMLineIndex(mline_index);
2725 }
2726 if (!transceiver) {
2727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2728 "Unknown transceiver");
2729 }
2730 } else {
2731 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2732 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2733 // of the same type...
2734 if (!transceiver &&
2735 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2736 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2737 }
2738 // If no RtpTransceiver was found in the previous step, create one with a
2739 // recvonly direction.
2740 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002741 RTC_LOG(LS_INFO) << "Adding "
2742 << cricket::MediaTypeToString(media_desc->type())
2743 << " transceiver for MID=" << content.name
2744 << " at i=" << mline_index
2745 << " in response to the remote description.";
Steve Anton02ee47c2018-01-10 16:26:06 -08002746 auto sender =
2747 CreateSender(media_desc->type(), nullptr, {rtc::CreateRandomUuid()});
Steve Anton5f94aa22018-02-01 10:58:30 -08002748 std::string receiver_id;
2749 if (!media_desc->streams().empty()) {
2750 receiver_id = media_desc->streams()[0].id;
2751 } else {
2752 receiver_id = rtc::CreateRandomUuid();
2753 }
2754 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002755 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002756 transceiver->internal()->set_direction(
2757 RtpTransceiverDirection::kRecvOnly);
2758 }
2759 }
2760 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002761 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002762 LOG_AND_RETURN_ERROR(
2763 RTCErrorType::INVALID_PARAMETER,
2764 "Transceiver type does not match media description type.");
2765 }
2766 // Associate the found or created RtpTransceiver with the m= section by
2767 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2768 // section, and establish a mapping between the transceiver and the index of
2769 // the m= section.
2770 transceiver->internal()->set_mid(content.name);
2771 transceiver->internal()->set_mline_index(mline_index);
2772 return std::move(transceiver);
2773}
2774
2775rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2776PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2777 RTC_DCHECK(IsUnifiedPlan());
2778 for (auto transceiver : transceivers_) {
2779 if (transceiver->mid() == mid) {
2780 return transceiver;
2781 }
2782 }
2783 return nullptr;
2784}
2785
2786rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2787PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2788 RTC_DCHECK(IsUnifiedPlan());
2789 for (auto transceiver : transceivers_) {
2790 if (transceiver->internal()->mline_index() == mline_index) {
2791 return transceiver;
2792 }
2793 }
2794 return nullptr;
2795}
2796
2797rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2798PeerConnection::FindAvailableTransceiverToReceive(
2799 cricket::MediaType media_type) const {
2800 RTC_DCHECK(IsUnifiedPlan());
2801 // From JSEP section 5.10 (Applying a Remote Description):
2802 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2803 // the same type that were added to the PeerConnection by addTrack and are not
2804 // associated with any m= section and are not stopped, find the first such
2805 // RtpTransceiver.
2806 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002807 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002808 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2809 !transceiver->stopped()) {
2810 return transceiver;
2811 }
2812 }
2813 return nullptr;
2814}
2815
Steve Antoned10bd92017-12-05 10:52:59 -08002816const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2817 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2818 transceiver,
2819 const SessionDescriptionInterface* sdesc) const {
2820 RTC_DCHECK(transceiver);
2821 RTC_DCHECK(sdesc);
2822 if (IsUnifiedPlan()) {
2823 if (!transceiver->internal()->mid()) {
2824 // This transceiver is not associated with a media section yet.
2825 return nullptr;
2826 }
2827 return sdesc->description()->GetContentByName(
2828 *transceiver->internal()->mid());
2829 } else {
2830 // Plan B only allows at most one audio and one video section, so use the
2831 // first media section of that type.
2832 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002833 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002834 }
2835}
2836
deadbeef46c73892016-11-16 19:42:04 -08002837PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2838 return configuration_;
2839}
2840
deadbeef293e9262017-01-11 12:28:30 -08002841bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2842 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002843 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08002844
Steve Antonc79268f2018-04-24 09:54:10 -07002845 if (IsClosed()) {
2846 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2847 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2848 }
2849
Qingsi Wanga2d60672018-04-11 16:57:45 -07002850 // According to JSEP, after setLocalDescription, changing the candidate pool
2851 // size is not allowed, and changing the set of ICE servers will not result
2852 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002853 if (local_description() && configuration.ice_candidate_pool_size !=
2854 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002855 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2856 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002857 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002858 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002859
deadbeef293e9262017-01-11 12:28:30 -08002860 // The simplest (and most future-compatible) way to tell if the config was
2861 // modified in an invalid way is to copy each property we do support
2862 // modifying, then use operator==. There are far more properties we don't
2863 // support modifying than those we do, and more could be added.
2864 RTCConfiguration modified_config = configuration_;
2865 modified_config.servers = configuration.servers;
2866 modified_config.type = configuration.type;
2867 modified_config.ice_candidate_pool_size =
2868 configuration.ice_candidate_pool_size;
2869 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002870 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002871 modified_config.ice_check_interval_strong_connectivity =
2872 configuration.ice_check_interval_strong_connectivity;
2873 modified_config.ice_check_interval_weak_connectivity =
2874 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002875 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2876 modified_config.ice_unwritable_min_checks =
2877 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002878 modified_config.stun_candidate_keepalive_interval =
2879 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002880 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002881 modified_config.network_preference = configuration.network_preference;
deadbeef293e9262017-01-11 12:28:30 -08002882 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002883 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002884 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2885 }
2886
Steve Anton038834f2017-07-14 15:59:59 -07002887 // Validate the modified configuration.
2888 RTCError validate_error = ValidateConfiguration(modified_config);
2889 if (!validate_error.ok()) {
2890 return SafeSetError(std::move(validate_error), error);
2891 }
2892
deadbeef293e9262017-01-11 12:28:30 -08002893 // Note that this isn't possible through chromium, since it's an unsigned
2894 // short in WebIDL.
2895 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002896 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002897 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2898 }
2899
2900 // Parse ICE servers before hopping to network thread.
2901 cricket::ServerAddresses stun_servers;
2902 std::vector<cricket::RelayServerConfig> turn_servers;
2903 RTCErrorType parse_error =
2904 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2905 if (parse_error != RTCErrorType::NONE) {
2906 return SafeSetError(parse_error, error);
2907 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002908 // Note if STUN or TURN servers were supplied.
2909 if (!stun_servers.empty()) {
2910 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2911 }
2912 if (!turn_servers.empty()) {
2913 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2914 }
deadbeef293e9262017-01-11 12:28:30 -08002915
2916 // In theory this shouldn't fail.
2917 if (!network_thread()->Invoke<bool>(
2918 RTC_FROM_HERE,
2919 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2920 stun_servers, turn_servers, modified_config.type,
2921 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002922 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002923 modified_config.turn_customizer,
2924 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002925 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002926 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2927 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002928
deadbeefd1a38b52016-12-10 13:15:33 -08002929 // As described in JSEP, calling setConfiguration with new ICE servers or
2930 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2931 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002932 if (modified_config.servers != configuration_.servers ||
2933 modified_config.type != configuration_.type ||
2934 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002935 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002936 }
skvladd1f5fda2017-02-03 16:54:05 -08002937
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002938 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002939
deadbeef293e9262017-01-11 12:28:30 -08002940 configuration_ = modified_config;
2941 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002942}
2943
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002944bool PeerConnection::AddIceCandidate(
2945 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002946 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002947 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002948 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002949 return false;
2950 }
Steve Antond25da372017-11-06 14:50:29 -08002951
2952 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002953 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002954 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002955 return false;
2956 }
2957
2958 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002959 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08002960 return false;
2961 }
2962
2963 bool valid = false;
2964 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2965 if (!valid) {
2966 return false;
2967 }
2968
2969 // Add this candidate to the remote session description.
2970 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002971 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08002972 return false;
2973 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002974 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08002975
2976 if (ready) {
2977 return UseCandidate(ice_candidate);
2978 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002979 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002980 return true;
2981 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002982}
2983
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002984bool PeerConnection::RemoveIceCandidates(
2985 const std::vector<cricket::Candidate>& candidates) {
2986 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002987 if (IsClosed()) {
2988 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2989 return false;
2990 }
2991
Steve Antond25da372017-11-06 14:50:29 -08002992 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002993 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
2994 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002995 return false;
2996 }
2997
2998 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002999 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003000 return false;
3001 }
3002
3003 size_t number_removed =
3004 mutable_remote_description()->RemoveCandidates(candidates);
3005 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003006 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003007 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003008 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003009 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003010 }
3011
3012 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003013 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3014 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003015 RTC_LOG(LS_ERROR)
3016 << "RemoveIceCandidates: Error when removing remote candidates: "
3017 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003018 }
3019 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003020}
3021
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003022void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003023 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003024 network_thread()->Invoke<void>(
3025 RTC_FROM_HERE,
3026 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
3027 // Send information about IPv4/IPv6 status.
3028 if (uma_observer_) {
3029 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3030 uma_observer_->IncrementEnumCounter(
3031 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3032 kPeerConnectionAddressFamilyCounter_Max);
3033 } else {
3034 uma_observer_->IncrementEnumCounter(
3035 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3036 kPeerConnectionAddressFamilyCounter_Max);
3037 }
3038 }
3039}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003040
Qingsi Wanga2d60672018-04-11 16:57:45 -07003041void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3042 RTC_DCHECK(network_thread()->IsCurrent());
3043 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003044 if (transport_controller_) {
3045 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003046 }
3047
3048 for (auto transceiver : transceivers_) {
3049 auto* channel = transceiver->internal()->channel();
3050 if (channel) {
3051 channel->SetMetricsObserver(uma_observer_);
3052 }
3053 }
3054
deadbeef293e9262017-01-11 12:28:30 -08003055 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003056 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003057 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003058}
3059
Niels Möller0c4f7be2018-05-07 14:01:37 +02003060RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003061 if (!worker_thread()->IsCurrent()) {
3062 return worker_thread()->Invoke<RTCError>(
Niels Möller0c4f7be2018-05-07 14:01:37 +02003063 RTC_FROM_HERE, [&](){ return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003064 }
3065
Niels Möller0c4f7be2018-05-07 14:01:37 +02003066 const bool has_min = bitrate.min_bitrate_bps.has_value();
3067 const bool has_start = bitrate.start_bitrate_bps.has_value();
3068 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003069 if (has_min && *bitrate.min_bitrate_bps < 0) {
3070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3071 "min_bitrate_bps <= 0");
3072 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003073 if (has_start) {
3074 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003075 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003076 "start_bitrate_bps < min_bitrate_bps");
3077 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003078 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3079 "curent_bitrate_bps < 0");
3080 }
3081 }
3082 if (has_max) {
Niels Möller0c4f7be2018-05-07 14:01:37 +02003083 if (has_start &&
3084 *bitrate.max_bitrate_bps < *bitrate.start_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 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003087 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3088 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3089 "max_bitrate_bps < min_bitrate_bps");
3090 } else if (*bitrate.max_bitrate_bps < 0) {
3091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3092 "max_bitrate_bps < 0");
3093 }
3094 }
3095
zstein4b979802017-06-02 14:37:37 -07003096 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003097 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003098
3099 return RTCError::OK();
3100}
3101
Alex Narest78609d52017-10-20 10:37:47 +02003102void PeerConnection::SetBitrateAllocationStrategy(
3103 std::unique_ptr<rtc::BitrateAllocationStrategy>
3104 bitrate_allocation_strategy) {
3105 rtc::Thread* worker_thread = factory_->worker_thread();
3106 if (!worker_thread->IsCurrent()) {
3107 rtc::BitrateAllocationStrategy* strategy_raw =
3108 bitrate_allocation_strategy.release();
3109 auto functor = [this, strategy_raw]() {
3110 call_->SetBitrateAllocationStrategy(
3111 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
3112 };
3113 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3114 return;
3115 }
3116 RTC_DCHECK(call_.get());
3117 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3118}
3119
henrika5f6bf242017-11-01 11:06:56 +01003120void PeerConnection::SetAudioPlayout(bool playout) {
3121 if (!worker_thread()->IsCurrent()) {
3122 worker_thread()->Invoke<void>(
3123 RTC_FROM_HERE,
3124 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3125 return;
3126 }
3127 auto audio_state =
3128 factory_->channel_manager()->media_engine()->GetAudioState();
3129 audio_state->SetPlayout(playout);
3130}
3131
3132void PeerConnection::SetAudioRecording(bool recording) {
3133 if (!worker_thread()->IsCurrent()) {
3134 worker_thread()->Invoke<void>(
3135 RTC_FROM_HERE,
3136 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3137 return;
3138 }
3139 auto audio_state =
3140 factory_->channel_manager()->media_engine()->GetAudioState();
3141 audio_state->SetRecording(recording);
3142}
3143
Steve Anton8c0f7a72017-10-03 10:03:10 -07003144std::unique_ptr<rtc::SSLCertificate>
3145PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003146 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3147 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003148 return nullptr;
3149 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003150 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003151}
3152
Zhi Huang70b820f2018-01-27 14:16:15 -08003153std::unique_ptr<rtc::SSLCertChain>
3154PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003155 auto audio_transceiver = GetFirstAudioTransceiver();
3156 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003157 return nullptr;
3158 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003159 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003160 audio_transceiver->internal()->channel()->transport_name());
3161}
3162
3163rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3164PeerConnection::GetFirstAudioTransceiver() const {
3165 for (auto transceiver : transceivers_) {
3166 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3167 return transceiver;
3168 }
3169 }
3170 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003171}
3172
ivoc14d5dbe2016-07-04 07:06:55 -07003173bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3174 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003175 // TODO(eladalon): It would be better to not allow negative values into PC.
3176 const size_t max_size = (max_size_bytes < 0)
3177 ? RtcEventLog::kUnlimitedOutput
3178 : rtc::saturated_cast<size_t>(max_size_bytes);
3179 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003180 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
3181 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003182}
3183
Bjorn Tereliusde939432017-11-20 17:38:14 +01003184bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3185 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003186 // TODO(eladalon): In C++14, this can be done with a lambda.
3187 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003188 bool operator()() {
3189 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3190 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003191 PeerConnection* const pc;
3192 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003193 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003194 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003195 return worker_thread()->Invoke<bool>(
3196 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003197}
3198
3199void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003200 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003201 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3202}
3203
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003204const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003205 return pending_local_description_ ? pending_local_description_.get()
3206 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207}
3208
3209const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003210 return pending_remote_description_ ? pending_remote_description_.get()
3211 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003212}
3213
deadbeeffe4a8a42016-12-20 17:56:17 -08003214const SessionDescriptionInterface* PeerConnection::current_local_description()
3215 const {
Steve Anton75737c02017-11-06 10:37:17 -08003216 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003217}
3218
3219const SessionDescriptionInterface* PeerConnection::current_remote_description()
3220 const {
Steve Anton75737c02017-11-06 10:37:17 -08003221 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003222}
3223
3224const SessionDescriptionInterface* PeerConnection::pending_local_description()
3225 const {
Steve Anton75737c02017-11-06 10:37:17 -08003226 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003227}
3228
3229const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3230 const {
Steve Anton75737c02017-11-06 10:37:17 -08003231 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003232}
3233
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003235 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003236 // Update stats here so that we have the most recent stats for tracks and
3237 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003238 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239
Steve Anton75737c02017-11-06 10:37:17 -08003240 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003241 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003242
Steve Anton8af21862017-12-15 11:20:13 -08003243 for (auto transceiver : transceivers_) {
3244 transceiver->Stop();
3245 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003246
3247 // Ensure that all asynchronous stats requests are completed before destroying
3248 // the transport controller below.
3249 if (stats_collector_) {
3250 stats_collector_->WaitForPendingRequest();
3251 }
3252
3253 // Don't destroy BaseChannels until after stats has been cleaned up so that
3254 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003255 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003256
Qingsi Wang93a84392018-01-30 17:13:09 -08003257 // The event log is used in the transport controller, which must be outlived
3258 // by the former. CreateOffer by the peer connection is implemented
3259 // asynchronously and if the peer connection is closed without resetting the
3260 // WebRTC session description factory, the session description factory would
3261 // call the transport controller.
3262 webrtc_session_desc_factory_.reset();
3263 transport_controller_.reset();
3264
deadbeef42a42632017-03-10 15:18:00 -08003265 network_thread()->Invoke<void>(
3266 RTC_FROM_HERE,
3267 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3268 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003269
Steve Anton978b8762017-09-29 12:15:02 -07003270 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003271 call_.reset();
3272 // The event log must outlive call (and any other object that uses it).
3273 event_log_.reset();
3274 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003275 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003276}
3277
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003278void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003279 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003280 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3281 SetSessionDescriptionMsg* param =
3282 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3283 param->observer->OnSuccess();
3284 delete param;
3285 break;
3286 }
3287 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3288 SetSessionDescriptionMsg* param =
3289 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003290 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291 delete param;
3292 break;
3293 }
deadbeefab9b2d12015-10-14 11:33:11 -07003294 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3295 CreateSessionDescriptionMsg* param =
3296 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003297 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003298 delete param;
3299 break;
3300 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003301 case MSG_GETSTATS: {
3302 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003303 StatsReports reports;
3304 stats_->GetStats(param->track, &reports);
3305 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003306 delete param;
3307 break;
3308 }
deadbeefbd292462015-12-14 18:15:29 -08003309 case MSG_FREE_DATACHANNELS: {
3310 sctp_data_channels_to_free_.clear();
3311 break;
3312 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003313 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003314 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315 break;
3316 }
3317}
3318
Steve Antonafb0bb72018-02-20 11:35:37 -08003319cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3320 RTC_DCHECK(!IsUnifiedPlan());
3321 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3322 GetAudioTransceiver()->internal()->channel());
3323 if (voice_channel) {
3324 return voice_channel->media_channel();
3325 } else {
3326 return nullptr;
3327 }
3328}
3329
3330cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3331 RTC_DCHECK(!IsUnifiedPlan());
3332 auto* video_channel = static_cast<cricket::VideoChannel*>(
3333 GetVideoTransceiver()->internal()->channel());
3334 if (video_channel) {
3335 return video_channel->media_channel();
3336 } else {
3337 return nullptr;
3338 }
3339}
3340
Steve Anton4171afb2017-11-20 10:20:22 -08003341void PeerConnection::CreateAudioReceiver(
3342 MediaStreamInterface* stream,
3343 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003344 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3345 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003346 auto* audio_receiver = new AudioRtpReceiver(
3347 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003348 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003349 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3350 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3351 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003352 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003353 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003354 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003355}
3356
Steve Anton4171afb2017-11-20 10:20:22 -08003357void PeerConnection::CreateVideoReceiver(
3358 MediaStreamInterface* stream,
3359 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003360 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3361 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Steve Antond3679212018-01-17 17:41:02 -08003362 auto* video_receiver = new VideoRtpReceiver(
3363 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003364 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003365 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3366 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3367 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003368 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003369 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003370 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371}
3372
deadbeef70ab1a12015-09-28 16:53:55 -07003373// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3374// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003375rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003376 const RtpSenderInfo& remote_sender_info) {
3377 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3378 if (!receiver) {
3379 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3380 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003381 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003382 }
Steve Anton4171afb2017-11-20 10:20:22 -08003383 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3384 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3385 } else {
3386 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3387 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003388 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389}
3390
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003391void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3392 MediaStreamInterface* stream) {
3393 RTC_DCHECK(!IsClosed());
3394 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003395 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003396 // We already have a sender for this track, so just change the stream_id
3397 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003398 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003399 return;
3400 }
3401
3402 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003403 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003404 CreateSender(cricket::MEDIA_TYPE_AUDIO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003405 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003406 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003407 // If the sender has already been configured in SDP, we call SetSsrc,
3408 // which will connect the sender to the underlying transport. This can
3409 // occur if a local session description that contains the ID of the sender
3410 // is set before AddStream is called. It can also occur if the local
3411 // session description is not changed and RemoveStream is called, and
3412 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003413 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003414 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003415 if (sender_info) {
3416 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003417 }
3418}
3419
3420// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3421// indefinitely, when we have unified plan SDP.
3422void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3423 MediaStreamInterface* stream) {
3424 RTC_DCHECK(!IsClosed());
3425 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003426 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003427 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3428 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003429 return;
3430 }
Steve Anton4171afb2017-11-20 10:20:22 -08003431 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003432}
3433
3434void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3435 MediaStreamInterface* stream) {
3436 RTC_DCHECK(!IsClosed());
3437 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003438 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003439 // We already have a sender for this track, so just change the stream_id
3440 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003441 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003442 return;
3443 }
3444
3445 // Normal case; we've never seen this track before.
Steve Anton02ee47c2018-01-10 16:26:06 -08003446 auto new_sender =
Seth Hampson13b8bad2018-03-13 16:05:28 -07003447 CreateSender(cricket::MEDIA_TYPE_VIDEO, track, {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003448 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003449 GetVideoTransceiver()->internal()->AddSender(new_sender);
3450 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003451 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003452 if (sender_info) {
3453 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003454 }
3455}
3456
3457void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3458 MediaStreamInterface* stream) {
3459 RTC_DCHECK(!IsClosed());
3460 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003461 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003462 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3463 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003464 return;
3465 }
Steve Anton4171afb2017-11-20 10:20:22 -08003466 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003467}
3468
Steve Antonba818672017-11-06 10:21:57 -08003469void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003470 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003471 if (ice_connection_state_ == new_state) {
3472 return;
3473 }
3474
deadbeefcbecd352015-09-23 11:50:27 -07003475 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003476 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003477 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003478 return;
3479 }
Steve Antonba818672017-11-06 10:21:57 -08003480
Mirko Bonadei675513b2017-11-09 11:09:25 +01003481 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3482 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003483 RTC_DCHECK(ice_connection_state_ !=
3484 PeerConnectionInterface::kIceConnectionClosed);
3485
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003486 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003487 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003488}
3489
3490void PeerConnection::OnIceGatheringChange(
3491 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003492 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003493 if (IsClosed()) {
3494 return;
3495 }
3496 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003497 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003498}
3499
jbauch81bf7b02017-03-25 08:31:12 -07003500void PeerConnection::OnIceCandidate(
3501 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003502 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003503 if (IsClosed()) {
3504 return;
3505 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003506 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003507 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508}
3509
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003510void PeerConnection::OnIceCandidatesRemoved(
3511 const std::vector<cricket::Candidate>& candidates) {
3512 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003513 if (IsClosed()) {
3514 return;
3515 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003516 observer_->OnIceCandidatesRemoved(candidates);
3517}
3518
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003519void PeerConnection::ChangeSignalingState(
3520 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003521 RTC_DCHECK(signaling_thread()->IsCurrent());
3522 if (signaling_state_ == signaling_state) {
3523 return;
3524 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003525 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3526 << GetSignalingStateString(signaling_state_)
3527 << " New state: "
3528 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529 signaling_state_ = signaling_state;
3530 if (signaling_state == kClosed) {
3531 ice_connection_state_ = kIceConnectionClosed;
3532 observer_->OnIceConnectionChange(ice_connection_state_);
3533 if (ice_gathering_state_ != kIceGatheringComplete) {
3534 ice_gathering_state_ = kIceGatheringComplete;
3535 observer_->OnIceGatheringChange(ice_gathering_state_);
3536 }
3537 }
3538 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003539}
3540
deadbeefeb459812015-12-15 19:24:43 -08003541void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3542 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003543 if (IsClosed()) {
3544 return;
3545 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003546 AddAudioTrack(track, stream);
3547 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003548}
3549
deadbeefeb459812015-12-15 19:24:43 -08003550void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3551 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003552 if (IsClosed()) {
3553 return;
3554 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003555 RemoveAudioTrack(track, stream);
3556 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003557}
3558
3559void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3560 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003561 if (IsClosed()) {
3562 return;
3563 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003564 AddVideoTrack(track, stream);
3565 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003566}
3567
3568void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3569 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003570 if (IsClosed()) {
3571 return;
3572 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003573 RemoveVideoTrack(track, stream);
3574 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003575}
3576
Henrik Boström31638672017-11-23 17:48:32 +01003577void PeerConnection::PostSetSessionDescriptionSuccess(
3578 SetSessionDescriptionObserver* observer) {
3579 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3580 signaling_thread()->Post(RTC_FROM_HERE, this,
3581 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3582}
3583
deadbeefab9b2d12015-10-14 11:33:11 -07003584void PeerConnection::PostSetSessionDescriptionFailure(
3585 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003586 RTCError&& error) {
3587 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003588 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003589 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003590 signaling_thread()->Post(RTC_FROM_HERE, this,
3591 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003592}
3593
3594void PeerConnection::PostCreateSessionDescriptionFailure(
3595 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003596 RTCError error) {
3597 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003598 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(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_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003602}
3603
zhihuang1c378ed2017-08-17 14:10:50 -07003604void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003605 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003606 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003607 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003608
Steve Antondcc3c022017-12-22 16:02:54 -08003609 if (IsUnifiedPlan()) {
3610 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3611 } else {
3612 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3613 }
3614
Steve Antonfa2260d2017-12-28 16:38:23 -08003615 // Intentionally unset the data channel type for RTP data channel with the
3616 // second condition. Otherwise the RTP data channels would be successfully
3617 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3618 // when building with chromium. We want to leave RTP data channels broken, so
3619 // people won't try to use them.
3620 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3621 session_options->data_channel_type = data_channel_type();
3622 }
3623
Steve Antondcc3c022017-12-22 16:02:54 -08003624 // Apply ICE restart flag and renomination flag.
3625 for (auto& options : session_options->media_description_options) {
3626 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3627 options.transport_options.enable_ice_renomination =
3628 configuration_.enable_ice_renomination;
3629 }
3630
3631 session_options->rtcp_cname = rtcp_cname_;
3632 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003633 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003634}
3635
3636void PeerConnection::GetOptionsForPlanBOffer(
3637 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3638 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003639 // Figure out transceiver directional preferences.
3640 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3641 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3642
3643 // By default, generate sendrecv/recvonly m= sections.
3644 bool recv_audio = true;
3645 bool recv_video = true;
3646
3647 // By default, only offer a new m= section if we have media to send with it.
3648 bool offer_new_audio_description = send_audio;
3649 bool offer_new_video_description = send_video;
3650 bool offer_new_data_description = HasDataChannels();
3651
3652 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003653 if (offer_answer_options.offer_to_receive_audio !=
3654 RTCOfferAnswerOptions::kUndefined) {
3655 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003656 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003657 offer_new_audio_description ||
3658 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003659 }
Steve Antondcc3c022017-12-22 16:02:54 -08003660 if (offer_answer_options.offer_to_receive_video !=
3661 RTCOfferAnswerOptions::kUndefined) {
3662 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003663 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003664 offer_new_video_description ||
3665 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003666 }
3667
3668 rtc::Optional<size_t> audio_index;
3669 rtc::Optional<size_t> video_index;
3670 rtc::Optional<size_t> data_index;
3671 // If a current description exists, generate m= sections in the same order,
3672 // using the first audio/video/data section that appears and rejecting
3673 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003674 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003675 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003676 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003677 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3678 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3679 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003680 }
3681
zhihuang1c378ed2017-08-17 14:10:50 -07003682 // Add audio/video/data m= sections to the end if needed.
3683 if (!audio_index && offer_new_audio_description) {
3684 session_options->media_description_options.push_back(
3685 cricket::MediaDescriptionOptions(
3686 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003687 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3688 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003689 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003690 }
zhihuang1c378ed2017-08-17 14:10:50 -07003691 if (!video_index && offer_new_video_description) {
3692 session_options->media_description_options.push_back(
3693 cricket::MediaDescriptionOptions(
3694 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003695 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3696 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003697 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003698 }
zhihuang1c378ed2017-08-17 14:10:50 -07003699 if (!data_index && offer_new_data_description) {
3700 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003701 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003702 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003703 }
3704
3705 cricket::MediaDescriptionOptions* audio_media_description_options =
3706 !audio_index ? nullptr
3707 : &session_options->media_description_options[*audio_index];
3708 cricket::MediaDescriptionOptions* video_media_description_options =
3709 !video_index ? nullptr
3710 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003711
Steve Anton4171afb2017-11-20 10:20:22 -08003712 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003713 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003714}
3715
3716// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3717// and return a reference to it.
3718// Generated MIDs should be no more than 3 bytes long to take up less space in
3719// the RTP packet.
3720static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3721 RTC_DCHECK(used_mids);
3722 // We're boring: just generate MIDs 0, 1, 2, ...
3723 size_t i = 0;
3724 std::set<std::string>::iterator it;
3725 bool inserted;
3726 do {
3727 std::string mid = rtc::ToString(i++);
3728 auto insert_result = used_mids->insert(mid);
3729 it = insert_result.first;
3730 inserted = insert_result.second;
3731 } while (!inserted);
3732 return *it;
3733}
3734
3735static cricket::MediaDescriptionOptions
3736GetMediaDescriptionOptionsForTransceiver(
3737 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3738 transceiver,
3739 const std::string& mid) {
3740 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003741 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003742 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003743 // This behavior is specified in JSEP. The gist is that:
3744 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3745 // sendrecv.
3746 // 2. If the MSID is included, then it must be included in any subsequent
3747 // offer/answer exactly the same until the RtpTransceiver is stopped.
3748 if (!transceiver->stopped() &&
3749 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3750 transceiver->internal()->has_ever_been_used_to_send())) {
3751 cricket::SenderOptions sender_options;
3752 sender_options.track_id = transceiver->sender()->id();
3753 sender_options.stream_ids = transceiver->sender()->stream_ids();
3754 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3755 // set in the RTP parameters when the transceiver was added.
3756 sender_options.num_sim_layers = 1;
3757 media_description_options.sender_options.push_back(sender_options);
3758 }
Steve Antondcc3c022017-12-22 16:02:54 -08003759 return media_description_options;
3760}
3761
3762void PeerConnection::GetOptionsForUnifiedPlanOffer(
3763 const RTCOfferAnswerOptions& offer_answer_options,
3764 cricket::MediaSessionOptions* session_options) {
3765 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3766 // Offers) and 5.2.2 (Subsequent Offers).
3767 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3768 const ContentInfos& local_contents =
3769 (local_description() ? local_description()->description()->contents()
3770 : ContentInfos());
3771 const ContentInfos& remote_contents =
3772 (remote_description() ? remote_description()->description()->contents()
3773 : ContentInfos());
3774 // The mline indices that can be recycled. New transceivers should reuse these
3775 // slots first.
3776 std::queue<size_t> recycleable_mline_indices;
3777 // Track the MIDs used in previous offer/answer exchanges and the current
3778 // offer so that new, unique MIDs are generated.
3779 std::set<std::string> used_mids = seen_mids_;
3780 // First, go through each media section that exists in either the local or
3781 // remote description and generate a media section in this offer for the
3782 // associated transceiver. If a media section can be recycled, generate a
3783 // default, rejected media section here that can be later overwritten.
3784 for (size_t i = 0;
3785 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3786 // Either |local_content| or |remote_content| is non-null.
3787 const ContentInfo* local_content =
3788 (i < local_contents.size() ? &local_contents[i] : nullptr);
3789 const ContentInfo* remote_content =
3790 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3791 bool had_been_rejected = (local_content && local_content->rejected) ||
3792 (remote_content && remote_content->rejected);
3793 const std::string& mid =
3794 (local_content ? local_content->name : remote_content->name);
3795 cricket::MediaType media_type =
3796 (local_content ? local_content->media_description()->type()
3797 : remote_content->media_description()->type());
3798 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3799 media_type == cricket::MEDIA_TYPE_VIDEO) {
3800 auto transceiver = GetAssociatedTransceiver(mid);
3801 RTC_CHECK(transceiver);
3802 // A media section is considered eligible for recycling if it is marked as
3803 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003804 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003805 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003806 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3807 RtpTransceiverDirection::kInactive,
3808 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003809 recycleable_mline_indices.push(i);
3810 } else {
3811 session_options->media_description_options.push_back(
3812 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3813 // CreateOffer shouldn't really cause any state changes in
3814 // PeerConnection, but we need a way to match new transceivers to new
3815 // media sections in SetLocalDescription and JSEP specifies this is done
3816 // by recording the index of the media section generated for the
3817 // transceiver in the offer.
3818 transceiver->internal()->set_mline_index(i);
3819 }
3820 } else {
3821 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003822 RTC_CHECK(GetDataMid());
3823 if (had_been_rejected || mid != *GetDataMid()) {
3824 session_options->media_description_options.push_back(
3825 GetMediaDescriptionOptionsForRejectedData(mid));
3826 } else {
3827 session_options->media_description_options.push_back(
3828 GetMediaDescriptionOptionsForActiveData(mid));
3829 }
Steve Antondcc3c022017-12-22 16:02:54 -08003830 }
3831 }
3832 // Next, look for transceivers that are newly added (that is, are not stopped
3833 // and not associated). Reuse media sections marked as recyclable first,
3834 // otherwise append to the end of the offer. New media sections should be
3835 // added in the order they were added to the PeerConnection.
3836 for (auto transceiver : transceivers_) {
3837 if (transceiver->mid() || transceiver->stopped()) {
3838 continue;
3839 }
3840 size_t mline_index;
3841 if (!recycleable_mline_indices.empty()) {
3842 mline_index = recycleable_mline_indices.front();
3843 recycleable_mline_indices.pop();
3844 session_options->media_description_options[mline_index] =
3845 GetMediaDescriptionOptionsForTransceiver(transceiver,
3846 AllocateMid(&used_mids));
3847 } else {
3848 mline_index = session_options->media_description_options.size();
3849 session_options->media_description_options.push_back(
3850 GetMediaDescriptionOptionsForTransceiver(transceiver,
3851 AllocateMid(&used_mids)));
3852 }
3853 // See comment above for why CreateOffer changes the transceiver's state.
3854 transceiver->internal()->set_mline_index(mline_index);
3855 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003856 // Lastly, add a m-section if we have local data channels and an m section
3857 // does not already exist.
3858 if (!GetDataMid() && HasDataChannels()) {
3859 session_options->media_description_options.push_back(
3860 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3861 }
Steve Antondcc3c022017-12-22 16:02:54 -08003862}
3863
3864void PeerConnection::GetOptionsForAnswer(
3865 const RTCOfferAnswerOptions& offer_answer_options,
3866 cricket::MediaSessionOptions* session_options) {
3867 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3868
3869 if (IsUnifiedPlan()) {
3870 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3871 } else {
3872 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3873 }
3874
Steve Antonfa2260d2017-12-28 16:38:23 -08003875 // Intentionally unset the data channel type for RTP data channel. Otherwise
3876 // the RTP data channels would be successfully negotiated by default and the
3877 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3878 // We want to leave RTP data channels broken, so people won't try to use them.
3879 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3880 session_options->data_channel_type = data_channel_type();
3881 }
3882
Steve Antondcc3c022017-12-22 16:02:54 -08003883 // Apply ICE renomination flag.
3884 for (auto& options : session_options->media_description_options) {
3885 options.transport_options.enable_ice_renomination =
3886 configuration_.enable_ice_renomination;
3887 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003888
3889 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003890 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003891 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003892}
3893
Steve Antondcc3c022017-12-22 16:02:54 -08003894void PeerConnection::GetOptionsForPlanBAnswer(
3895 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003896 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003897 // Figure out transceiver directional preferences.
3898 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3899 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3900
3901 // By default, generate sendrecv/recvonly m= sections. The direction is also
3902 // restricted by the direction in the offer.
3903 bool recv_audio = true;
3904 bool recv_video = true;
3905
3906 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003907 if (offer_answer_options.offer_to_receive_audio !=
3908 RTCOfferAnswerOptions::kUndefined) {
3909 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003910 }
Steve Antondcc3c022017-12-22 16:02:54 -08003911 if (offer_answer_options.offer_to_receive_video !=
3912 RTCOfferAnswerOptions::kUndefined) {
3913 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003914 }
3915
3916 rtc::Optional<size_t> audio_index;
3917 rtc::Optional<size_t> video_index;
3918 rtc::Optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003919
3920 // Generate m= sections that match those in the offer.
3921 // Note that mediasession.cc will handle intersection our preferred
3922 // direction with the offered direction.
3923 GenerateMediaDescriptionOptions(
3924 remote_description(),
3925 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3926 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3927 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003928
3929 cricket::MediaDescriptionOptions* audio_media_description_options =
3930 !audio_index ? nullptr
3931 : &session_options->media_description_options[*audio_index];
3932 cricket::MediaDescriptionOptions* video_media_description_options =
3933 !video_index ? nullptr
3934 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003935
Steve Anton4171afb2017-11-20 10:20:22 -08003936 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003937 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003938}
zhihuangaf388472016-11-02 16:49:48 -07003939
Steve Antondcc3c022017-12-22 16:02:54 -08003940void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3941 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3942 cricket::MediaSessionOptions* session_options) {
3943 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3944 // Answers) and 5.3.2 (Subsequent Answers).
3945 RTC_DCHECK(remote_description());
3946 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3947 for (const ContentInfo& content :
3948 remote_description()->description()->contents()) {
3949 cricket::MediaType media_type = content.media_description()->type();
3950 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3951 media_type == cricket::MEDIA_TYPE_VIDEO) {
3952 auto transceiver = GetAssociatedTransceiver(content.name);
3953 RTC_CHECK(transceiver);
3954 session_options->media_description_options.push_back(
3955 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3956 } else {
3957 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003958 // Reject all data sections if data channels are disabled.
3959 // Reject a data section if it has already been rejected.
3960 // Reject all data sections except for the first one.
3961 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3962 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003963 session_options->media_description_options.push_back(
3964 GetMediaDescriptionOptionsForRejectedData(content.name));
3965 } else {
3966 session_options->media_description_options.push_back(
3967 GetMediaDescriptionOptionsForActiveData(content.name));
3968 }
Steve Antondcc3c022017-12-22 16:02:54 -08003969 }
3970 }
htaa2a49d92016-03-04 02:51:39 -08003971}
3972
zhihuang1c378ed2017-08-17 14:10:50 -07003973void PeerConnection::GenerateMediaDescriptionOptions(
3974 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003975 RtpTransceiverDirection audio_direction,
3976 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07003977 rtc::Optional<size_t>* audio_index,
3978 rtc::Optional<size_t>* video_index,
3979 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003980 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003981 for (const cricket::ContentInfo& content :
3982 session_desc->description()->contents()) {
3983 if (IsAudioContent(&content)) {
3984 // If we already have an audio m= section, reject this extra one.
3985 if (*audio_index) {
3986 session_options->media_description_options.push_back(
3987 cricket::MediaDescriptionOptions(
3988 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003989 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003990 } else {
3991 session_options->media_description_options.push_back(
3992 cricket::MediaDescriptionOptions(
3993 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003994 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003995 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003996 }
3997 } else if (IsVideoContent(&content)) {
3998 // If we already have an video m= section, reject this extra one.
3999 if (*video_index) {
4000 session_options->media_description_options.push_back(
4001 cricket::MediaDescriptionOptions(
4002 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004003 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004004 } else {
4005 session_options->media_description_options.push_back(
4006 cricket::MediaDescriptionOptions(
4007 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004008 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004009 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004010 }
4011 } else {
4012 RTC_DCHECK(IsDataContent(&content));
4013 // If we already have an data m= section, reject this extra one.
4014 if (*data_index) {
4015 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004016 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004017 } else {
4018 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004019 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004020 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004021 }
4022 }
htaa2a49d92016-03-04 02:51:39 -08004023 }
deadbeefab9b2d12015-10-14 11:33:11 -07004024}
4025
Steve Antonfa2260d2017-12-28 16:38:23 -08004026cricket::MediaDescriptionOptions
4027PeerConnection::GetMediaDescriptionOptionsForActiveData(
4028 const std::string& mid) const {
4029 // Direction for data sections is meaningless, but legacy endpoints might
4030 // expect sendrecv.
4031 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4032 RtpTransceiverDirection::kSendRecv,
4033 /*stopped=*/false);
4034 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4035 return options;
4036}
4037
4038cricket::MediaDescriptionOptions
4039PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4040 const std::string& mid) const {
4041 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4042 RtpTransceiverDirection::kInactive,
4043 /*stopped=*/true);
4044 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4045 return options;
4046}
4047
4048rtc::Optional<std::string> PeerConnection::GetDataMid() const {
4049 switch (data_channel_type_) {
4050 case cricket::DCT_RTP:
4051 if (!rtp_data_channel_) {
4052 return rtc::nullopt;
4053 }
4054 return rtp_data_channel_->content_name();
4055 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004056 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004057 default:
4058 return rtc::nullopt;
4059 }
4060}
4061
Steve Anton4171afb2017-11-20 10:20:22 -08004062void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4063 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4064 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004065 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004066}
4067
Steve Anton4171afb2017-11-20 10:20:22 -08004068void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004069 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004070 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004071 cricket::MediaType media_type,
4072 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004073 RTC_DCHECK(!IsUnifiedPlan());
4074
Steve Anton4171afb2017-11-20 10:20:22 -08004075 std::vector<RtpSenderInfo>* current_senders =
4076 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004077
Steve Anton4171afb2017-11-20 10:20:22 -08004078 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004079 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004080 for (auto sender_it = current_senders->begin();
4081 sender_it != current_senders->end();
4082 /* incremented manually */) {
4083 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004084 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004085 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004086 std::string params_stream_id;
4087 if (params) {
4088 params_stream_id =
4089 (!params->first_stream_id().empty() ? params->first_stream_id()
4090 : kDefaultStreamId);
4091 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004092 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004093 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004094 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004095 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004096 sender_exists) {
4097 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004098 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004099 OnRemoteSenderRemoved(info, media_type);
4100 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004101 }
4102 }
4103
Steve Anton4171afb2017-11-20 10:20:22 -08004104 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004105 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004106 if (!params.has_ssrcs()) {
4107 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4108 // sender, this means it is coming from a Unified Plan endpoint,so we just
4109 // create a default.
4110 default_sender_needed = true;
4111 break;
4112 }
4113
Seth Hampson845e8782018-03-02 11:34:10 -08004114 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004115 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004116 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4117 // not supported in Plan B, we just take the first here and create the
4118 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004119 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004120 (!params.first_stream_id().empty() ? params.first_stream_id()
4121 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004122 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004123 uint32_t ssrc = params.first_ssrc();
4124
4125 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004126 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004127 if (!stream) {
4128 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004129 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004130 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004131 remote_streams_->AddStream(stream);
4132 new_streams->AddStream(stream);
4133 }
4134
Steve Anton4171afb2017-11-20 10:20:22 -08004135 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004136 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004137 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004138 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004139 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004140 }
4141 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004142
Steve Anton4171afb2017-11-20 10:20:22 -08004143 // Add default sender if necessary.
4144 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004145 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004146 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004147 if (!default_stream) {
4148 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004149 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004150 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004151 remote_streams_->AddStream(default_stream);
4152 new_streams->AddStream(default_stream);
4153 }
Steve Anton4171afb2017-11-20 10:20:22 -08004154 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4155 ? kDefaultAudioSenderId
4156 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004157 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004158 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004159 if (!default_sender_info) {
4160 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004161 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004162 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004163 }
4164 }
deadbeefab9b2d12015-10-14 11:33:11 -07004165}
4166
Steve Anton4171afb2017-11-20 10:20:22 -08004167void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4168 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004169 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4170 << " receiver for track_id=" << sender_info.sender_id
4171 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004172
Steve Anton3d954a62018-04-02 11:27:23 -07004173 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004174 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004175 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004176 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004177 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004178 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004179 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004180 }
4181}
4182
Steve Anton4171afb2017-11-20 10:20:22 -08004183void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4184 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004185 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4186 << " receiver for track_id=" << sender_info.sender_id
4187 << " and stream_id=" << sender_info.stream_id;
4188
Seth Hampson845e8782018-03-02 11:34:10 -08004189 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004190
Henrik Boström933d8b02017-10-10 10:05:16 -07004191 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004192 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004193 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4194 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004195 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004196 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004197 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004198 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004199 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004200 }
4201 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004202 // Stopping or destroying a VideoRtpReceiver will end the
4203 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004204 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004205 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004206 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004207 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004208 // There's no guarantee the track is still available, e.g. the track may
4209 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004210 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004211 }
4212 } else {
nisseede5da42017-01-12 05:15:36 -08004213 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004214 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004215 if (receiver) {
4216 observer_->OnRemoveTrack(receiver);
4217 }
deadbeefab9b2d12015-10-14 11:33:11 -07004218}
4219
4220void PeerConnection::UpdateEndedRemoteMediaStreams() {
4221 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4222 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4223 MediaStreamInterface* stream = remote_streams_->at(i);
4224 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4225 streams_to_remove.push_back(stream);
4226 }
4227 }
4228
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004229 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004230 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004231 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004232 }
4233}
4234
Steve Anton4171afb2017-11-20 10:20:22 -08004235void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004236 const std::vector<cricket::StreamParams>& streams,
4237 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004238 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004239
Seth Hampson845e8782018-03-02 11:34:10 -08004240 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004241 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004242 for (auto sender_it = current_senders->begin();
4243 sender_it != current_senders->end();
4244 /* incremented manually */) {
4245 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004246 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004247 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4248 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004249 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004250 OnLocalSenderRemoved(info, media_type);
4251 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004252 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004253 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004254 }
4255 }
4256
Steve Anton4171afb2017-11-20 10:20:22 -08004257 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004258 for (const cricket::StreamParams& params : streams) {
4259 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004260 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004261 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004262 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004263 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004264 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004265 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004266 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004267 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004268 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004269 }
4270 }
4271}
4272
Steve Anton4171afb2017-11-20 10:20:22 -08004273void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4274 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004275 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004276 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004277 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004278 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4279 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004280 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004281 return;
4282 }
4283
deadbeeffac06552015-11-25 11:26:01 -08004284 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004285 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004286 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004287 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004288 }
deadbeeffac06552015-11-25 11:26:01 -08004289
Seth Hampson5b4f0752018-04-02 16:31:36 -07004290 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004291 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004292}
4293
Steve Anton4171afb2017-11-20 10:20:22 -08004294void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4295 cricket::MediaType media_type) {
4296 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004297 if (!sender) {
4298 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004299 // SessionDescriptions has been renegotiated.
4300 return;
4301 }
deadbeeffac06552015-11-25 11:26:01 -08004302
4303 // A sender has been removed from the SessionDescription but it's still
4304 // associated with the PeerConnection. This only occurs if the SDP doesn't
4305 // match with the calls to CreateSender, AddStream and RemoveStream.
4306 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004307 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004308 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004309 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004310 }
deadbeeffac06552015-11-25 11:26:01 -08004311
Steve Anton4171afb2017-11-20 10:20:22 -08004312 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004313}
4314
4315void PeerConnection::UpdateLocalRtpDataChannels(
4316 const cricket::StreamParamsVec& streams) {
4317 std::vector<std::string> existing_channels;
4318
4319 // Find new and active data channels.
4320 for (const cricket::StreamParams& params : streams) {
4321 // |it->sync_label| is actually the data channel label. The reason is that
4322 // we use the same naming of data channels as we do for
4323 // MediaStreams and Tracks.
4324 // For MediaStreams, the sync_label is the MediaStream label and the
4325 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004326 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004327 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004328 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004329 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004330 continue;
4331 }
4332 // Set the SSRC the data channel should use for sending.
4333 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4334 existing_channels.push_back(data_channel_it->first);
4335 }
4336
4337 UpdateClosingRtpDataChannels(existing_channels, true);
4338}
4339
4340void PeerConnection::UpdateRemoteRtpDataChannels(
4341 const cricket::StreamParamsVec& streams) {
4342 std::vector<std::string> existing_channels;
4343
4344 // Find new and active data channels.
4345 for (const cricket::StreamParams& params : streams) {
4346 // The data channel label is either the mslabel or the SSRC if the mslabel
4347 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004348 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004349 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004350 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004351 auto data_channel_it = rtp_data_channels_.find(label);
4352 if (data_channel_it == rtp_data_channels_.end()) {
4353 // This is a new data channel.
4354 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4355 } else {
4356 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4357 }
4358 existing_channels.push_back(label);
4359 }
4360
4361 UpdateClosingRtpDataChannels(existing_channels, false);
4362}
4363
4364void PeerConnection::UpdateClosingRtpDataChannels(
4365 const std::vector<std::string>& active_channels,
4366 bool is_local_update) {
4367 auto it = rtp_data_channels_.begin();
4368 while (it != rtp_data_channels_.end()) {
4369 DataChannel* data_channel = it->second;
4370 if (std::find(active_channels.begin(), active_channels.end(),
4371 data_channel->label()) != active_channels.end()) {
4372 ++it;
4373 continue;
4374 }
4375
4376 if (is_local_update) {
4377 data_channel->SetSendSsrc(0);
4378 } else {
4379 data_channel->RemotePeerRequestClose();
4380 }
4381
4382 if (data_channel->state() == DataChannel::kClosed) {
4383 rtp_data_channels_.erase(it);
4384 it = rtp_data_channels_.begin();
4385 } else {
4386 ++it;
4387 }
4388 }
4389}
4390
4391void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4392 uint32_t remote_ssrc) {
4393 rtc::scoped_refptr<DataChannel> channel(
4394 InternalCreateDataChannel(label, nullptr));
4395 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004396 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004397 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004398 return;
4399 }
4400 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004401 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4402 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004403 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004404}
4405
4406rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4407 const std::string& label,
4408 const InternalDataChannelInit* config) {
4409 if (IsClosed()) {
4410 return nullptr;
4411 }
Steve Anton75737c02017-11-06 10:37:17 -08004412 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004413 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004414 << "InternalCreateDataChannel: Data is not supported in this call.";
4415 return nullptr;
4416 }
4417 InternalDataChannelInit new_config =
4418 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004419 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004420 if (new_config.id < 0) {
4421 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004422 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004423 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004424 RTC_LOG(LS_ERROR)
4425 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004426 return nullptr;
4427 }
4428 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004429 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004430 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004431 return nullptr;
4432 }
4433 }
4434
Steve Anton75737c02017-11-06 10:37:17 -08004435 rtc::scoped_refptr<DataChannel> channel(
4436 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004437 if (!channel) {
4438 sid_allocator_.ReleaseSid(new_config.id);
4439 return nullptr;
4440 }
4441
4442 if (channel->data_channel_type() == cricket::DCT_RTP) {
4443 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004444 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4445 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004446 return nullptr;
4447 }
4448 rtp_data_channels_[channel->label()] = channel;
4449 } else {
4450 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4451 sctp_data_channels_.push_back(channel);
4452 channel->SignalClosed.connect(this,
4453 &PeerConnection::OnSctpDataChannelClosed);
4454 }
4455
Steve Anton2d8609c2018-01-23 16:38:46 -08004456 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004457 return channel;
4458}
4459
4460bool PeerConnection::HasDataChannels() const {
4461 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4462}
4463
4464void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4465 for (const auto& channel : sctp_data_channels_) {
4466 if (channel->id() < 0) {
4467 int sid;
4468 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004469 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004470 continue;
4471 }
4472 channel->SetSctpSid(sid);
4473 }
4474 }
4475}
4476
4477void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004478 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004479 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4480 ++it) {
4481 if (it->get() == channel) {
4482 if (channel->id() >= 0) {
4483 sid_allocator_.ReleaseSid(channel->id());
4484 }
deadbeefbd292462015-12-14 18:15:29 -08004485 // Since this method is triggered by a signal from the DataChannel,
4486 // we can't free it directly here; we need to free it asynchronously.
4487 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004488 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004489 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4490 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004491 return;
4492 }
4493 }
4494}
4495
deadbeefab9b2d12015-10-14 11:33:11 -07004496void PeerConnection::OnDataChannelDestroyed() {
4497 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4498 // DataChannel may callback to us and try to modify the list.
4499 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4500 temp_rtp_dcs.swap(rtp_data_channels_);
4501 for (const auto& kv : temp_rtp_dcs) {
4502 kv.second->OnTransportChannelDestroyed();
4503 }
4504
4505 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4506 temp_sctp_dcs.swap(sctp_data_channels_);
4507 for (const auto& channel : temp_sctp_dcs) {
4508 channel->OnTransportChannelDestroyed();
4509 }
4510}
4511
4512void PeerConnection::OnDataChannelOpenMessage(
4513 const std::string& label,
4514 const InternalDataChannelInit& config) {
4515 rtc::scoped_refptr<DataChannel> channel(
4516 InternalCreateDataChannel(label, &config));
4517 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004518 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004519 return;
4520 }
4521
deadbeefa601f5c2016-06-06 14:27:39 -07004522 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4523 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004524 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004525}
4526
Steve Anton4171afb2017-11-20 10:20:22 -08004527rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4528PeerConnection::GetAudioTransceiver() const {
4529 // This method only works with Plan B SDP, where there is a single
4530 // audio/video transceiver.
4531 RTC_DCHECK(!IsUnifiedPlan());
4532 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004533 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004534 return transceiver;
4535 }
4536 }
4537 RTC_NOTREACHED();
4538 return nullptr;
4539}
4540
4541rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4542PeerConnection::GetVideoTransceiver() const {
4543 // This method only works with Plan B SDP, where there is a single
4544 // audio/video transceiver.
4545 RTC_DCHECK(!IsUnifiedPlan());
4546 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004547 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004548 return transceiver;
4549 }
4550 }
4551 RTC_NOTREACHED();
4552 return nullptr;
4553}
4554
4555// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4556// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004557bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004558 switch (type) {
4559 case cricket::MEDIA_TYPE_AUDIO:
4560 return !GetAudioTransceiver()->internal()->senders().empty();
4561 case cricket::MEDIA_TYPE_VIDEO:
4562 return !GetVideoTransceiver()->internal()->senders().empty();
4563 case cricket::MEDIA_TYPE_DATA:
4564 return false;
4565 }
4566 RTC_NOTREACHED();
4567 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004568}
4569
Steve Anton4171afb2017-11-20 10:20:22 -08004570rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4571PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4572 for (auto transceiver : transceivers_) {
4573 for (auto sender : transceiver->internal()->senders()) {
4574 if (sender->track() == track) {
4575 return sender;
4576 }
4577 }
4578 }
4579 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004580}
4581
Steve Anton4171afb2017-11-20 10:20:22 -08004582rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4583PeerConnection::FindSenderById(const std::string& sender_id) const {
4584 for (auto transceiver : transceivers_) {
4585 for (auto sender : transceiver->internal()->senders()) {
4586 if (sender->id() == sender_id) {
4587 return sender;
4588 }
4589 }
4590 }
4591 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004592}
4593
Steve Anton4171afb2017-11-20 10:20:22 -08004594rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4595PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4596 for (auto transceiver : transceivers_) {
4597 for (auto receiver : transceiver->internal()->receivers()) {
4598 if (receiver->id() == receiver_id) {
4599 return receiver;
4600 }
4601 }
4602 }
4603 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004604}
4605
Steve Anton4171afb2017-11-20 10:20:22 -08004606std::vector<PeerConnection::RtpSenderInfo>*
4607PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4608 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4609 media_type == cricket::MEDIA_TYPE_VIDEO);
4610 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4611 ? &remote_audio_sender_infos_
4612 : &remote_video_sender_infos_;
4613}
4614
4615std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004616 cricket::MediaType media_type) {
4617 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4618 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004619 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4620 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004621}
4622
Steve Anton4171afb2017-11-20 10:20:22 -08004623const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4624 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004625 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004626 const std::string sender_id) const {
4627 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004628 if (sender_info.stream_id == stream_id &&
4629 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004630 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004631 }
4632 }
4633 return nullptr;
4634}
4635
4636DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4637 for (const auto& channel : sctp_data_channels_) {
4638 if (channel->id() == sid) {
4639 return channel;
4640 }
4641 }
4642 return nullptr;
4643}
4644
deadbeef91dd5672016-05-18 16:55:30 -07004645bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004646 const RTCConfiguration& configuration) {
4647 cricket::ServerAddresses stun_servers;
4648 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08004649 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
4650 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004651 return false;
4652 }
4653
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004654 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004655 // To handle both internal and externally created port allocator, we will
4656 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004657 port_allocator_flags_ = port_allocator_->flags();
4658 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4659 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4660 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004661 // If the disable-IPv6 flag was specified, we'll not override it
4662 // by experiment.
4663 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004664 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004665 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4666 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004667 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004668 }
4669
zhihuangb09b3f92017-03-07 14:40:51 -08004670 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004671 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004672 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004673 }
4674
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004675 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004676 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004677 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004678 }
4679
honghaiz60347052016-05-31 18:29:12 -07004680 if (configuration.candidate_network_policy ==
4681 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004682 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004683 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004684 }
4685
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004686 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004687 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004688 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4689 }
4690
Qingsi Wanga2d60672018-04-11 16:57:45 -07004691 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004692 // No step delay is used while allocating ports.
4693 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4694 port_allocator_->set_candidate_filter(
4695 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004696 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004697
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004698 if (tls_cert_verifier_ != nullptr) {
4699 for (auto& turn_server : turn_servers) {
4700 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4701 }
4702 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004703 // Call this last since it may create pooled allocator sessions using the
4704 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004705 port_allocator_->SetConfiguration(
4706 stun_servers, turn_servers, configuration.ice_candidate_pool_size,
4707 configuration.prune_turn_ports, configuration.turn_customizer,
4708 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004709 return true;
4710}
4711
deadbeef91dd5672016-05-18 16:55:30 -07004712bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004713 const cricket::ServerAddresses& stun_servers,
4714 const std::vector<cricket::RelayServerConfig>& turn_servers,
4715 IceTransportsType type,
4716 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004717 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004718 webrtc::TurnCustomizer* turn_customizer,
4719 rtc::Optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004720 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004721 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004722 // According to JSEP, after setLocalDescription, changing the candidate pool
4723 // size is not allowed, and changing the set of ICE servers will not result
4724 // in new candidates being gathered.
4725 if (local_description()) {
4726 port_allocator_->FreezeCandidatePool();
4727 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004728 // Call this last since it may create pooled allocator sessions using the
4729 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004730 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004731 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004732 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004733}
4734
Steve Antonba818672017-11-06 10:21:57 -08004735cricket::ChannelManager* PeerConnection::channel_manager() const {
4736 return factory_->channel_manager();
4737}
4738
4739MetricsObserverInterface* PeerConnection::metrics_observer() const {
4740 return uma_observer_;
4741}
4742
Elad Alon99c3fe52017-10-13 16:29:40 +02004743bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004744 std::unique_ptr<RtcEventLogOutput> output,
4745 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004746 if (!event_log_) {
4747 return false;
4748 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004749 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004750}
4751
4752void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004753 if (event_log_) {
4754 event_log_->StopLogging();
4755 }
ivoc14d5dbe2016-07-04 07:06:55 -07004756}
nisseeaabdf62017-05-05 02:23:02 -07004757
Steve Anton75737c02017-11-06 10:37:17 -08004758cricket::BaseChannel* PeerConnection::GetChannel(
4759 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004760 for (auto transceiver : transceivers_) {
4761 cricket::BaseChannel* channel = transceiver->internal()->channel();
4762 if (channel && channel->content_name() == content_name) {
4763 return channel;
4764 }
Steve Anton75737c02017-11-06 10:37:17 -08004765 }
4766 if (rtp_data_channel() &&
4767 rtp_data_channel()->content_name() == content_name) {
4768 return rtp_data_channel();
4769 }
4770 return nullptr;
4771}
4772
4773bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4774 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004775 RTC_LOG(LS_INFO)
4776 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004777 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004778 return false;
4779 }
4780 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004781 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004782 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004783 return false;
4784 }
4785
Zhi Huange830e682018-03-30 10:48:35 -07004786 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4787 if (dtls_role) {
4788 *role = *dtls_role;
4789 return true;
4790 }
4791 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004792}
4793
4794bool PeerConnection::GetSslRole(const std::string& content_name,
4795 rtc::SSLRole* role) {
4796 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004797 RTC_LOG(LS_INFO)
4798 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004799 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004800 return false;
4801 }
4802
Zhi Huange830e682018-03-30 10:48:35 -07004803 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4804 if (dtls_role) {
4805 *role = *dtls_role;
4806 return true;
4807 }
4808 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004809}
4810
Steve Antonf8470812017-12-04 10:46:21 -08004811void PeerConnection::SetSessionError(SessionError error,
4812 const std::string& error_desc) {
4813 RTC_DCHECK_RUN_ON(signaling_thread());
4814 if (error != session_error_) {
4815 session_error_ = error;
4816 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004817 }
4818}
4819
Zhi Huange830e682018-03-30 10:48:35 -07004820RTCError PeerConnection::UpdateSessionState(
4821 SdpType type,
4822 cricket::ContentSource source,
4823 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004824 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004825
4826 // If there's already a pending error then no state transition should happen.
4827 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004828 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004829
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004830 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004831 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004832 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004833 }
4834
4835 // Update the signaling state according to the specified state machine (see
4836 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004837 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004838 ChangeSignalingState(source == cricket::CS_LOCAL
4839 ? PeerConnectionInterface::kHaveLocalOffer
4840 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004841 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004842 ChangeSignalingState(source == cricket::CS_LOCAL
4843 ? PeerConnectionInterface::kHaveLocalPrAnswer
4844 : PeerConnectionInterface::kHaveRemotePrAnswer);
4845 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004846 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004847 ChangeSignalingState(PeerConnectionInterface::kStable);
4848 }
4849
4850 // Update internal objects according to the session description's media
4851 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004852 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004853 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004854 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004855 }
4856
Steve Anton8a006912017-12-04 15:25:56 -08004857 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004858}
4859
Steve Anton8a006912017-12-04 15:25:56 -08004860RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004861 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004862 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004863 const SessionDescriptionInterface* sdesc =
4864 (source == cricket::CS_LOCAL ? local_description()
4865 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004866 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004867
4868 // Push down the new SDP media section for each audio/video transceiver.
4869 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004870 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004871 FindMediaSectionForTransceiver(transceiver, sdesc);
4872 cricket::BaseChannel* channel = transceiver->internal()->channel();
4873 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004874 continue;
4875 }
4876 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004877 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004878 if (!content_desc) {
4879 continue;
4880 }
4881 std::string error;
4882 bool success =
4883 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004884 ? channel->SetLocalContent(content_desc, type, &error)
4885 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004886 if (!success) {
4887 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4888 }
4889 }
4890
4891 // If using the RtpDataChannel, push down the new SDP section for it too.
4892 if (rtp_data_channel_) {
4893 const ContentInfo* data_content =
4894 cricket::GetFirstDataContent(sdesc->description());
4895 if (data_content && !data_content->rejected) {
4896 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004897 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004898 if (data_desc) {
4899 std::string error;
4900 bool success =
4901 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004902 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
4903 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08004904 &error);
4905 if (!success) {
4906 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4907 std::move(error));
4908 }
Steve Anton75737c02017-11-06 10:37:17 -08004909 }
4910 }
4911 }
Steve Antoned10bd92017-12-05 10:52:59 -08004912
Steve Anton75737c02017-11-06 10:37:17 -08004913 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4914 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4915 if (sctp_transport_ && local_description() && remote_description() &&
4916 cricket::GetFirstDataContent(local_description()->description()) &&
4917 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004918 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004919 RTC_FROM_HERE,
4920 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004921 if (!success) {
4922 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4923 "Failed to push down SCTP parameters.");
4924 }
Steve Anton75737c02017-11-06 10:37:17 -08004925 }
Steve Antoned10bd92017-12-05 10:52:59 -08004926
Steve Anton8a006912017-12-04 15:25:56 -08004927 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004928}
4929
4930bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4931 RTC_DCHECK(network_thread()->IsCurrent());
4932 RTC_DCHECK(local_description());
4933 RTC_DCHECK(remote_description());
4934 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4935 // When we support "max-message-size", that would also be pushed down here.
4936 return sctp_transport_->Start(
4937 GetSctpPort(local_description()->description()),
4938 GetSctpPort(remote_description()->description()));
4939}
4940
Steve Anton8a006912017-12-04 15:25:56 -08004941RTCError PeerConnection::PushdownTransportDescription(
4942 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004943 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004944 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004945
Zhi Huange830e682018-03-30 10:48:35 -07004946 if (source == cricket::CS_LOCAL) {
4947 const SessionDescriptionInterface* sdesc = local_description();
4948 RTC_DCHECK(sdesc);
4949 return transport_controller_->SetLocalDescription(type,
4950 sdesc->description());
4951 } else {
4952 const SessionDescriptionInterface* sdesc = remote_description();
4953 RTC_DCHECK(sdesc);
4954 return transport_controller_->SetRemoteDescription(type,
4955 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004956 }
Steve Anton75737c02017-11-06 10:37:17 -08004957}
4958
4959bool PeerConnection::GetTransportDescription(
4960 const SessionDescription* description,
4961 const std::string& content_name,
4962 cricket::TransportDescription* tdesc) {
4963 if (!description || !tdesc) {
4964 return false;
4965 }
4966 const TransportInfo* transport_info =
4967 description->GetTransportInfoByName(content_name);
4968 if (!transport_info) {
4969 return false;
4970 }
4971 *tdesc = transport_info->description;
4972 return true;
4973}
4974
Steve Anton75737c02017-11-06 10:37:17 -08004975cricket::IceConfig PeerConnection::ParseIceConfig(
4976 const PeerConnectionInterface::RTCConfiguration& config) const {
4977 cricket::ContinualGatheringPolicy gathering_policy;
4978 // TODO(honghaiz): Add the third continual gathering policy in
4979 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
4980 switch (config.continual_gathering_policy) {
4981 case PeerConnectionInterface::GATHER_ONCE:
4982 gathering_policy = cricket::GATHER_ONCE;
4983 break;
4984 case PeerConnectionInterface::GATHER_CONTINUALLY:
4985 gathering_policy = cricket::GATHER_CONTINUALLY;
4986 break;
4987 default:
4988 RTC_NOTREACHED();
4989 gathering_policy = cricket::GATHER_ONCE;
4990 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004991
Steve Anton75737c02017-11-06 10:37:17 -08004992 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004993 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4994 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004995 ice_config.prioritize_most_likely_candidate_pairs =
4996 config.prioritize_most_likely_ice_candidate_pairs;
4997 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004998 RTCConfigurationToIceConfigOptionalInt(
4999 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005000 ice_config.continual_gathering_policy = gathering_policy;
5001 ice_config.presume_writable_when_fully_relayed =
5002 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005003 ice_config.ice_check_interval_strong_connectivity =
5004 config.ice_check_interval_strong_connectivity;
5005 ice_config.ice_check_interval_weak_connectivity =
5006 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005007 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005008 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005009 ice_config.regather_all_networks_interval_range =
5010 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005011 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005012 return ice_config;
5013}
5014
Steve Anton75737c02017-11-06 10:37:17 -08005015bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5016 std::string* track_id) {
5017 if (!local_description()) {
5018 return false;
5019 }
5020 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5021 track_id);
5022}
5023
5024bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5025 std::string* track_id) {
5026 if (!remote_description()) {
5027 return false;
5028 }
5029 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5030 track_id);
5031}
5032
5033bool PeerConnection::SendData(const cricket::SendDataParams& params,
5034 const rtc::CopyOnWriteBuffer& payload,
5035 cricket::SendDataResult* result) {
5036 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005037 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005038 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005039 return false;
5040 }
5041 return rtp_data_channel_
5042 ? rtp_data_channel_->SendData(params, payload, result)
5043 : network_thread()->Invoke<bool>(
5044 RTC_FROM_HERE,
5045 Bind(&cricket::SctpTransportInternal::SendData,
5046 sctp_transport_.get(), params, payload, result));
5047}
5048
5049bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5050 if (!rtp_data_channel_ && !sctp_transport_) {
5051 // Don't log an error here, because DataChannels are expected to call
5052 // ConnectDataChannel in this state. It's the only way to initially tell
5053 // whether or not the underlying transport is ready.
5054 return false;
5055 }
5056 if (rtp_data_channel_) {
5057 rtp_data_channel_->SignalReadyToSendData.connect(
5058 webrtc_data_channel, &DataChannel::OnChannelReady);
5059 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5060 &DataChannel::OnDataReceived);
5061 } else {
5062 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5063 &DataChannel::OnChannelReady);
5064 SignalSctpDataReceived.connect(webrtc_data_channel,
5065 &DataChannel::OnDataReceived);
5066 SignalSctpStreamClosedRemotely.connect(
5067 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
5068 }
5069 return true;
5070}
5071
5072void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5073 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005074 RTC_LOG(LS_ERROR)
5075 << "DisconnectDataChannel called when rtp_data_channel_ and "
5076 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005077 return;
5078 }
5079 if (rtp_data_channel_) {
5080 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5081 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5082 } else {
5083 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5084 SignalSctpDataReceived.disconnect(webrtc_data_channel);
5085 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
5086 }
5087}
5088
5089void PeerConnection::AddSctpDataStream(int sid) {
5090 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005091 RTC_LOG(LS_ERROR)
5092 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005093 return;
5094 }
5095 network_thread()->Invoke<void>(
5096 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5097 sctp_transport_.get(), sid));
5098}
5099
5100void PeerConnection::RemoveSctpDataStream(int sid) {
5101 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005102 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005103 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005104 return;
5105 }
5106 network_thread()->Invoke<void>(
5107 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5108 sctp_transport_.get(), sid));
5109}
5110
5111bool PeerConnection::ReadyToSendData() const {
5112 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5113 sctp_ready_to_send_data_;
5114}
5115
Zhi Huange830e682018-03-30 10:48:35 -07005116rtc::Optional<std::string> PeerConnection::sctp_transport_name() const {
5117 if (sctp_mid_ && transport_controller_) {
5118 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5119 if (dtls_transport) {
5120 return dtls_transport->transport_name();
5121 }
5122 return rtc::Optional<std::string>();
5123 }
5124 return rtc::Optional<std::string>();
5125}
5126
Qingsi Wang72a43a12018-02-20 16:03:18 -08005127cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5128 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005129 network_thread()->Invoke<void>(
5130 RTC_FROM_HERE,
5131 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5132 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005133 return candidate_states_list;
5134}
5135
Steve Anton5dfde182018-02-06 10:34:40 -08005136std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5137 const {
5138 std::map<std::string, std::string> transport_names_by_mid;
5139 for (auto transceiver : transceivers_) {
5140 cricket::BaseChannel* channel = transceiver->internal()->channel();
5141 if (channel) {
5142 transport_names_by_mid[channel->content_name()] =
5143 channel->transport_name();
5144 }
Steve Anton75737c02017-11-06 10:37:17 -08005145 }
Steve Anton5dfde182018-02-06 10:34:40 -08005146 if (rtp_data_channel_) {
5147 transport_names_by_mid[rtp_data_channel_->content_name()] =
5148 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005149 }
5150 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005151 rtc::Optional<std::string> transport_name = sctp_transport_name();
5152 RTC_DCHECK(transport_name);
5153 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005154 }
Steve Anton5dfde182018-02-06 10:34:40 -08005155 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005156}
5157
Steve Anton5dfde182018-02-06 10:34:40 -08005158std::map<std::string, cricket::TransportStats>
5159PeerConnection::GetTransportStatsByNames(
5160 const std::set<std::string>& transport_names) {
5161 if (!network_thread()->IsCurrent()) {
5162 return network_thread()
5163 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5164 RTC_FROM_HERE,
5165 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005166 }
Steve Anton5dfde182018-02-06 10:34:40 -08005167 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5168 for (const std::string& transport_name : transport_names) {
5169 cricket::TransportStats transport_stats;
5170 bool success =
5171 transport_controller_->GetStats(transport_name, &transport_stats);
5172 if (success) {
5173 transport_stats_by_name[transport_name] = std::move(transport_stats);
5174 } else {
5175 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5176 << transport_name;
5177 }
5178 }
5179 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005180}
5181
5182bool PeerConnection::GetLocalCertificate(
5183 const std::string& transport_name,
5184 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005185 if (!certificate) {
5186 return false;
5187 }
5188 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5189 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005190}
5191
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005192std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005193 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005194 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005195}
5196
5197cricket::DataChannelType PeerConnection::data_channel_type() const {
5198 return data_channel_type_;
5199}
5200
5201bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5202 return pending_ice_restarts_.find(content_name) !=
5203 pending_ice_restarts_.end();
5204}
5205
Steve Anton75737c02017-11-06 10:37:17 -08005206bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5207 return transport_controller_->NeedsIceRestart(content_name);
5208}
5209
5210void PeerConnection::OnCertificateReady(
5211 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5212 transport_controller_->SetLocalCertificate(certificate);
5213}
5214
5215void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005216 SetSessionError(SessionError::kTransport,
5217 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005218}
5219
5220void PeerConnection::OnTransportControllerConnectionState(
5221 cricket::IceConnectionState state) {
5222 switch (state) {
5223 case cricket::kIceConnectionConnecting:
5224 // If the current state is Connected or Completed, then there were
5225 // writable channels but now there are not, so the next state must
5226 // be Disconnected.
5227 // kIceConnectionConnecting is currently used as the default,
5228 // un-connected state by the TransportController, so its only use is
5229 // detecting disconnections.
5230 if (ice_connection_state_ ==
5231 PeerConnectionInterface::kIceConnectionConnected ||
5232 ice_connection_state_ ==
5233 PeerConnectionInterface::kIceConnectionCompleted) {
5234 SetIceConnectionState(
5235 PeerConnectionInterface::kIceConnectionDisconnected);
5236 }
5237 break;
5238 case cricket::kIceConnectionFailed:
5239 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5240 break;
5241 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005242 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005243 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005244 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005245 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005246 break;
5247 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005248 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005249 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005250 if (ice_connection_state_ !=
5251 PeerConnectionInterface::kIceConnectionConnected) {
5252 // If jumping directly from "checking" to "connected",
5253 // signal "connected" first.
5254 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5255 }
5256 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005257 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005258 if (metrics_observer()) {
5259 ReportTransportStats();
5260 }
5261 break;
5262 default:
5263 RTC_NOTREACHED();
5264 }
5265}
5266
5267void PeerConnection::OnTransportControllerCandidatesGathered(
5268 const std::string& transport_name,
5269 const cricket::Candidates& candidates) {
5270 RTC_DCHECK(signaling_thread()->IsCurrent());
5271 int sdp_mline_index;
5272 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005273 RTC_LOG(LS_ERROR)
5274 << "OnTransportControllerCandidatesGathered: content name "
5275 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005276 return;
5277 }
5278
5279 for (cricket::Candidates::const_iterator citer = candidates.begin();
5280 citer != candidates.end(); ++citer) {
5281 // Use transport_name as the candidate media id.
5282 std::unique_ptr<JsepIceCandidate> candidate(
5283 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5284 if (local_description()) {
5285 mutable_local_description()->AddCandidate(candidate.get());
5286 }
5287 OnIceCandidate(std::move(candidate));
5288 }
5289}
5290
5291void PeerConnection::OnTransportControllerCandidatesRemoved(
5292 const std::vector<cricket::Candidate>& candidates) {
5293 RTC_DCHECK(signaling_thread()->IsCurrent());
5294 // Sanity check.
5295 for (const cricket::Candidate& candidate : candidates) {
5296 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005297 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005298 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005299 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005300 return;
5301 }
5302 }
5303
5304 if (local_description()) {
5305 mutable_local_description()->RemoveCandidates(candidates);
5306 }
5307 OnIceCandidatesRemoved(candidates);
5308}
5309
5310void PeerConnection::OnTransportControllerDtlsHandshakeError(
5311 rtc::SSLHandshakeError error) {
5312 if (metrics_observer()) {
5313 metrics_observer()->IncrementEnumCounter(
5314 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5315 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5316 }
5317}
5318
Steve Antoned10bd92017-12-05 10:52:59 -08005319void PeerConnection::EnableSending() {
5320 for (auto transceiver : transceivers_) {
5321 cricket::BaseChannel* channel = transceiver->internal()->channel();
5322 if (channel && !channel->enabled()) {
5323 channel->Enable(true);
5324 }
Steve Anton75737c02017-11-06 10:37:17 -08005325 }
5326
Steve Anton4171afb2017-11-20 10:20:22 -08005327 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005328 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005329 }
Steve Anton75737c02017-11-06 10:37:17 -08005330}
5331
5332// Returns the media index for a local ice candidate given the content name.
5333bool PeerConnection::GetLocalCandidateMediaIndex(
5334 const std::string& content_name,
5335 int* sdp_mline_index) {
5336 if (!local_description() || !sdp_mline_index) {
5337 return false;
5338 }
5339
5340 bool content_found = false;
5341 const ContentInfos& contents = local_description()->description()->contents();
5342 for (size_t index = 0; index < contents.size(); ++index) {
5343 if (contents[index].name == content_name) {
5344 *sdp_mline_index = static_cast<int>(index);
5345 content_found = true;
5346 break;
5347 }
5348 }
5349 return content_found;
5350}
5351
5352bool PeerConnection::UseCandidatesInSessionDescription(
5353 const SessionDescriptionInterface* remote_desc) {
5354 if (!remote_desc) {
5355 return true;
5356 }
5357 bool ret = true;
5358
5359 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5360 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5361 for (size_t n = 0; n < candidates->count(); ++n) {
5362 const IceCandidateInterface* candidate = candidates->at(n);
5363 bool valid = false;
5364 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5365 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005366 RTC_LOG(LS_INFO)
5367 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005368 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005369 }
5370 continue;
5371 }
5372 ret = UseCandidate(candidate);
5373 if (!ret) {
5374 break;
5375 }
5376 }
5377 }
5378 return ret;
5379}
5380
5381bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5382 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5383 size_t remote_content_size =
5384 remote_description()->description()->contents().size();
5385 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005386 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005387 return false;
5388 }
5389
5390 cricket::ContentInfo content =
5391 remote_description()->description()->contents()[mediacontent_index];
5392 std::vector<cricket::Candidate> candidates;
5393 candidates.push_back(candidate->candidate());
5394 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005395 RTCError error =
5396 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005397 if (error.ok()) {
5398 // Candidates successfully submitted for checking.
5399 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5400 ice_connection_state_ ==
5401 PeerConnectionInterface::kIceConnectionDisconnected) {
5402 // If state is New, then the session has just gotten its first remote ICE
5403 // candidates, so go to Checking.
5404 // If state is Disconnected, the session is re-using old candidates or
5405 // receiving additional ones, so go to Checking.
5406 // If state is Connected, stay Connected.
5407 // TODO(bemasc): If state is Connected, and the new candidates are for a
5408 // newly added transport, then the state actually _should_ move to
5409 // checking. Add a way to distinguish that case.
5410 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5411 }
5412 // TODO(bemasc): If state is Completed, go back to Connected.
5413 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005414 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005415 }
5416 return true;
5417}
5418
5419void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005420 // Destroy video channel first since it may have a pointer to the
5421 // voice channel.
5422 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005423 if (!video_info || video_info->rejected) {
5424 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005425 }
5426
Steve Anton6fec8802017-12-04 10:37:29 -08005427 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5428 if (!audio_info || audio_info->rejected) {
5429 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005430 }
5431
5432 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5433 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005434 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005435 }
5436}
5437
Steve Antondcc3c022017-12-22 16:02:54 -08005438RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5439 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005440 const cricket::ContentGroup* bundle_group = nullptr;
5441 if (configuration_.bundle_policy ==
5442 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005443 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005444 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005445 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5446 "max-bundle configured but session description "
5447 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005448 }
5449 }
Steve Antondcc3c022017-12-22 16:02:54 -08005450 return std::move(bundle_group);
5451}
5452
5453RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005454 // Creating the media channels. Transports should already have been created
5455 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005456 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005457 if (voice && !voice->rejected &&
5458 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005459 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005460 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005461 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5462 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005463 }
5464 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5465 }
5466
Steve Antondcc3c022017-12-22 16:02:54 -08005467 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005468 if (video && !video->rejected &&
5469 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005470 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005471 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005472 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5473 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005474 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005475 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005476 }
5477
Steve Antondcc3c022017-12-22 16:02:54 -08005478 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005479 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5480 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005481 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005482 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5483 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005484 }
5485 }
5486
Steve Anton8a006912017-12-04 15:25:56 -08005487 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005488}
5489
Steve Anton4171afb2017-11-20 10:20:22 -08005490// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005491cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005492 const std::string& mid) {
5493 RtpTransportInternal* rtp_transport =
5494 transport_controller_->GetRtpTransport(mid);
5495 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005496 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005497 call_.get(), configuration_.media_config, rtp_transport,
5498 signaling_thread(), mid, SrtpRequired(),
5499 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005500 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005501 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005502 }
Steve Anton75737c02017-11-06 10:37:17 -08005503 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5504 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005505 voice_channel->SignalSentPacket.connect(this,
5506 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005507 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005508 if (uma_observer_) {
5509 voice_channel->SetMetricsObserver(uma_observer_);
5510 }
Steve Anton4171afb2017-11-20 10:20:22 -08005511
Steve Antoneda6ccd2017-12-04 10:21:55 -08005512 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005513}
5514
Steve Anton4171afb2017-11-20 10:20:22 -08005515// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005516cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005517 const std::string& mid) {
5518 RtpTransportInternal* rtp_transport =
5519 transport_controller_->GetRtpTransport(mid);
5520 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005521 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005522 call_.get(), configuration_.media_config, rtp_transport,
5523 signaling_thread(), mid, SrtpRequired(),
5524 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005525 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005526 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005527 }
Steve Anton75737c02017-11-06 10:37:17 -08005528 video_channel->SignalDtlsSrtpSetupFailure.connect(
5529 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005530 video_channel->SignalSentPacket.connect(this,
5531 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005532 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005533 if (uma_observer_) {
5534 video_channel->SetMetricsObserver(uma_observer_);
5535 }
Steve Anton4171afb2017-11-20 10:20:22 -08005536
Steve Antoneda6ccd2017-12-04 10:21:55 -08005537 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005538}
5539
Zhi Huange830e682018-03-30 10:48:35 -07005540bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005541 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5542 if (sctp) {
5543 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005544 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005545 << "Trying to create SCTP transport, but didn't compile with "
5546 "SCTP support (HAVE_SCTP)";
5547 return false;
5548 }
5549 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005550 RTC_FROM_HERE,
5551 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005552 return false;
5553 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005554 for (const auto& channel : sctp_data_channels_) {
5555 channel->OnTransportChannelCreated();
5556 }
Steve Anton75737c02017-11-06 10:37:17 -08005557 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005558 RtpTransportInternal* rtp_transport =
5559 transport_controller_->GetRtpTransport(mid);
5560 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005561 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005562 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5563 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005564 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005565 return false;
5566 }
Steve Anton75737c02017-11-06 10:37:17 -08005567 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5568 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5569 rtp_data_channel_->SignalSentPacket.connect(
5570 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005571 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005572 if (uma_observer_) {
5573 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5574 }
Steve Anton75737c02017-11-06 10:37:17 -08005575 }
5576
Steve Anton75737c02017-11-06 10:37:17 -08005577 return true;
5578}
5579
5580Call::Stats PeerConnection::GetCallStats() {
5581 if (!worker_thread()->IsCurrent()) {
5582 return worker_thread()->Invoke<Call::Stats>(
5583 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5584 }
5585 if (call_) {
5586 return call_->GetStats();
5587 } else {
5588 return Call::Stats();
5589 }
5590}
5591
Zhi Huange830e682018-03-30 10:48:35 -07005592bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005593 RTC_DCHECK(network_thread()->IsCurrent());
5594 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005595 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005596 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005597 RTC_DCHECK(dtls_transport);
5598 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005599 RTC_DCHECK(sctp_transport_);
5600 sctp_invoker_.reset(new rtc::AsyncInvoker());
5601 sctp_transport_->SignalReadyToSendData.connect(
5602 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5603 sctp_transport_->SignalDataReceived.connect(
5604 this, &PeerConnection::OnSctpTransportDataReceived_n);
5605 sctp_transport_->SignalStreamClosedRemotely.connect(
5606 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Zhi Huange830e682018-03-30 10:48:35 -07005607 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005608 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005609 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005610}
5611
5612void PeerConnection::DestroySctpTransport_n() {
5613 RTC_DCHECK(network_thread()->IsCurrent());
5614 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005615 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005616 sctp_invoker_.reset(nullptr);
5617 sctp_ready_to_send_data_ = false;
5618}
5619
5620void PeerConnection::OnSctpTransportReadyToSendData_n() {
5621 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5622 RTC_DCHECK(network_thread()->IsCurrent());
5623 // Note: Cannot use rtc::Bind here because it will grab a reference to
5624 // PeerConnection and potentially cause PeerConnection to live longer than
5625 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5626 // be destroyed before PeerConnection is destroyed, and at that point all
5627 // pending tasks will be cleared.
5628 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5629 OnSctpTransportReadyToSendData_s(true);
5630 });
5631}
5632
5633void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5634 RTC_DCHECK(signaling_thread()->IsCurrent());
5635 sctp_ready_to_send_data_ = ready;
5636 SignalSctpReadyToSendData(ready);
5637}
5638
5639void PeerConnection::OnSctpTransportDataReceived_n(
5640 const cricket::ReceiveDataParams& params,
5641 const rtc::CopyOnWriteBuffer& payload) {
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>(
5650 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5651 OnSctpTransportDataReceived_s(params, payload);
5652 });
5653}
5654
5655void PeerConnection::OnSctpTransportDataReceived_s(
5656 const cricket::ReceiveDataParams& params,
5657 const rtc::CopyOnWriteBuffer& payload) {
5658 RTC_DCHECK(signaling_thread()->IsCurrent());
5659 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5660 // Received OPEN message; parse and signal that a new data channel should
5661 // be created.
5662 std::string label;
5663 InternalDataChannelInit config;
5664 config.id = params.ssrc;
5665 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005666 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5667 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005668 return;
5669 }
5670 config.open_handshake_role = InternalDataChannelInit::kAcker;
5671 OnDataChannelOpenMessage(label, config);
5672 } else {
5673 // Otherwise just forward the signal.
5674 SignalSctpDataReceived(params, payload);
5675 }
5676}
5677
5678void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
5679 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5680 RTC_DCHECK(network_thread()->IsCurrent());
5681 sctp_invoker_->AsyncInvoke<void>(
5682 RTC_FROM_HERE, signaling_thread(),
5683 rtc::Bind(&sigslot::signal1<int>::operator(),
5684 &SignalSctpStreamClosedRemotely, sid));
5685}
5686
5687// Returns false if bundle is enabled and rtcp_mux is disabled.
5688bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5689 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5690 if (!bundle_enabled)
5691 return true;
5692
5693 const cricket::ContentGroup* bundle_group =
5694 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5695 RTC_DCHECK(bundle_group != NULL);
5696
5697 const cricket::ContentInfos& contents = desc->contents();
5698 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5699 citer != contents.end(); ++citer) {
5700 const cricket::ContentInfo* content = (&*citer);
5701 RTC_DCHECK(content != NULL);
5702 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005703 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005704 if (!HasRtcpMuxEnabled(content))
5705 return false;
5706 }
5707 }
5708 // RTCP-MUX is enabled in all the contents.
5709 return true;
5710}
5711
5712bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005713 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005714}
5715
Steve Anton8a006912017-12-04 15:25:56 -08005716RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005717 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005718 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005719 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005720 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005721 }
5722
5723 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005724 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005725 }
5726
Steve Anton3828c062017-12-06 10:34:51 -08005727 SdpType type = sdesc->GetType();
5728 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5729 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005730 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005731 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005732 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005733 }
5734
5735 // Verify crypto settings.
5736 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005737 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5738 dtls_enabled_) {
Harald Alvestrand194939b2018-01-24 16:04:13 +01005739 RTCError crypto_error =
5740 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005741 if (!crypto_error.ok()) {
5742 return crypto_error;
5743 }
Steve Anton75737c02017-11-06 10:37:17 -08005744 }
5745
5746 // Verify ice-ufrag and ice-pwd.
5747 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005748 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5749 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
5751
5752 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005753 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5754 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005755 }
5756
5757 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5758 // m-lines that do not rtcp-mux enabled.
5759
5760 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005761 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005762 // With an answer we want to compare the new answer session description with
5763 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005764 const cricket::SessionDescription* offer_desc =
5765 (source == cricket::CS_LOCAL) ? remote_description()->description()
5766 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005767 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5768 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5769 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005770 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5771 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005772 }
5773 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005774 // The re-offers should respect the order of m= sections in current
5775 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005776 // With a re-offer, either the current local or current remote descriptions
5777 // could be the most up to date, so we would like to check against both of
5778 // them if they exist. It could be the case that one of them has a 0 port
5779 // for a media section, but the other does not. This is important to check
5780 // against in the case that we are recycling an m= section.
5781 const cricket::SessionDescription* current_desc = nullptr;
5782 const cricket::SessionDescription* secondary_current_desc = nullptr;
5783 if (local_description()) {
5784 current_desc = local_description()->description();
5785 if (remote_description()) {
5786 secondary_current_desc = remote_description()->description();
5787 }
5788 } else if (remote_description()) {
5789 current_desc = remote_description()->description();
5790 }
Steve Anton75737c02017-11-06 10:37:17 -08005791 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005792 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5793 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005794 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5795 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005796 }
5797 }
5798
Steve Antonba42e992018-04-09 14:10:01 -07005799 if (IsUnifiedPlan()) {
5800 // Ensure that each audio and video media section has at most one
5801 // "StreamParams". This will return an error if receiving a session
5802 // description from a "Plan B" endpoint which adds multiple tracks of the
5803 // same type. With Unified Plan, there can only be at most one track per
5804 // media section.
5805 for (const ContentInfo& content : sdesc->description()->contents()) {
5806 const MediaContentDescription& desc = *content.description;
5807 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5808 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5809 desc.streams().size() > 1u) {
5810 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5811 "Media section has more than one track specified "
5812 "with a=ssrc lines which is not supported with "
5813 "Unified Plan.");
5814 }
5815 }
5816 }
5817
Steve Anton8a006912017-12-04 15:25:56 -08005818 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005819}
5820
Steve Anton3828c062017-12-06 10:34:51 -08005821bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005822 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005823 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005824 return (state == PeerConnectionInterface::kStable) ||
5825 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005826 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005827 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005828 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5829 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5830 }
5831}
5832
Steve Anton3828c062017-12-06 10:34:51 -08005833bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005834 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005835 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005836 return (state == PeerConnectionInterface::kStable) ||
5837 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005838 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005839 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005840 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5841 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5842 }
5843}
5844
Steve Antonf8470812017-12-04 10:46:21 -08005845const char* PeerConnection::SessionErrorToString(SessionError error) const {
5846 switch (error) {
5847 case SessionError::kNone:
5848 return "ERROR_NONE";
5849 case SessionError::kContent:
5850 return "ERROR_CONTENT";
5851 case SessionError::kTransport:
5852 return "ERROR_TRANSPORT";
5853 }
5854 RTC_NOTREACHED();
5855 return "";
5856}
5857
Steve Anton75737c02017-11-06 10:37:17 -08005858std::string PeerConnection::GetSessionErrorMsg() {
5859 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005860 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5861 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005862 return desc.str();
5863}
5864
Steve Anton8e20f172018-03-06 10:55:04 -08005865void PeerConnection::ReportSdpFormatReceived(
5866 const SessionDescriptionInterface& remote_offer) {
5867 if (!uma_observer_) {
5868 return;
5869 }
5870 int num_audio_mlines = 0;
5871 int num_video_mlines = 0;
5872 int num_audio_tracks = 0;
5873 int num_video_tracks = 0;
5874 for (const ContentInfo& content : remote_offer.description()->contents()) {
5875 cricket::MediaType media_type = content.media_description()->type();
5876 int num_tracks = std::max(
5877 1, static_cast<int>(content.media_description()->streams().size()));
5878 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5879 num_audio_mlines += 1;
5880 num_audio_tracks += num_tracks;
5881 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5882 num_video_mlines += 1;
5883 num_video_tracks += num_tracks;
5884 }
5885 }
5886 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5887 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5888 format = kSdpFormatReceivedComplexUnifiedPlan;
5889 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5890 format = kSdpFormatReceivedComplexPlanB;
5891 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5892 format = kSdpFormatReceivedSimple;
5893 }
5894 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5895 kSdpFormatReceivedMax);
5896}
5897
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005898void PeerConnection::NoteUsageEvent(UsageEvent event) {
5899 RTC_DCHECK_RUN_ON(signaling_thread());
5900 usage_event_accumulator_ |= static_cast<int>(event);
5901}
5902
5903void PeerConnection::ReportUsagePattern() const {
5904 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
5905 if (uma_observer_) {
5906 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5907 usage_event_accumulator_);
5908 }
5909}
5910
Steve Anton0ffaaa22018-02-23 10:31:30 -08005911void PeerConnection::ReportNegotiatedSdpSemantics(
5912 const SessionDescriptionInterface& answer) {
5913 if (!uma_observer_) {
5914 return;
5915 }
5916 switch (answer.description()->msid_signaling()) {
5917 case 0:
5918 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5919 kSdpSemanticNegotiatedNone,
5920 kSdpSemanticNegotiatedMax);
5921 break;
5922 case cricket::kMsidSignalingMediaSection:
5923 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5924 kSdpSemanticNegotiatedUnifiedPlan,
5925 kSdpSemanticNegotiatedMax);
5926 break;
5927 case cricket::kMsidSignalingSsrcAttribute:
5928 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5929 kSdpSemanticNegotiatedPlanB,
5930 kSdpSemanticNegotiatedMax);
5931 break;
5932 case cricket::kMsidSignalingMediaSection |
5933 cricket::kMsidSignalingSsrcAttribute:
5934 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5935 kSdpSemanticNegotiatedMixed,
5936 kSdpSemanticNegotiatedMax);
5937 break;
5938 default:
5939 RTC_NOTREACHED();
5940 }
5941}
5942
Steve Anton75737c02017-11-06 10:37:17 -08005943// We need to check the local/remote description for the Transport instead of
5944// the session, because a new Transport added during renegotiation may have
5945// them unset while the session has them set from the previous negotiation.
5946// Not doing so may trigger the auto generation of transport description and
5947// mess up DTLS identity information, ICE credential, etc.
5948bool PeerConnection::ReadyToUseRemoteCandidate(
5949 const IceCandidateInterface* candidate,
5950 const SessionDescriptionInterface* remote_desc,
5951 bool* valid) {
5952 *valid = true;
5953
5954 const SessionDescriptionInterface* current_remote_desc =
5955 remote_desc ? remote_desc : remote_description();
5956
5957 if (!current_remote_desc) {
5958 return false;
5959 }
5960
5961 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5962 size_t remote_content_size =
5963 current_remote_desc->description()->contents().size();
5964 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005965 RTC_LOG(LS_ERROR)
5966 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5967 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005968
5969 *valid = false;
5970 return false;
5971 }
5972
5973 cricket::ContentInfo content =
5974 current_remote_desc->description()->contents()[mediacontent_index];
5975
5976 const std::string transport_name = GetTransportName(content.name);
5977 if (transport_name.empty()) {
5978 return false;
5979 }
Zhi Huange830e682018-03-30 10:48:35 -07005980 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005981}
5982
5983bool PeerConnection::SrtpRequired() const {
5984 return dtls_enabled_ ||
5985 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5986}
5987
5988void PeerConnection::OnTransportControllerGatheringState(
5989 cricket::IceGatheringState state) {
5990 RTC_DCHECK(signaling_thread()->IsCurrent());
5991 if (state == cricket::kIceGatheringGathering) {
5992 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5993 } else if (state == cricket::kIceGatheringComplete) {
5994 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5995 }
5996}
5997
5998void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005999 std::map<std::string, std::set<cricket::MediaType>>
6000 media_types_by_transport_name;
6001 for (auto transceiver : transceivers_) {
6002 if (transceiver->internal()->channel()) {
6003 const std::string& transport_name =
6004 transceiver->internal()->channel()->transport_name();
6005 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006006 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006007 }
Steve Anton75737c02017-11-06 10:37:17 -08006008 }
6009 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006010 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6011 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006012 }
Zhi Huange830e682018-03-30 10:48:35 -07006013
6014 rtc::Optional<std::string> transport_name = sctp_transport_name();
6015 if (transport_name) {
6016 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006017 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006018 }
Zhi Huange830e682018-03-30 10:48:35 -07006019
Steve Antonc7b964c2018-02-01 14:39:45 -08006020 for (const auto& entry : media_types_by_transport_name) {
6021 const std::string& transport_name = entry.first;
6022 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006023 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006024 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006025 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006026 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006027 }
6028 }
6029}
6030// Walk through the ConnectionInfos to gather best connection usage
6031// for IPv4 and IPv6.
6032void PeerConnection::ReportBestConnectionState(
6033 const cricket::TransportStats& stats) {
6034 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006035 for (const cricket::TransportChannelStats& channel_stats :
6036 stats.channel_stats) {
6037 for (const cricket::ConnectionInfo& connection_info :
6038 channel_stats.connection_infos) {
6039 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006040 continue;
6041 }
6042
6043 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006044 const cricket::Candidate& local = connection_info.local_candidate;
6045 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006046
6047 // Increment the counter for IceCandidatePairType.
6048 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6049 (local.type() == RELAY_PORT_TYPE &&
6050 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
6051 type = kEnumCounterIceCandidatePairTypeTcp;
6052 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
6053 type = kEnumCounterIceCandidatePairTypeUdp;
6054 } else {
6055 RTC_CHECK(0);
6056 }
6057 metrics_observer()->IncrementEnumCounter(
6058 type, GetIceCandidatePairCounter(local, remote),
6059 kIceCandidatePairMax);
6060
6061 // Increment the counter for IP type.
6062 if (local.address().family() == AF_INET) {
6063 metrics_observer()->IncrementEnumCounter(
6064 kEnumCounterAddressFamily, kBestConnections_IPv4,
6065 kPeerConnectionAddressFamilyCounter_Max);
6066
6067 } else if (local.address().family() == AF_INET6) {
6068 metrics_observer()->IncrementEnumCounter(
6069 kEnumCounterAddressFamily, kBestConnections_IPv6,
6070 kPeerConnectionAddressFamilyCounter_Max);
6071 } else {
6072 RTC_CHECK(0);
6073 }
6074
6075 return;
6076 }
6077 }
6078}
6079
6080void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006081 const cricket::TransportStats& stats,
6082 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006083 RTC_DCHECK(metrics_observer());
6084 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6085 return;
6086 }
6087
6088 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6089 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6090 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6091 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6092 return;
6093 }
6094
Steve Antonc7b964c2018-02-01 14:39:45 -08006095 for (cricket::MediaType media_type : media_types) {
6096 PeerConnectionEnumCounterType srtp_counter_type;
6097 PeerConnectionEnumCounterType ssl_counter_type;
6098 switch (media_type) {
6099 case cricket::MEDIA_TYPE_AUDIO:
6100 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6101 ssl_counter_type = kEnumCounterAudioSslCipher;
6102 break;
6103 case cricket::MEDIA_TYPE_VIDEO:
6104 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6105 ssl_counter_type = kEnumCounterVideoSslCipher;
6106 break;
6107 case cricket::MEDIA_TYPE_DATA:
6108 srtp_counter_type = kEnumCounterDataSrtpCipher;
6109 ssl_counter_type = kEnumCounterDataSslCipher;
6110 break;
6111 default:
6112 RTC_NOTREACHED();
6113 continue;
6114 }
6115 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6116 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6117 srtp_crypto_suite);
6118 }
6119 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6120 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6121 ssl_cipher_suite);
6122 }
Steve Anton75737c02017-11-06 10:37:17 -08006123 }
6124}
6125
6126void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6127 RTC_DCHECK(worker_thread()->IsCurrent());
6128 RTC_DCHECK(call_);
6129 call_->OnSentPacket(sent_packet);
6130}
6131
6132const std::string PeerConnection::GetTransportName(
6133 const std::string& content_name) {
6134 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006135 if (channel) {
6136 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006137 }
Steve Anton6fec8802017-12-04 10:37:29 -08006138 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006139 RTC_DCHECK(sctp_mid_);
6140 if (content_name == *sctp_mid_) {
6141 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006142 }
6143 }
6144 // Return an empty string if failed to retrieve the transport name.
6145 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006146}
6147
Steve Anton6fec8802017-12-04 10:37:29 -08006148void PeerConnection::DestroyTransceiverChannel(
6149 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6150 transceiver) {
6151 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006152
Steve Anton6fec8802017-12-04 10:37:29 -08006153 cricket::BaseChannel* channel = transceiver->internal()->channel();
6154 if (channel) {
6155 transceiver->internal()->SetChannel(nullptr);
6156 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006157 }
6158}
6159
6160void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006161 if (rtp_data_channel_) {
6162 OnDataChannelDestroyed();
6163 DestroyBaseChannel(rtp_data_channel_);
6164 rtp_data_channel_ = nullptr;
6165 }
6166
6167 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6168 // grab a reference to this PeerConnection. If this is called from the
6169 // PeerConnection destructor, the RefCountedObject vtable will have already
6170 // been destroyed (since it is a subclass of PeerConnection) and using
6171 // rtc::Bind will cause "Pure virtual function called" error to appear.
6172
6173 if (sctp_transport_) {
6174 OnDataChannelDestroyed();
6175 network_thread()->Invoke<void>(RTC_FROM_HERE,
6176 [this] { DestroySctpTransport_n(); });
6177 }
6178}
6179
6180void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6181 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006182 switch (channel->media_type()) {
6183 case cricket::MEDIA_TYPE_AUDIO:
6184 channel_manager()->DestroyVoiceChannel(
6185 static_cast<cricket::VoiceChannel*>(channel));
6186 break;
6187 case cricket::MEDIA_TYPE_VIDEO:
6188 channel_manager()->DestroyVideoChannel(
6189 static_cast<cricket::VideoChannel*>(channel));
6190 break;
6191 case cricket::MEDIA_TYPE_DATA:
6192 channel_manager()->DestroyRtpDataChannel(
6193 static_cast<cricket::RtpDataChannel*>(channel));
6194 break;
6195 default:
6196 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6197 break;
6198 }
Zhi Huange830e682018-03-30 10:48:35 -07006199}
Steve Anton6fec8802017-12-04 10:37:29 -08006200
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006201bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006202 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006203 RtpTransportInternal* rtp_transport,
6204 cricket::DtlsTransportInternal* dtls_transport) {
6205 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006206 auto base_channel = GetChannel(mid);
6207 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006208 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006209 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006210 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006211 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006212 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006213 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006214}
6215
Harald Alvestrand89061872018-01-02 14:08:34 +01006216void PeerConnection::ClearStatsCache() {
6217 if (stats_collector_) {
6218 stats_collector_->ClearCachedStatsReport();
6219 }
6220}
6221
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006222} // namespace webrtc