blob: ebf7cee3c4f7face38d9b5f2769f3aaf7829efe3 [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
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
23#include "api/mediaconstraintsinterface.h"
24#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
26#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.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,
Harald Alvestrand19793842018-06-25 12:03:50 +0200109 MSG_REPORT_USAGE_PATTERN,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000110};
111
Harald Alvestrand19793842018-06-25 12:03:50 +0200112static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
113
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115 explicit SetSessionDescriptionMsg(
116 webrtc::SetSessionDescriptionObserver* observer)
Yves Gerey665174f2018-06-19 15:03:05 +0200117 : observer(observer) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000118
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000119 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100120 RTCError error;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000121};
122
deadbeefab9b2d12015-10-14 11:33:11 -0700123struct CreateSessionDescriptionMsg : public rtc::MessageData {
124 explicit CreateSessionDescriptionMsg(
125 webrtc::CreateSessionDescriptionObserver* observer)
126 : observer(observer) {}
127
128 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100129 RTCError error;
deadbeefab9b2d12015-10-14 11:33:11 -0700130};
131
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000133 GetStatsMsg(webrtc::StatsObserver* observer,
134 webrtc::MediaStreamTrackInterface* track)
Yves Gerey665174f2018-06-19 15:03:05 +0200135 : observer(observer), track(track) {}
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000136 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000137 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000138};
139
deadbeefab9b2d12015-10-14 11:33:11 -0700140// Check if we can send |new_stream| on a PeerConnection.
141bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
142 webrtc::MediaStreamInterface* new_stream) {
143 if (!new_stream || !current_streams) {
144 return false;
145 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700146 if (current_streams->find(new_stream->id()) != nullptr) {
147 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100148 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700149 return false;
150 }
151 return true;
152}
153
deadbeef5e97fb52015-10-15 12:49:08 -0700154// If the direction is "recvonly" or "inactive", treat the description
155// as containing no streams.
156// See: https://code.google.com/p/webrtc/issues/detail?id=5054
157std::vector<cricket::StreamParams> GetActiveStreams(
158 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800159 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700160 ? desc->streams()
161 : std::vector<cricket::StreamParams>();
162}
163
deadbeefab9b2d12015-10-14 11:33:11 -0700164bool IsValidOfferToReceiveMedia(int value) {
165 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
166 return (value >= Options::kUndefined) &&
167 (value <= Options::kMaxOfferToReceiveMedia);
168}
169
zhihuang1c378ed2017-08-17 14:10:50 -0700170// Add options to |[audio/video]_media_description_options| from |senders|.
171void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700172 const std::vector<rtc::scoped_refptr<
173 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700174 cricket::MediaDescriptionOptions* audio_media_description_options,
175 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700176 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700177 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
178 if (audio_media_description_options) {
179 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700180 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700181 }
182 } else {
183 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
184 if (video_media_description_options) {
185 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700186 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700187 }
188 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700189 }
zhihuang1c378ed2017-08-17 14:10:50 -0700190}
olka3c747662017-08-17 06:50:32 -0700191
zhihuang1c378ed2017-08-17 14:10:50 -0700192// Add options to |session_options| from |rtp_data_channels|.
193void AddRtpDataChannelOptions(
194 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
195 rtp_data_channels,
196 cricket::MediaDescriptionOptions* data_media_description_options) {
197 if (!data_media_description_options) {
198 return;
199 }
deadbeefab9b2d12015-10-14 11:33:11 -0700200 // Check for data channels.
201 for (const auto& kv : rtp_data_channels) {
202 const DataChannel* channel = kv.second;
203 if (channel->state() == DataChannel::kConnecting ||
204 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 // Legacy RTP data channels are signaled with the track/stream ID set to
206 // the data channel's label.
207 data_media_description_options->AddRtpDataChannel(channel->label(),
208 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700209 }
210 }
211}
212
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700213uint32_t ConvertIceTransportTypeToCandidateFilter(
214 PeerConnectionInterface::IceTransportsType type) {
215 switch (type) {
216 case PeerConnectionInterface::kNone:
217 return cricket::CF_NONE;
218 case PeerConnectionInterface::kRelay:
219 return cricket::CF_RELAY;
220 case PeerConnectionInterface::kNoHost:
221 return (cricket::CF_ALL & ~cricket::CF_HOST);
222 case PeerConnectionInterface::kAll:
223 return cricket::CF_ALL;
224 default:
nissec80e7412017-01-11 05:56:46 -0800225 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700226 }
227 return cricket::CF_NONE;
228}
229
deadbeef293e9262017-01-11 12:28:30 -0800230// Helper to set an error and return from a method.
231bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
232 if (error) {
233 error->set_type(type);
234 }
235 return type == webrtc::RTCErrorType::NONE;
236}
237
Steve Anton038834f2017-07-14 15:59:59 -0700238bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
239 if (error_out) {
240 *error_out = std::move(error);
241 }
242 return error.ok();
243}
244
Steve Antonba818672017-11-06 10:21:57 -0800245std::string GetSignalingStateString(
246 PeerConnectionInterface::SignalingState state) {
247 switch (state) {
248 case PeerConnectionInterface::kStable:
249 return "kStable";
250 case PeerConnectionInterface::kHaveLocalOffer:
251 return "kHaveLocalOffer";
252 case PeerConnectionInterface::kHaveLocalPrAnswer:
253 return "kHavePrAnswer";
254 case PeerConnectionInterface::kHaveRemoteOffer:
255 return "kHaveRemoteOffer";
256 case PeerConnectionInterface::kHaveRemotePrAnswer:
257 return "kHaveRemotePrAnswer";
258 case PeerConnectionInterface::kClosed:
259 return "kClosed";
260 }
261 RTC_NOTREACHED();
262 return "";
263}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700264
Steve Anton75737c02017-11-06 10:37:17 -0800265IceCandidatePairType GetIceCandidatePairCounter(
266 const cricket::Candidate& local,
267 const cricket::Candidate& remote) {
268 const auto& l = local.type();
269 const auto& r = remote.type();
270 const auto& host = LOCAL_PORT_TYPE;
271 const auto& srflx = STUN_PORT_TYPE;
272 const auto& relay = RELAY_PORT_TYPE;
273 const auto& prflx = PRFLX_PORT_TYPE;
274 if (l == host && r == host) {
275 bool local_private = IPIsPrivate(local.address().ipaddr());
276 bool remote_private = IPIsPrivate(remote.address().ipaddr());
277 if (local_private) {
278 if (remote_private) {
279 return kIceCandidatePairHostPrivateHostPrivate;
280 } else {
281 return kIceCandidatePairHostPrivateHostPublic;
282 }
283 } else {
284 if (remote_private) {
285 return kIceCandidatePairHostPublicHostPrivate;
286 } else {
287 return kIceCandidatePairHostPublicHostPublic;
288 }
289 }
290 }
291 if (l == host && r == srflx)
292 return kIceCandidatePairHostSrflx;
293 if (l == host && r == relay)
294 return kIceCandidatePairHostRelay;
295 if (l == host && r == prflx)
296 return kIceCandidatePairHostPrflx;
297 if (l == srflx && r == host)
298 return kIceCandidatePairSrflxHost;
299 if (l == srflx && r == srflx)
300 return kIceCandidatePairSrflxSrflx;
301 if (l == srflx && r == relay)
302 return kIceCandidatePairSrflxRelay;
303 if (l == srflx && r == prflx)
304 return kIceCandidatePairSrflxPrflx;
305 if (l == relay && r == host)
306 return kIceCandidatePairRelayHost;
307 if (l == relay && r == srflx)
308 return kIceCandidatePairRelaySrflx;
309 if (l == relay && r == relay)
310 return kIceCandidatePairRelayRelay;
311 if (l == relay && r == prflx)
312 return kIceCandidatePairRelayPrflx;
313 if (l == prflx && r == host)
314 return kIceCandidatePairPrflxHost;
315 if (l == prflx && r == srflx)
316 return kIceCandidatePairPrflxSrflx;
317 if (l == prflx && r == relay)
318 return kIceCandidatePairPrflxRelay;
319 return kIceCandidatePairMax;
320}
321
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800322// Logic to decide if an m= section can be recycled. This means that the new
323// m= section is not rejected, but the old local or remote m= section is
324// rejected. |old_content_one| and |old_content_two| refer to the m= section
325// of the old remote and old local descriptions in no particular order.
326// We need to check both the old local and remote because either
327// could be the most current from the latest negotation.
328bool IsMediaSectionBeingRecycled(SdpType type,
329 const ContentInfo& content,
330 const ContentInfo* old_content_one,
331 const ContentInfo* old_content_two) {
332 return type == SdpType::kOffer && !content.rejected &&
333 ((old_content_one && old_content_one->rejected) ||
334 (old_content_two && old_content_two->rejected));
335}
336
Steve Anton75737c02017-11-06 10:37:17 -0800337// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800338// |current_desc|. The number of m= sections in |new_desc| should be no
339// less than |current_desc|. In the case of checking an answer's
340// |new_desc|, the |current_desc| is the last offer that was set as the
341// local or remote. In the case of checking an offer's |new_desc| we
342// check against the local and remote descriptions stored from the last
343// negotiation, because either of these could be the most up to date for
344// possible rejected m sections. These are the |current_desc| and
345// |secondary_current_desc|.
346bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
347 const SessionDescription* secondary_current_desc,
348 const SessionDescription& new_desc,
349 const SdpType type) {
350 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800351 return false;
352 }
353
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800354 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
355 const cricket::ContentInfo* secondary_content_info = nullptr;
356 if (secondary_current_desc &&
357 i < secondary_current_desc->contents().size()) {
358 secondary_content_info = &secondary_current_desc->contents()[i];
359 }
360 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
361 &current_desc.contents()[i],
362 secondary_content_info)) {
363 // For new offer descriptions, if the media section can be recycled, it's
364 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800365 continue;
366 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800367 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800368 return false;
369 }
370 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800371 new_desc.contents()[i].media_description();
372 const MediaContentDescription* current_desc_mdesc =
373 current_desc.contents()[i].media_description();
374 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800375 return false;
376 }
377 }
378 return true;
379}
380
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800381bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
382 const SessionDescription& desc2) {
383 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800384}
385
Qingsi Wang78fef762018-07-11 18:33:52 +0000386void NoteKeyProtocolAndMedia(
387 KeyExchangeProtocolType protocol_type,
388 cricket::MediaType media_type,
389 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
390 if (!uma_observer)
391 return;
392 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocol,
393 protocol_type,
394 webrtc::kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100395 static const std::map<std::pair<KeyExchangeProtocolType, cricket::MediaType>,
396 KeyExchangeProtocolMedia>
397 proto_media_counter_map = {
398 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO},
399 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
400 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO},
401 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
402 {{kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA},
403 kEnumCounterKeyProtocolMediaTypeDtlsData},
404 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO},
405 kEnumCounterKeyProtocolMediaTypeSdesAudio},
406 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO},
407 kEnumCounterKeyProtocolMediaTypeSdesVideo},
408 {{kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA},
409 kEnumCounterKeyProtocolMediaTypeSdesData}};
410
411 auto it = proto_media_counter_map.find({protocol_type, media_type});
412 if (it != proto_media_counter_map.end()) {
Qingsi Wang78fef762018-07-11 18:33:52 +0000413 uma_observer->IncrementEnumCounter(webrtc::kEnumCounterKeyProtocolMediaType,
414 it->second,
415 kEnumCounterKeyProtocolMediaTypeMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100416 }
417}
418
Steve Anton75737c02017-11-06 10:37:17 -0800419// Checks that each non-rejected content has SDES crypto keys or a DTLS
420// fingerprint, unless it's in a BUNDLE group, in which case only the
421// BUNDLE-tag section (first media section/description in the BUNDLE group)
422// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
423// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
424// by Channel's |srtp_required| check.
Qingsi Wang78fef762018-07-11 18:33:52 +0000425RTCError VerifyCrypto(const SessionDescription* desc,
426 bool dtls_enabled,
427 rtc::scoped_refptr<webrtc::UMAObserver> uma_observer) {
Steve Anton75737c02017-11-06 10:37:17 -0800428 const cricket::ContentGroup* bundle =
429 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800430 for (const cricket::ContentInfo& content_info : desc->contents()) {
431 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800432 continue;
433 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100434 // Note what media is used with each crypto protocol, for all sections.
435 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
436 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang78fef762018-07-11 18:33:52 +0000437 content_info.media_description()->type(),
438 uma_observer);
Steve Anton8a006912017-12-04 15:25:56 -0800439 const std::string& mid = content_info.name;
440 if (bundle && bundle->HasContentName(mid) &&
441 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800442 // This isn't the first media section in the BUNDLE group, so it's not
443 // required to have crypto attributes, since only the crypto attributes
444 // from the first section actually get used.
445 continue;
446 }
447
448 // If the content isn't rejected or bundled into another m= section, crypto
449 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800450 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800451 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800452 if (!media || !tinfo) {
453 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800455 }
456 if (dtls_enabled) {
457 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100458 RTC_LOG(LS_WARNING)
459 << "Session description must have DTLS fingerprint if "
460 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800461 return RTCError(RTCErrorType::INVALID_PARAMETER,
462 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800463 }
464 } else {
465 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100466 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800467 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800468 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800469 }
470 }
471 }
Steve Anton8a006912017-12-04 15:25:56 -0800472 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800473}
474
475// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
476// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
477// media section/description in the BUNDLE group) needs a ufrag and pwd.
478bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
479 const cricket::ContentGroup* bundle =
480 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800481 for (const cricket::ContentInfo& content_info : desc->contents()) {
482 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800483 continue;
484 }
Steve Anton8a006912017-12-04 15:25:56 -0800485 const std::string& mid = content_info.name;
486 if (bundle && bundle->HasContentName(mid) &&
487 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800488 // This isn't the first media section in the BUNDLE group, so it's not
489 // required to have ufrag/password, since only the ufrag/password from
490 // the first section actually get used.
491 continue;
492 }
493
494 // If the content isn't rejected or bundled into another m= section,
495 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800496 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800497 if (!tinfo) {
498 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100499 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800500 return false;
501 }
502 if (tinfo->description.ice_ufrag.empty() ||
503 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100504 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800505 return false;
506 }
507 }
508 return true;
509}
510
511bool GetTrackIdBySsrc(const SessionDescription* session_description,
512 uint32_t ssrc,
513 std::string* track_id) {
514 RTC_DCHECK(track_id != NULL);
515
Steve Antonb1c1de12017-12-21 15:14:30 -0800516 const cricket::AudioContentDescription* audio_desc =
517 cricket::GetFirstAudioContentDescription(session_description);
518 if (audio_desc) {
519 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800520 if (found) {
521 *track_id = found->id;
522 return true;
523 }
524 }
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::VideoContentDescription* video_desc =
527 cricket::GetFirstVideoContentDescription(session_description);
528 if (video_desc) {
529 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535 return false;
536}
537
538// Get the SCTP port out of a SessionDescription.
539// Return -1 if not found.
540int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800541 const cricket::DataContentDescription* data_desc =
542 GetFirstDataContentDescription(session_description);
543 RTC_DCHECK(data_desc);
544 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800545 return -1;
546 }
Steve Anton75737c02017-11-06 10:37:17 -0800547 std::string value;
548 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
549 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800550 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800551 if (!codec.Matches(match_pattern)) {
552 continue;
553 }
554 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
555 return rtc::FromString<int>(value);
556 }
557 }
558 return -1;
559}
560
Steve Anton75737c02017-11-06 10:37:17 -0800561// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
562bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
563 const SessionDescriptionInterface* new_desc,
564 const std::string& content_name) {
565 if (!old_desc) {
566 return false;
567 }
568 const SessionDescription* new_sd = new_desc->description();
569 const SessionDescription* old_sd = old_desc->description();
570 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
571 if (!cinfo || cinfo->rejected) {
572 return false;
573 }
574 // If the content isn't rejected, check if ufrag and password has changed.
575 const cricket::TransportDescription* new_transport_desc =
576 new_sd->GetTransportDescriptionByName(content_name);
577 const cricket::TransportDescription* old_transport_desc =
578 old_sd->GetTransportDescriptionByName(content_name);
579 if (!new_transport_desc || !old_transport_desc) {
580 // No transport description exists. This is not an ICE restart.
581 return false;
582 }
583 if (cricket::IceCredentialsChanged(
584 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
585 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100586 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
587 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800588 return true;
589 }
590 return false;
591}
592
Steve Anton80dd7b52018-02-16 17:08:42 -0800593// Generates a string error message for SetLocalDescription/SetRemoteDescription
594// from an RTCError.
595std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
596 SdpType type,
597 const RTCError& error) {
598 std::ostringstream oss;
599 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
600 << " " << SdpTypeToString(type) << " sdp: " << error.message();
601 return oss.str();
602}
603
Seth Hampson5b4f0752018-04-02 16:31:36 -0700604std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
605 std::string output = "streams=[";
606 const char* separator = "";
607 for (const auto& stream_id : stream_ids) {
608 output.append(separator).append(stream_id);
609 separator = ", ";
610 }
611 output.append("]");
612 return output;
613}
614
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200615absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700616 int rtc_configuration_parameter) {
617 if (rtc_configuration_parameter ==
618 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200619 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700620 }
621 return rtc_configuration_parameter;
622}
623
Steve Anton75737c02017-11-06 10:37:17 -0800624} // namespace
625
Henrik Boström31638672017-11-23 17:48:32 +0100626// Upon completion, posts a task to execute the callback of the
627// SetSessionDescriptionObserver asynchronously on the same thread. At this
628// point, the state of the peer connection might no longer reflect the effects
629// of the SetRemoteDescription operation, as the peer connection could have been
630// modified during the post.
631// TODO(hbos): Remove this class once we remove the version of
632// PeerConnectionInterface::SetRemoteDescription() that takes a
633// SetSessionDescriptionObserver as an argument.
634class PeerConnection::SetRemoteDescriptionObserverAdapter
635 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
636 public:
637 SetRemoteDescriptionObserverAdapter(
638 rtc::scoped_refptr<PeerConnection> pc,
639 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
640 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
641
642 // SetRemoteDescriptionObserverInterface implementation.
643 void OnSetRemoteDescriptionComplete(RTCError error) override {
644 if (error.ok())
645 pc_->PostSetSessionDescriptionSuccess(wrapper_);
646 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100647 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100648 }
649
650 private:
651 rtc::scoped_refptr<PeerConnection> pc_;
652 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
653};
654
deadbeef293e9262017-01-11 12:28:30 -0800655bool PeerConnectionInterface::RTCConfiguration::operator==(
656 const PeerConnectionInterface::RTCConfiguration& o) const {
657 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700658 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800659 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000660 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700661 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800662 BundlePolicy bundle_policy;
663 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700664 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
665 int ice_candidate_pool_size;
666 bool disable_ipv6;
667 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700668 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100669 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700670 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200671 absl::optional<int> screencast_min_bitrate;
672 absl::optional<bool> combined_audio_video_bwe;
673 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800674 TcpCandidatePolicy tcp_candidate_policy;
675 CandidateNetworkPolicy candidate_network_policy;
676 int audio_jitter_buffer_max_packets;
677 bool audio_jitter_buffer_fast_accelerate;
678 int ice_connection_receiving_timeout;
679 int ice_backup_candidate_pair_ping_interval;
680 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800681 bool prioritize_most_likely_ice_candidate_pairs;
682 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800683 bool prune_turn_ports;
684 bool presume_writable_when_fully_relayed;
685 bool enable_ice_renomination;
686 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200687 absl::optional<int> ice_check_interval_strong_connectivity;
688 absl::optional<int> ice_check_interval_weak_connectivity;
689 absl::optional<int> ice_check_min_interval;
690 absl::optional<int> ice_unwritable_timeout;
691 absl::optional<int> ice_unwritable_min_checks;
692 absl::optional<int> stun_candidate_keepalive_interval;
693 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200694 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800695 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200696 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700697 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800698 };
699 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
700 "Did you add something to RTCConfiguration and forget to "
701 "update operator==?");
702 return type == o.type && servers == o.servers &&
703 bundle_policy == o.bundle_policy &&
704 rtcp_mux_policy == o.rtcp_mux_policy &&
705 tcp_candidate_policy == o.tcp_candidate_policy &&
706 candidate_network_policy == o.candidate_network_policy &&
707 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
708 audio_jitter_buffer_fast_accelerate ==
709 o.audio_jitter_buffer_fast_accelerate &&
710 ice_connection_receiving_timeout ==
711 o.ice_connection_receiving_timeout &&
712 ice_backup_candidate_pair_ping_interval ==
713 o.ice_backup_candidate_pair_ping_interval &&
714 continual_gathering_policy == o.continual_gathering_policy &&
715 certificates == o.certificates &&
716 prioritize_most_likely_ice_candidate_pairs ==
717 o.prioritize_most_likely_ice_candidate_pairs &&
718 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800719 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700720 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100721 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800722 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800723 screencast_min_bitrate == o.screencast_min_bitrate &&
724 combined_audio_video_bwe == o.combined_audio_video_bwe &&
725 enable_dtls_srtp == o.enable_dtls_srtp &&
726 ice_candidate_pool_size == o.ice_candidate_pool_size &&
727 prune_turn_ports == o.prune_turn_ports &&
728 presume_writable_when_fully_relayed ==
729 o.presume_writable_when_fully_relayed &&
730 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800731 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800732 ice_check_interval_strong_connectivity ==
733 o.ice_check_interval_strong_connectivity &&
734 ice_check_interval_weak_connectivity ==
735 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700736 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700737 ice_unwritable_timeout == o.ice_unwritable_timeout &&
738 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800739 stun_candidate_keepalive_interval ==
740 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200741 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800742 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800743 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700744 network_preference == o.network_preference &&
745 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800746}
747
748bool PeerConnectionInterface::RTCConfiguration::operator!=(
749 const PeerConnectionInterface::RTCConfiguration& o) const {
750 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800751}
752
zhihuang8f65cdf2016-05-06 18:40:30 -0700753// Generate a RTCP CNAME when a PeerConnection is created.
754std::string GenerateRtcpCname() {
755 std::string cname;
756 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100757 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800758 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700759 }
760 return cname;
761}
762
zhihuang1c378ed2017-08-17 14:10:50 -0700763bool ValidateOfferAnswerOptions(
764 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
765 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
766 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700767}
768
zhihuang1c378ed2017-08-17 14:10:50 -0700769// From |rtc_options|, fill parts of |session_options| shared by all generated
770// m= sections (in other words, nothing that involves a map/array).
771void ExtractSharedMediaSessionOptions(
772 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
773 cricket::MediaSessionOptions* session_options) {
774 session_options->vad_enabled = rtc_options.voice_activity_detection;
775 session_options->bundle_enabled = rtc_options.use_rtp_mux;
776}
zhihuanga77e6bb2017-08-14 18:17:48 -0700777
zhihuang1c378ed2017-08-17 14:10:50 -0700778bool ConvertConstraintsToOfferAnswerOptions(
779 const MediaConstraintsInterface* constraints,
780 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700781 if (!constraints) {
782 return true;
783 }
zhihuang1c378ed2017-08-17 14:10:50 -0700784
785 bool value = false;
786 size_t mandatory_constraints_satisfied = 0;
787
788 if (FindConstraint(constraints,
789 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
790 &mandatory_constraints_satisfied)) {
791 offer_answer_options->offer_to_receive_audio =
792 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
793 kOfferToReceiveMediaTrue
794 : 0;
795 }
796
797 if (FindConstraint(constraints,
798 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
799 &mandatory_constraints_satisfied)) {
800 offer_answer_options->offer_to_receive_video =
801 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
802 kOfferToReceiveMediaTrue
803 : 0;
804 }
805 if (FindConstraint(constraints,
806 MediaConstraintsInterface::kVoiceActivityDetection, &value,
807 &mandatory_constraints_satisfied)) {
808 offer_answer_options->voice_activity_detection = value;
809 }
810 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
811 &mandatory_constraints_satisfied)) {
812 offer_answer_options->use_rtp_mux = value;
813 }
814 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
815 &value, &mandatory_constraints_satisfied)) {
816 offer_answer_options->ice_restart = value;
817 }
818
deadbeefab9b2d12015-10-14 11:33:11 -0700819 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
820}
821
zhihuang38ede132017-06-15 12:52:32 -0700822PeerConnection::PeerConnection(PeerConnectionFactory* factory,
823 std::unique_ptr<RtcEventLog> event_log,
824 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700826 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700827 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700828 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700829 remote_streams_(StreamCollection::Create()),
830 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000831
832PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100833 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800834 RTC_DCHECK_RUN_ON(signaling_thread());
835
Steve Anton8af21862017-12-15 11:20:13 -0800836 // Need to stop transceivers before destroying the stats collector because
837 // AudioRtpSender has a reference to the StatsCollector it will update when
838 // stopping.
839 for (auto transceiver : transceivers_) {
840 transceiver->Stop();
841 }
Steve Anton4171afb2017-11-20 10:20:22 -0800842
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700843 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800844 if (stats_collector_) {
845 stats_collector_->WaitForPendingRequest();
846 stats_collector_ = nullptr;
847 }
Steve Anton75737c02017-11-06 10:37:17 -0800848
Steve Anton8af21862017-12-15 11:20:13 -0800849 // Don't destroy BaseChannels until after stats has been cleaned up so that
850 // the last stats request can still read from the channels.
851 DestroyAllChannels();
852
Mirko Bonadei675513b2017-11-09 11:09:25 +0100853 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800854
855 webrtc_session_desc_factory_.reset();
856 sctp_invoker_.reset();
857 sctp_factory_.reset();
858 transport_controller_.reset();
859
deadbeef91dd5672016-05-18 16:55:30 -0700860 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700861 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700862 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700863 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700864 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700865 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800866 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700867 event_log_.reset();
868 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000869}
870
Steve Anton8af21862017-12-15 11:20:13 -0800871void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800872 // Destroy video channels first since they may have a pointer to a voice
873 // channel.
874 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800875 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800876 DestroyTransceiverChannel(transceiver);
877 }
878 }
879 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800880 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800881 DestroyTransceiverChannel(transceiver);
882 }
883 }
884 DestroyDataChannel();
885}
886
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000888 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700889 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100890 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700891
892 RTCError config_error = ValidateConfiguration(configuration);
893 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100894 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700895 return false;
896 }
897
Benjamin Wrightcab58882018-05-02 15:12:47 -0700898 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_ERROR)
900 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100901 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800902 return false;
903 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200904
Benjamin Wrightcab58882018-05-02 15:12:47 -0700905 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800906 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100908 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800909 return false;
910 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700911
Benjamin Wrightcab58882018-05-02 15:12:47 -0700912 observer_ = dependencies.observer;
913 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700914 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800915
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200916 cricket::ServerAddresses stun_servers;
917 std::vector<cricket::RelayServerConfig> turn_servers;
918
919 RTCErrorType parse_error =
920 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
921 if (parse_error != RTCErrorType::NONE) {
922 return false;
923 }
924
deadbeef91dd5672016-05-18 16:55:30 -0700925 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700926 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700927 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200928 RTC_FROM_HERE,
929 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
930 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 return false;
932 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200933 // If initialization was successful, note if STUN or TURN servers
934 // were supplied.
935 if (!stun_servers.empty()) {
936 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
937 }
938 if (!turn_servers.empty()) {
939 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
940 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941
Zhi Huange830e682018-03-30 10:48:35 -0700942 const PeerConnectionFactoryInterface::Options& options = factory_->options();
943
Steve Anton75737c02017-11-06 10:37:17 -0800944 // RFC 3264: The numeric value of the session id and version in the
945 // o line MUST be representable with a "64 bit signed integer".
946 // Due to this constraint session id |session_id_| is max limited to
947 // LLONG_MAX.
948 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700949 JsepTransportController::Config config;
950 config.redetermine_role_on_ice_restart =
951 configuration.redetermine_role_on_ice_restart;
952 config.ssl_max_version = factory_->options().ssl_max_version;
953 config.disable_encryption = options.disable_encryption;
954 config.bundle_policy = configuration.bundle_policy;
955 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
956 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700957 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700958 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700959#if defined(ENABLE_EXTERNAL_AUTH)
960 config.enable_external_auth = true;
961#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700962 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700963 transport_controller_.reset(new JsepTransportController(
964 signaling_thread(), network_thread(), port_allocator_.get(), config));
965 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800966 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700967 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800968 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700969 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800970 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700971 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800972 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
973 transport_controller_->SignalDtlsHandshakeError.connect(
974 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
975
976 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700977
deadbeefab9b2d12015-10-14 11:33:11 -0700978 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700979 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000980
Steve Antonba818672017-11-06 10:21:57 -0800981 configuration_ = configuration;
982
Steve Anton75737c02017-11-06 10:37:17 -0800983 // Obtain a certificate from RTCConfiguration if any were provided (optional).
984 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
985 if (!configuration.certificates.empty()) {
986 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
987 // just picking the first one. The decision should be made based on the DTLS
988 // handshake. The DTLS negotiations need to know about all certificates.
989 certificate = configuration.certificates[0];
990 }
991
Steve Antond25da372017-11-06 14:50:29 -0800992 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800993
994 if (options.disable_encryption) {
995 dtls_enabled_ = false;
996 } else {
997 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700998 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800999 // |configuration| can override the default |dtls_enabled_| value.
1000 if (configuration.enable_dtls_srtp) {
1001 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1002 }
1003 }
1004
1005 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
1006 // It takes precendence over the disable_sctp_data_channels
1007 // PeerConnectionFactoryInterface::Options.
1008 if (configuration.enable_rtp_data_channel) {
1009 data_channel_type_ = cricket::DCT_RTP;
1010 } else {
1011 // DTLS has to be enabled to use SCTP.
1012 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1013 data_channel_type_ = cricket::DCT_SCTP;
1014 }
1015 }
1016
1017 video_options_.screencast_min_bitrate_kbps =
1018 configuration.screencast_min_bitrate;
1019 audio_options_.combined_audio_video_bwe =
1020 configuration.combined_audio_video_bwe;
1021
1022 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001023 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001024
1025 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001026 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001027
1028 // Whether the certificate generator/certificate is null or not determines
1029 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1030 // the right instructions by clearing the variables if needed.
1031 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001032 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001033 certificate = nullptr;
1034 } else if (certificate) {
1035 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001036 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001037 }
1038
1039 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1040 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001041 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001042 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1043 this, &PeerConnection::OnCertificateReady);
1044
1045 if (options.disable_encryption) {
1046 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1047 }
1048
1049 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1050 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001051
Steve Anton4171afb2017-11-20 10:20:22 -08001052 // Add default audio/video transceivers for Plan B SDP.
1053 if (!IsUnifiedPlan()) {
1054 transceivers_.push_back(
1055 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1056 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1057 transceivers_.push_back(
1058 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1059 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1060 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001061 int delay_ms =
1062 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
1063 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1064 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001065 return true;
1066}
1067
Steve Anton038834f2017-07-14 15:59:59 -07001068RTCError PeerConnection::ValidateConfiguration(
1069 const RTCConfiguration& config) const {
1070 if (config.ice_regather_interval_range &&
1071 config.continual_gathering_policy == GATHER_ONCE) {
1072 return RTCError(RTCErrorType::INVALID_PARAMETER,
1073 "ice_regather_interval_range specified but continual "
1074 "gathering policy is GATHER_ONCE");
1075 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001076 auto result =
1077 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1078 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001079}
1080
Yves Gerey665174f2018-06-19 15:03:05 +02001081rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001082 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1083 "Plan SdpSemantics. Please use GetSenders "
1084 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001085 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001086}
1087
Yves Gerey665174f2018-06-19 15:03:05 +02001088rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001089 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1090 "Plan SdpSemantics. Please use GetReceivers "
1091 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001092 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093}
1094
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001095bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001096 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1097 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001098 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001099 if (IsClosed()) {
1100 return false;
1101 }
deadbeefab9b2d12015-10-14 11:33:11 -07001102 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001103 return false;
1104 }
deadbeefab9b2d12015-10-14 11:33:11 -07001105
1106 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001107 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1108 observer->SignalAudioTrackAdded.connect(this,
1109 &PeerConnection::OnAudioTrackAdded);
1110 observer->SignalAudioTrackRemoved.connect(
1111 this, &PeerConnection::OnAudioTrackRemoved);
1112 observer->SignalVideoTrackAdded.connect(this,
1113 &PeerConnection::OnVideoTrackAdded);
1114 observer->SignalVideoTrackRemoved.connect(
1115 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001116 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001117
deadbeefab9b2d12015-10-14 11:33:11 -07001118 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001119 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001120 }
1121 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001122 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001123 }
1124
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001125 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126 observer_->OnRenegotiationNeeded();
1127 return true;
1128}
1129
1130void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001131 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1132 "Plan SdpSemantics. Please use RemoveTrack "
1133 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001134 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001135 if (!IsClosed()) {
1136 for (const auto& track : local_stream->GetAudioTracks()) {
1137 RemoveAudioTrack(track.get(), local_stream);
1138 }
1139 for (const auto& track : local_stream->GetVideoTracks()) {
1140 RemoveVideoTrack(track.get(), local_stream);
1141 }
deadbeefab9b2d12015-10-14 11:33:11 -07001142 }
deadbeefab9b2d12015-10-14 11:33:11 -07001143 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001144 stream_observers_.erase(
1145 std::remove_if(
1146 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001147 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001148 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001149 }),
1150 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001151
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 if (IsClosed()) {
1153 return;
1154 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001155 observer_->OnRenegotiationNeeded();
1156}
1157
deadbeefe1f9d832016-01-14 15:35:42 -08001158rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1159 MediaStreamTrackInterface* track,
1160 std::vector<MediaStreamInterface*> streams) {
1161 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Seth Hampson845e8782018-03-02 11:34:10 -08001162 std::vector<std::string> stream_ids;
Steve Antonf9381f02017-12-14 10:23:57 -08001163 for (auto* stream : streams) {
1164 if (!stream) {
1165 RTC_LOG(LS_ERROR) << "Stream list has null element.";
1166 return nullptr;
1167 }
Seth Hampson13b8bad2018-03-13 16:05:28 -07001168 stream_ids.push_back(stream->id());
Steve Antonf9381f02017-12-14 10:23:57 -08001169 }
Seth Hampson845e8782018-03-02 11:34:10 -08001170 auto sender_or_error = AddTrack(track, stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001171 if (!sender_or_error.ok()) {
deadbeefe1f9d832016-01-14 15:35:42 -08001172 return nullptr;
1173 }
Steve Antonf9381f02017-12-14 10:23:57 -08001174 return sender_or_error.MoveValue();
1175}
1176
Steve Anton2d6c76a2018-01-05 17:10:52 -08001177RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001178 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001179 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001180 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001181 if (!track) {
1182 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1183 }
1184 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1185 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1186 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1187 "Track has invalid kind: " + track->kind());
1188 }
Steve Antonf9381f02017-12-14 10:23:57 -08001189 if (IsClosed()) {
1190 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1191 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001192 }
Steve Anton4171afb2017-11-20 10:20:22 -08001193 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001194 LOG_AND_RETURN_ERROR(
1195 RTCErrorType::INVALID_PARAMETER,
1196 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001197 }
Steve Antonf9381f02017-12-14 10:23:57 -08001198 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001199 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1200 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001201 if (sender_or_error.ok()) {
1202 observer_->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001203 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001204 }
1205 return sender_or_error;
1206}
deadbeefe1f9d832016-01-14 15:35:42 -08001207
Steve Antonf9381f02017-12-14 10:23:57 -08001208RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1209PeerConnection::AddTrackPlanB(
1210 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001211 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001212 if (stream_ids.size() > 1u) {
1213 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1214 "AddTrack with more than one stream is not "
1215 "supported with Plan B semantics.");
1216 }
1217 std::vector<std::string> adjusted_stream_ids = stream_ids;
1218 if (adjusted_stream_ids.empty()) {
1219 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1220 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001221 cricket::MediaType media_type =
1222 (track->kind() == MediaStreamTrackInterface::kAudioKind
1223 ? cricket::MEDIA_TYPE_AUDIO
1224 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001225 auto new_sender =
1226 CreateSender(media_type, track->id(), track, adjusted_stream_ids);
deadbeefe1f9d832016-01-14 15:35:42 -08001227 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001228 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001229 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001230 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001231 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001232 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001233 if (sender_info) {
1234 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001235 }
Steve Antonf9381f02017-12-14 10:23:57 -08001236 } else {
1237 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001238 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001239 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001240 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001241 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001242 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001243 if (sender_info) {
1244 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001245 }
deadbeefe1f9d832016-01-14 15:35:42 -08001246 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001247 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001248}
deadbeefe1f9d832016-01-14 15:35:42 -08001249
Steve Antonf9381f02017-12-14 10:23:57 -08001250RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1251PeerConnection::AddTrackUnifiedPlan(
1252 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001253 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001254 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1255 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001256 RTC_LOG(LS_INFO) << "Reusing an existing "
1257 << cricket::MediaTypeToString(transceiver->media_type())
1258 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001259 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001260 transceiver->internal()->set_direction(
1261 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001262 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001263 transceiver->internal()->set_direction(
1264 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001265 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001266 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001267 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001268 } else {
1269 cricket::MediaType media_type =
1270 (track->kind() == MediaStreamTrackInterface::kAudioKind
1271 ? cricket::MEDIA_TYPE_AUDIO
1272 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001273 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1274 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001275 std::string sender_id = track->id();
1276 // Avoid creating a sender with an existing ID by generating a random ID.
1277 // This can happen if this is the second time AddTrack has created a sender
1278 // for this track.
1279 if (FindSenderById(sender_id)) {
1280 sender_id = rtc::CreateRandomUuid();
1281 }
1282 auto sender = CreateSender(media_type, sender_id, track, stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001283 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1284 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001285 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001286 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001287 }
Steve Antonf9381f02017-12-14 10:23:57 -08001288 return transceiver->sender();
1289}
1290
1291rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1292PeerConnection::FindFirstTransceiverForAddedTrack(
1293 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1294 RTC_DCHECK(track);
1295 for (auto transceiver : transceivers_) {
1296 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001297 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001298 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001299 !transceiver->internal()->has_ever_been_used_to_send() &&
1300 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001301 return transceiver;
1302 }
1303 }
1304 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001305}
1306
1307bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1308 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001309 return RemoveTrackInternal(sender).ok();
1310}
1311
1312RTCError PeerConnection::RemoveTrackInternal(
1313 rtc::scoped_refptr<RtpSenderInterface> sender) {
1314 if (!sender) {
1315 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1316 }
deadbeefe1f9d832016-01-14 15:35:42 -08001317 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001318 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1319 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001320 }
Steve Antonf9381f02017-12-14 10:23:57 -08001321 if (IsUnifiedPlan()) {
1322 auto transceiver = FindTransceiverBySender(sender);
1323 if (!transceiver || !sender->track()) {
1324 return RTCError::OK();
1325 }
1326 sender->SetTrack(nullptr);
1327 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001328 transceiver->internal()->set_direction(
1329 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001330 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001331 transceiver->internal()->set_direction(
1332 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001333 }
Steve Anton4171afb2017-11-20 10:20:22 -08001334 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001335 bool removed;
1336 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1337 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1338 } else {
1339 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1340 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1341 }
1342 if (!removed) {
1343 LOG_AND_RETURN_ERROR(
1344 RTCErrorType::INVALID_PARAMETER,
1345 "Couldn't find sender " + sender->id() + " to remove.");
1346 }
Steve Anton4171afb2017-11-20 10:20:22 -08001347 }
deadbeefe1f9d832016-01-14 15:35:42 -08001348 observer_->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001349 return RTCError::OK();
1350}
1351
1352rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1353PeerConnection::FindTransceiverBySender(
1354 rtc::scoped_refptr<RtpSenderInterface> sender) {
1355 for (auto transceiver : transceivers_) {
1356 if (transceiver->sender() == sender) {
1357 return transceiver;
1358 }
1359 }
1360 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001361}
1362
Steve Anton9158ef62017-11-27 13:01:52 -08001363RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1364PeerConnection::AddTransceiver(
1365 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1366 return AddTransceiver(track, RtpTransceiverInit());
1367}
1368
1369RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1370PeerConnection::AddTransceiver(
1371 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1372 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001373 RTC_CHECK(IsUnifiedPlan())
1374 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001375 if (!track) {
1376 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1377 }
1378 cricket::MediaType media_type;
1379 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1380 media_type = cricket::MEDIA_TYPE_AUDIO;
1381 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1382 media_type = cricket::MEDIA_TYPE_VIDEO;
1383 } else {
1384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1385 "Track kind is not audio or video");
1386 }
1387 return AddTransceiver(media_type, track, init);
1388}
1389
1390RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1391PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1392 return AddTransceiver(media_type, RtpTransceiverInit());
1393}
1394
1395RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1396PeerConnection::AddTransceiver(cricket::MediaType media_type,
1397 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001398 RTC_CHECK(IsUnifiedPlan())
1399 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001400 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1401 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1402 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1403 "media type is not audio or video");
1404 }
1405 return AddTransceiver(media_type, nullptr, init);
1406}
1407
1408RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1409PeerConnection::AddTransceiver(
1410 cricket::MediaType media_type,
1411 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001412 const RtpTransceiverInit& init,
1413 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001414 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1415 media_type == cricket::MEDIA_TYPE_VIDEO));
1416 if (track) {
1417 RTC_DCHECK_EQ(media_type,
1418 (track->kind() == MediaStreamTrackInterface::kAudioKind
1419 ? cricket::MEDIA_TYPE_AUDIO
1420 : cricket::MEDIA_TYPE_VIDEO));
1421 }
1422
1423 // TODO(bugs.webrtc.org/7600): Verify init.
1424
Steve Anton3d954a62018-04-02 11:27:23 -07001425 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1426 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001427 // Set the sender ID equal to the track ID if the track is specified unless
1428 // that sender ID is already in use.
1429 std::string sender_id =
1430 (track && !FindSenderById(track->id()) ? track->id()
1431 : rtc::CreateRandomUuid());
1432 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001433 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1434 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1435 transceiver->internal()->set_direction(init.direction);
1436
Steve Anton22da89f2018-01-25 13:58:07 -08001437 if (fire_callback) {
1438 observer_->OnRenegotiationNeeded();
1439 }
Steve Antonf9381f02017-12-14 10:23:57 -08001440
1441 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1442}
1443
Steve Anton02ee47c2018-01-10 16:26:06 -08001444rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1445PeerConnection::CreateSender(
1446 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001447 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001448 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001449 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001450 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001451 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1452 RTC_DCHECK(!track ||
1453 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1454 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1455 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001456 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001457 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001458 } else {
1459 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1460 RTC_DCHECK(!track ||
1461 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1462 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001463 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001464 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001465 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001466 bool set_track_succeeded = sender->SetTrack(track);
1467 RTC_DCHECK(set_track_succeeded);
1468 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001469 return sender;
1470}
1471
1472rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1473PeerConnection::CreateReceiver(cricket::MediaType media_type,
1474 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001475 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1476 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001477 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001478 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001479 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1480 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001481 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001482 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001483 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001484 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001485 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1486 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001487 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001488 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001489 return receiver;
1490}
1491
1492rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1493PeerConnection::CreateAndAddTransceiver(
1494 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1495 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1496 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001497 // Ensure that the new sender does not have an ID that is already in use by
1498 // another sender.
1499 // Allow receiver IDs to conflict since those come from remote SDP (which
1500 // could be invalid, but should not cause a crash).
1501 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1503 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001504 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001505 transceiver->internal()->SignalNegotiationNeeded.connect(
1506 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001507 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001508}
1509
Steve Anton52d86772018-02-20 15:48:12 -08001510void PeerConnection::OnNegotiationNeeded() {
1511 RTC_DCHECK_RUN_ON(signaling_thread());
1512 RTC_DCHECK(!IsClosed());
1513 observer_->OnRenegotiationNeeded();
1514}
1515
deadbeeffac06552015-11-25 11:26:01 -08001516rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001517 const std::string& kind,
1518 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001519 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1520 "Plan SdpSemantics. Please use AddTransceiver "
1521 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001522 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001523 if (IsClosed()) {
1524 return nullptr;
1525 }
Steve Anton4171afb2017-11-20 10:20:22 -08001526
Seth Hampson5b4f0752018-04-02 16:31:36 -07001527 // Internally we need to have one stream with Plan B semantics, so we
1528 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001529 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001530 if (stream_id.empty()) {
1531 stream_ids.push_back(rtc::CreateRandomUuid());
1532 RTC_LOG(LS_INFO)
1533 << "No stream_id specified for sender. Generated stream ID: "
1534 << stream_ids[0];
1535 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001536 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001537 }
1538
Steve Anton4171afb2017-11-20 10:20:22 -08001539 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001540 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001541 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001542 auto* audio_sender = new AudioRtpSender(
1543 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001544 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001545 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001546 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001547 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001548 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001549 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001550 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001551 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001552 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001553 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001554 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001555 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001556 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001557 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001558 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001559 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001560
deadbeefe1f9d832016-01-14 15:35:42 -08001561 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001562}
1563
deadbeef70ab1a12015-09-28 16:53:55 -07001564std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1565 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001566 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001567 for (auto sender : GetSendersInternal()) {
1568 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001569 }
1570 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001571}
1572
Steve Anton4171afb2017-11-20 10:20:22 -08001573std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1574PeerConnection::GetSendersInternal() const {
1575 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1576 all_senders;
1577 for (auto transceiver : transceivers_) {
1578 auto senders = transceiver->internal()->senders();
1579 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1580 }
1581 return all_senders;
1582}
1583
deadbeef70ab1a12015-09-28 16:53:55 -07001584std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1585PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001586 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001587 for (const auto& receiver : GetReceiversInternal()) {
1588 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001589 }
1590 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001591}
1592
Steve Anton4171afb2017-11-20 10:20:22 -08001593std::vector<
1594 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1595PeerConnection::GetReceiversInternal() const {
1596 std::vector<
1597 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1598 all_receivers;
1599 for (auto transceiver : transceivers_) {
1600 auto receivers = transceiver->internal()->receivers();
1601 all_receivers.insert(all_receivers.end(), receivers.begin(),
1602 receivers.end());
1603 }
1604 return all_receivers;
1605}
1606
Steve Anton9158ef62017-11-27 13:01:52 -08001607std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1608PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001609 RTC_CHECK(IsUnifiedPlan())
1610 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001611 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1612 for (auto transceiver : transceivers_) {
1613 all_transceivers.push_back(transceiver);
1614 }
1615 return all_transceivers;
1616}
1617
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001618bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001619 MediaStreamTrackInterface* track,
1620 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001621 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001622 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001623 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001624 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001625 return false;
1626 }
1627
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001628 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001629 // The StatsCollector is used to tell if a track is valid because it may
1630 // remember tracks that the PeerConnection previously removed.
1631 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001632 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1633 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001634 return false;
1635 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001636 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001637 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001638 return true;
1639}
1640
hbos74e1a4f2016-09-15 23:33:01 -07001641void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001642 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001643 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001644 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001645 stats_collector_->GetStatsReport(callback);
1646}
1647
Henrik Boström1df1bf82018-03-20 13:24:20 +01001648void PeerConnection::GetStats(
1649 rtc::scoped_refptr<RtpSenderInterface> selector,
1650 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1651 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1652 RTC_DCHECK(callback);
1653 RTC_DCHECK(stats_collector_);
1654 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1655 if (selector) {
1656 for (const auto& proxy_transceiver : transceivers_) {
1657 for (const auto& proxy_sender :
1658 proxy_transceiver->internal()->senders()) {
1659 if (proxy_sender == selector) {
1660 internal_sender = proxy_sender->internal();
1661 break;
1662 }
1663 }
1664 if (internal_sender)
1665 break;
1666 }
1667 }
1668 // If there is no |internal_sender| then |selector| is either null or does not
1669 // belong to the PeerConnection (in Plan B, senders can be removed from the
1670 // PeerConnection). This means that "all the stats objects representing the
1671 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1672 // produces an empty stats report.
1673 stats_collector_->GetStatsReport(internal_sender, callback);
1674}
1675
1676void PeerConnection::GetStats(
1677 rtc::scoped_refptr<RtpReceiverInterface> selector,
1678 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1679 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1680 RTC_DCHECK(callback);
1681 RTC_DCHECK(stats_collector_);
1682 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1683 if (selector) {
1684 for (const auto& proxy_transceiver : transceivers_) {
1685 for (const auto& proxy_receiver :
1686 proxy_transceiver->internal()->receivers()) {
1687 if (proxy_receiver == selector) {
1688 internal_receiver = proxy_receiver->internal();
1689 break;
1690 }
1691 }
1692 if (internal_receiver)
1693 break;
1694 }
1695 }
1696 // If there is no |internal_receiver| then |selector| is either null or does
1697 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1698 // the PeerConnection). This means that "all the stats objects representing
1699 // the selector" is an empty set. Invoking GetStatsReport() with a null
1700 // selector produces an empty stats report.
1701 stats_collector_->GetStatsReport(internal_receiver, callback);
1702}
1703
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1705 return signaling_state_;
1706}
1707
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001708PeerConnectionInterface::IceConnectionState
1709PeerConnection::ice_connection_state() {
1710 return ice_connection_state_;
1711}
1712
1713PeerConnectionInterface::IceGatheringState
1714PeerConnection::ice_gathering_state() {
1715 return ice_gathering_state_;
1716}
1717
Yves Gerey665174f2018-06-19 15:03:05 +02001718rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719 const std::string& label,
1720 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001721 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001722
deadbeefab9b2d12015-10-14 11:33:11 -07001723 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001724
kwibergd1fe2812016-04-27 06:47:29 -07001725 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001726 if (config) {
1727 internal_config.reset(new InternalDataChannelInit(*config));
1728 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001729 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001730 InternalCreateDataChannel(label, internal_config.get()));
1731 if (!channel.get()) {
1732 return nullptr;
1733 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001734
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001735 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1736 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001737 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001738 observer_->OnRenegotiationNeeded();
1739 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001740 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741 return DataChannelProxy::Create(signaling_thread(), channel.get());
1742}
1743
1744void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1745 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001746 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001747
zhihuang1c378ed2017-08-17 14:10:50 -07001748 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1749 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1750 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1751 // compares the mandatory fields parsed with the mandatory fields added in the
1752 // |constraints| and some downstream applications might create offers with
1753 // mandatory fields which would not be parsed in the helper method. For
1754 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1755 // |constraints| as a mandatory field but it is not parsed.
1756 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001757
zhihuang1c378ed2017-08-17 14:10:50 -07001758 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001759}
1760
1761void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1762 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001763 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001764
nisse7ce109a2017-01-31 00:57:56 -08001765 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001766 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001767 return;
1768 }
deadbeefab9b2d12015-10-14 11:33:11 -07001769
Steve Anton8d3444d2017-10-20 15:30:51 -07001770 if (IsClosed()) {
1771 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001772 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001773 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001774 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001775 return;
1776 }
1777
zhihuang1c378ed2017-08-17 14:10:50 -07001778 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001779 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001780 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001781 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001782 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001783 return;
1784 }
1785
Steve Anton22da89f2018-01-25 13:58:07 -08001786 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1787 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1788 if (IsUnifiedPlan()) {
1789 RTCError error = HandleLegacyOfferOptions(options);
1790 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001791 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001792 return;
1793 }
1794 }
1795
zhihuang1c378ed2017-08-17 14:10:50 -07001796 cricket::MediaSessionOptions session_options;
1797 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001798 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001799}
1800
Steve Anton22da89f2018-01-25 13:58:07 -08001801RTCError PeerConnection::HandleLegacyOfferOptions(
1802 const RTCOfferAnswerOptions& options) {
1803 RTC_DCHECK(IsUnifiedPlan());
1804
1805 if (options.offer_to_receive_audio == 0) {
1806 RemoveRecvDirectionFromReceivingTransceiversOfType(
1807 cricket::MEDIA_TYPE_AUDIO);
1808 } else if (options.offer_to_receive_audio == 1) {
1809 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1810 } else if (options.offer_to_receive_audio > 1) {
1811 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1812 "offer_to_receive_audio > 1 is not supported.");
1813 }
1814
1815 if (options.offer_to_receive_video == 0) {
1816 RemoveRecvDirectionFromReceivingTransceiversOfType(
1817 cricket::MEDIA_TYPE_VIDEO);
1818 } else if (options.offer_to_receive_video == 1) {
1819 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1820 } else if (options.offer_to_receive_video > 1) {
1821 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1822 "offer_to_receive_video > 1 is not supported.");
1823 }
1824
1825 return RTCError::OK();
1826}
1827
1828void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1829 cricket::MediaType media_type) {
1830 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001831 RtpTransceiverDirection new_direction =
1832 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1833 if (new_direction != transceiver->direction()) {
1834 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1835 << " transceiver (MID="
1836 << transceiver->mid().value_or("<not set>") << ") from "
1837 << RtpTransceiverDirectionToString(
1838 transceiver->direction())
1839 << " to "
1840 << RtpTransceiverDirectionToString(new_direction)
1841 << " since CreateOffer specified offer_to_receive=0";
1842 transceiver->internal()->set_direction(new_direction);
1843 }
Steve Anton22da89f2018-01-25 13:58:07 -08001844 }
1845}
1846
1847void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1848 cricket::MediaType media_type) {
1849 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001850 RTC_LOG(LS_INFO)
1851 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1852 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001853 RtpTransceiverInit init;
1854 init.direction = RtpTransceiverDirection::kRecvOnly;
1855 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1856 }
1857}
1858
1859std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1860PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1861 std::vector<
1862 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1863 receiving_transceivers;
1864 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001865 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001866 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1867 receiving_transceivers.push_back(transceiver);
1868 }
1869 }
1870 return receiving_transceivers;
1871}
1872
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001873void PeerConnection::CreateAnswer(
1874 CreateSessionDescriptionObserver* observer,
1875 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001876 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001877
nisse7ce109a2017-01-31 00:57:56 -08001878 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001879 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001880 return;
1881 }
deadbeefab9b2d12015-10-14 11:33:11 -07001882
zhihuang1c378ed2017-08-17 14:10:50 -07001883 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1884 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1885 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001886 std::string error = "CreateAnswer called with invalid constraints.";
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_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001890 return;
1891 }
1892
Steve Anton8d3444d2017-10-20 15:30:51 -07001893 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001894}
1895
1896void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1897 const RTCOfferAnswerOptions& options) {
1898 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001899 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001900 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001901 return;
1902 }
1903
Steve Antondffead82018-02-06 10:31:29 -08001904 if (!(signaling_state_ == kHaveRemoteOffer ||
1905 signaling_state_ == kHaveLocalPrAnswer)) {
1906 std::string error =
1907 "PeerConnection cannot create an answer in a state other than "
1908 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001909 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001910 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001911 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001912 return;
1913 }
1914
Steve Antondffead82018-02-06 10:31:29 -08001915 // The remote description should be set if we're in the right state.
1916 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001917
Steve Anton22da89f2018-01-25 13:58:07 -08001918 if (IsUnifiedPlan()) {
1919 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1920 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1921 "supported with Unified Plan semantics. Use the "
1922 "RtpTransceiver API instead.";
1923 }
1924 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1925 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1926 "supported with Unified Plan semantics. Use the "
1927 "RtpTransceiver API instead.";
1928 }
1929 }
1930
htaa2a49d92016-03-04 02:51:39 -08001931 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001932 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001933
Steve Antond25da372017-11-06 14:50:29 -08001934 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935}
1936
1937void PeerConnection::SetLocalDescription(
1938 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001939 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001940 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001941
Steve Anton80dd7b52018-02-16 17:08:42 -08001942 // The SetLocalDescription contract is that we take ownership of the session
1943 // description regardless of the outcome, so wrap it in a unique_ptr right
1944 // away. Ideally, SetLocalDescription's signature will be changed to take the
1945 // description as a unique_ptr argument to formalize this agreement.
1946 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1947
nisse7ce109a2017-01-31 00:57:56 -08001948 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001949 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001950 return;
1951 }
Steve Anton8a006912017-12-04 15:25:56 -08001952
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001953 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001954 PostSetSessionDescriptionFailure(
1955 observer,
1956 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957 return;
1958 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001959
Steve Anton80dd7b52018-02-16 17:08:42 -08001960 // If a session error has occurred the PeerConnection is in a possibly
1961 // inconsistent state so fail right away.
1962 if (session_error() != SessionError::kNone) {
1963 std::string error_message = GetSessionErrorMsg();
1964 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001965 PostSetSessionDescriptionFailure(
1966 observer,
1967 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001968 return;
1969 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001970
Steve Anton80dd7b52018-02-16 17:08:42 -08001971 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1972 if (!error.ok()) {
1973 std::string error_message = GetSetDescriptionErrorMessage(
1974 cricket::CS_LOCAL, desc->GetType(), error);
1975 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001976 PostSetSessionDescriptionFailure(
1977 observer,
1978 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001979 return;
1980 }
1981
1982 // Grab the description type before moving ownership to ApplyLocalDescription,
1983 // which may destroy it before returning.
1984 const SdpType type = desc->GetType();
1985
1986 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001987 // |desc| may be destroyed at this point.
1988
1989 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001990 // If ApplyLocalDescription fails, the PeerConnection could be in an
1991 // inconsistent state, so act conservatively here and set the session error
1992 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1993 SetSessionError(SessionError::kContent, error.message());
1994 std::string error_message =
1995 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1996 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001997 PostSetSessionDescriptionFailure(
1998 observer,
1999 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002000 return;
2001 }
Steve Anton8a006912017-12-04 15:25:56 -08002002 RTC_DCHECK(local_description());
2003
2004 PostSetSessionDescriptionSuccess(observer);
2005
Steve Anton8a006912017-12-04 15:25:56 -08002006 // MaybeStartGathering needs to be called after posting
2007 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2008 // before signaling that SetLocalDescription completed.
2009 transport_controller_->MaybeStartGathering();
2010
Steve Antona3a92c22017-12-07 10:27:41 -08002011 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002012 // TODO(deadbeef): We already had to hop to the network thread for
2013 // MaybeStartGathering...
2014 network_thread()->Invoke<void>(
2015 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2016 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002017 // Make UMA notes about what was agreed to.
2018 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002019 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002020 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002021}
2022
2023RTCError PeerConnection::ApplyLocalDescription(
2024 std::unique_ptr<SessionDescriptionInterface> desc) {
2025 RTC_DCHECK_RUN_ON(signaling_thread());
2026 RTC_DCHECK(desc);
2027
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 // Update stats here so that we have the most recent stats for tracks and
2029 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002030 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002031
Steve Antondcc3c022017-12-22 16:02:54 -08002032 // Take a reference to the old local description since it's used below to
2033 // compare against the new local description. When setting the new local
2034 // description, grab ownership of the replaced session description in case it
2035 // is the same as |old_local_description|, to keep it alive for the duration
2036 // of the method.
2037 const SessionDescriptionInterface* old_local_description =
2038 local_description();
2039 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002040 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002041 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002042 replaced_local_description = pending_local_description_
2043 ? std::move(pending_local_description_)
2044 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002045 current_local_description_ = std::move(desc);
2046 pending_local_description_ = nullptr;
2047 current_remote_description_ = std::move(pending_remote_description_);
2048 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002049 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002050 pending_local_description_ = std::move(desc);
2051 }
2052 // The session description to apply now must be accessed by
2053 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002054 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002055
Zhi Huange830e682018-03-30 10:48:35 -07002056 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2057 if (!error.ok()) {
2058 return error;
2059 }
2060
Steve Antondcc3c022017-12-22 16:02:54 -08002061 if (IsUnifiedPlan()) {
2062 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002063 cricket::CS_LOCAL, *local_description(), old_local_description,
2064 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002065 if (!error.ok()) {
2066 return error;
2067 }
Steve Antondcc3c022017-12-22 16:02:54 -08002068 for (auto transceiver : transceivers_) {
2069 const ContentInfo* content =
2070 FindMediaSectionForTransceiver(transceiver, local_description());
2071 if (!content) {
2072 continue;
2073 }
2074 const MediaContentDescription* media_desc = content->media_description();
2075 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2076 transceiver->internal()->set_current_direction(media_desc->direction());
2077 }
2078 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002079 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2080 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002081 transceiver->Stop();
2082 }
2083 }
2084 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002085 // Media channels will be created only when offer is set. These may use new
2086 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002087 if (type == SdpType::kOffer) {
2088 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2089 // description is applied. Restore back to old description.
2090 RTCError error = CreateChannels(*local_description()->description());
2091 if (!error.ok()) {
2092 return error;
2093 }
2094 }
Steve Antondcc3c022017-12-22 16:02:54 -08002095 // Remove unused channels if MediaContentDescription is rejected.
2096 RemoveUnusedChannels(local_description()->description());
2097 }
Steve Anton8a006912017-12-04 15:25:56 -08002098
Zhi Huange830e682018-03-30 10:48:35 -07002099 error = UpdateSessionState(type, cricket::CS_LOCAL,
2100 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002101 if (!error.ok()) {
2102 return error;
2103 }
Steve Antondcc3c022017-12-22 16:02:54 -08002104
Steve Anton8a006912017-12-04 15:25:56 -08002105 if (remote_description()) {
2106 // Now that we have a local description, we can push down remote candidates.
2107 UseCandidatesInSessionDescription(remote_description());
2108 }
2109
2110 pending_ice_restarts_.clear();
2111 if (session_error() != SessionError::kNone) {
2112 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2113 }
2114
deadbeefab9b2d12015-10-14 11:33:11 -07002115 // If setting the description decided our SSL role, allocate any necessary
2116 // SCTP sids.
2117 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002118 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002119 AllocateSctpSids(role);
2120 }
2121
Steve Antond3679212018-01-17 17:41:02 -08002122 if (IsUnifiedPlan()) {
2123 for (auto transceiver : transceivers_) {
2124 const ContentInfo* content =
2125 FindMediaSectionForTransceiver(transceiver, local_description());
2126 if (!content) {
2127 continue;
2128 }
Steve Anton74255ff2018-01-24 18:32:57 -08002129 const auto& streams = content->media_description()->streams();
2130 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002131 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002132 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002133 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002134 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002135 } else {
2136 // 0 is a special value meaning "this sender has no associated send
2137 // stream". Need to call this so the sender won't attempt to configure
2138 // a no longer existing stream and run into DCHECKs in the lower
2139 // layers.
2140 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002141 }
2142 }
2143 } else {
2144 // Plan B semantics.
2145
Steve Antondcc3c022017-12-22 16:02:54 -08002146 // Update state and SSRC of local MediaStreams and DataChannels based on the
2147 // local session description.
2148 const cricket::ContentInfo* audio_content =
2149 GetFirstAudioContent(local_description()->description());
2150 if (audio_content) {
2151 if (audio_content->rejected) {
2152 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2153 } else {
2154 const cricket::AudioContentDescription* audio_desc =
2155 audio_content->media_description()->as_audio();
2156 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2157 }
deadbeeffaac4972015-11-12 15:33:07 -08002158 }
deadbeefab9b2d12015-10-14 11:33:11 -07002159
Steve Antondcc3c022017-12-22 16:02:54 -08002160 const cricket::ContentInfo* video_content =
2161 GetFirstVideoContent(local_description()->description());
2162 if (video_content) {
2163 if (video_content->rejected) {
2164 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2165 } else {
2166 const cricket::VideoContentDescription* video_desc =
2167 video_content->media_description()->as_video();
2168 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2169 }
deadbeeffaac4972015-11-12 15:33:07 -08002170 }
deadbeefab9b2d12015-10-14 11:33:11 -07002171 }
2172
2173 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002174 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002175 if (data_content) {
2176 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002177 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002178 if (rtc::starts_with(data_desc->protocol().data(),
2179 cricket::kMediaProtocolRtpPrefix)) {
2180 UpdateLocalRtpDataChannels(data_desc->streams());
2181 }
2182 }
2183
Steve Anton8a006912017-12-04 15:25:56 -08002184 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002185}
2186
2187void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002188 SetSessionDescriptionObserver* observer,
2189 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002190 SetRemoteDescription(
2191 std::unique_ptr<SessionDescriptionInterface>(desc),
2192 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2193 new SetRemoteDescriptionObserverAdapter(this, observer)));
2194}
2195
2196void PeerConnection::SetRemoteDescription(
2197 std::unique_ptr<SessionDescriptionInterface> desc,
2198 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002199 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002200
nisse7ce109a2017-01-31 00:57:56 -08002201 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002202 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002203 return;
2204 }
Steve Anton8a006912017-12-04 15:25:56 -08002205
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002207 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002208 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002209 return;
2210 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002211
Steve Anton80dd7b52018-02-16 17:08:42 -08002212 // If a session error has occurred the PeerConnection is in a possibly
2213 // inconsistent state so fail right away.
2214 if (session_error() != SessionError::kNone) {
2215 std::string error_message = GetSessionErrorMsg();
2216 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2217 observer->OnSetRemoteDescriptionComplete(
2218 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2219 return;
2220 }
Steve Anton71439a62018-02-15 11:53:06 -08002221
Steve Antonba42e992018-04-09 14:10:01 -07002222 if (desc->GetType() == SdpType::kOffer) {
2223 // Report to UMA the format of the received offer.
2224 ReportSdpFormatReceived(*desc);
2225 }
2226
Steve Anton80dd7b52018-02-16 17:08:42 -08002227 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002228 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002229 std::string error_message = GetSetDescriptionErrorMessage(
2230 cricket::CS_REMOTE, desc->GetType(), error);
2231 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002232 observer->OnSetRemoteDescriptionComplete(
2233 RTCError(error.type(), std::move(error_message)));
2234 return;
2235 }
Steve Anton71439a62018-02-15 11:53:06 -08002236
Steve Anton80dd7b52018-02-16 17:08:42 -08002237 // Grab the description type before moving ownership to
2238 // ApplyRemoteDescription, which may destroy it before returning.
2239 const SdpType type = desc->GetType();
2240
2241 error = ApplyRemoteDescription(std::move(desc));
2242 // |desc| may be destroyed at this point.
2243
2244 if (!error.ok()) {
2245 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2246 // inconsistent state, so act conservatively here and set the session error
2247 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2248 SetSessionError(SessionError::kContent, error.message());
2249 std::string error_message =
2250 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2251 RTC_LOG(LS_ERROR) << error_message;
2252 observer->OnSetRemoteDescriptionComplete(
2253 RTCError(error.type(), std::move(error_message)));
2254 return;
2255 }
2256 RTC_DCHECK(remote_description());
2257
2258 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002259 // TODO(deadbeef): We already had to hop to the network thread for
2260 // MaybeStartGathering...
2261 network_thread()->Invoke<void>(
2262 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2263 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002264 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002265 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002266 }
2267
2268 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002269 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002270}
2271
2272RTCError PeerConnection::ApplyRemoteDescription(
2273 std::unique_ptr<SessionDescriptionInterface> desc) {
2274 RTC_DCHECK_RUN_ON(signaling_thread());
2275 RTC_DCHECK(desc);
2276
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277 // Update stats here so that we have the most recent stats for tracks and
2278 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002279 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002280
Steve Antondcc3c022017-12-22 16:02:54 -08002281 // Take a reference to the old remote description since it's used below to
2282 // compare against the new remote description. When setting the new remote
2283 // description, grab ownership of the replaced session description in case it
2284 // is the same as |old_remote_description|, to keep it alive for the duration
2285 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002286 const SessionDescriptionInterface* old_remote_description =
2287 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002288 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002289 SdpType type = desc->GetType();
2290 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002291 replaced_remote_description = pending_remote_description_
2292 ? std::move(pending_remote_description_)
2293 : std::move(current_remote_description_);
2294 current_remote_description_ = std::move(desc);
2295 pending_remote_description_ = nullptr;
2296 current_local_description_ = std::move(pending_local_description_);
2297 } else {
2298 replaced_remote_description = std::move(pending_remote_description_);
2299 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002300 }
Steve Anton8a006912017-12-04 15:25:56 -08002301 // The session description to apply now must be accessed by
2302 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002303 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002304
Zhi Huange830e682018-03-30 10:48:35 -07002305 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2306 if (!error.ok()) {
2307 return error;
2308 }
Steve Anton8a006912017-12-04 15:25:56 -08002309 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002310 if (IsUnifiedPlan()) {
2311 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002312 cricket::CS_REMOTE, *remote_description(), local_description(),
2313 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002314 if (!error.ok()) {
2315 return error;
2316 }
Steve Antondcc3c022017-12-22 16:02:54 -08002317 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002318 // Media channels will be created only when offer is set. These may use new
2319 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002320 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002321 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002322 // description is applied. Restore back to old description.
2323 RTCError error = CreateChannels(*remote_description()->description());
2324 if (!error.ok()) {
2325 return error;
2326 }
2327 }
Steve Antondcc3c022017-12-22 16:02:54 -08002328 // Remove unused channels if MediaContentDescription is rejected.
2329 RemoveUnusedChannels(remote_description()->description());
2330 }
Steve Anton8a006912017-12-04 15:25:56 -08002331
Zhi Huange830e682018-03-30 10:48:35 -07002332 // NOTE: Candidates allocation will be initiated only when
2333 // SetLocalDescription is called.
2334 error = UpdateSessionState(type, cricket::CS_REMOTE,
2335 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002336 if (!error.ok()) {
2337 return error;
2338 }
2339
2340 if (local_description() &&
2341 !UseCandidatesInSessionDescription(remote_description())) {
2342 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2343 }
2344
2345 if (old_remote_description) {
2346 for (const cricket::ContentInfo& content :
2347 old_remote_description->description()->contents()) {
2348 // Check if this new SessionDescription contains new ICE ufrag and
2349 // password that indicates the remote peer requests an ICE restart.
2350 // TODO(deadbeef): When we start storing both the current and pending
2351 // remote description, this should reset pending_ice_restarts and compare
2352 // against the current description.
2353 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2354 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002355 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002356 pending_ice_restarts_.insert(content.name);
2357 }
2358 } else {
2359 // We retain all received candidates only if ICE is not restarted.
2360 // When ICE is restarted, all previous candidates belong to an old
2361 // generation and should not be kept.
2362 // TODO(deadbeef): This goes against the W3C spec which says the remote
2363 // description should only contain candidates from the last set remote
2364 // description plus any candidates added since then. We should remove
2365 // this once we're sure it won't break anything.
2366 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2367 old_remote_description, content.name, mutable_remote_description());
2368 }
2369 }
2370 }
2371
2372 if (session_error() != SessionError::kNone) {
2373 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2374 }
2375
2376 // Set the the ICE connection state to connecting since the connection may
2377 // become writable with peer reflexive candidates before any remote candidate
2378 // is signaled.
2379 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2380 // is to have a new signal the indicates a change in checking state from the
2381 // transport and expose a new checking() member from transport that can be
2382 // read to determine the current checking state. The existing SignalConnecting
2383 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002384 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002385 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002386 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2387 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2388 }
2389
deadbeefab9b2d12015-10-14 11:33:11 -07002390 // If setting the description decided our SSL role, allocate any necessary
2391 // SCTP sids.
2392 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002393 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002394 AllocateSctpSids(role);
2395 }
2396
Steve Antondcc3c022017-12-22 16:02:54 -08002397 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002398 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002399 now_receiving_transceivers;
2400 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
2401 no_longer_receiving_transceivers;
Steve Antonc49bcd92018-02-14 14:28:13 -08002402 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002403 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002404 for (auto transceiver : transceivers_) {
2405 const ContentInfo* content =
2406 FindMediaSectionForTransceiver(transceiver, remote_description());
2407 if (!content) {
2408 continue;
2409 }
2410 const MediaContentDescription* media_desc = content->media_description();
2411 RtpTransceiverDirection local_direction =
2412 RtpTransceiverDirectionReversed(media_desc->direction());
2413 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2414 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2415 // transceiver's current direction is neither sendrecv nor recvonly,
2416 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002417 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002418 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002419 // The remote description has signaled the stream IDs.
2420 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002421 }
Steve Antondcc3c022017-12-22 16:02:54 -08002422 if (RtpTransceiverDirectionHasRecv(local_direction) &&
2423 (!transceiver->current_direction() ||
2424 !RtpTransceiverDirectionHasRecv(
Seth Hampson2f0d7022018-02-20 11:54:42 -08002425 *transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002426 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002427 << content->name << " (added to "
2428 << GetStreamIdsString(stream_ids) << ").";
2429
2430 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2431 for (const std::string& stream_id : stream_ids) {
2432 rtc::scoped_refptr<MediaStreamInterface> stream =
2433 remote_streams_->find(stream_id);
2434 if (!stream) {
2435 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2436 MediaStream::Create(stream_id));
2437 remote_streams_->AddStream(stream);
2438 added_streams.push_back(stream);
2439 }
2440 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002441 }
Steve Anton3172c032018-05-03 15:30:18 -07002442 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002443 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2444 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002445 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002446 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002447 }
2448 // If direction is sendonly or inactive, and transceiver's current
2449 // direction is neither sendonly nor inactive, process the removal of a
2450 // remote track for the media description.
2451 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Antonef65ef12018-01-10 17:15:20 -08002452 (transceiver->current_direction() &&
Steve Antondcc3c022017-12-22 16:02:54 -08002453 RtpTransceiverDirectionHasRecv(*transceiver->current_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002454 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2455 << content->name;
Steve Anton3172c032018-05-03 15:30:18 -07002456 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2457 transceiver->internal()->receiver_internal()->streams();
2458 // This will remove the remote track from the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002459 transceiver->internal()->receiver_internal()->set_stream_ids({});
Steve Anton3172c032018-05-03 15:30:18 -07002460 no_longer_receiving_transceivers.push_back(transceiver);
2461 // Remove any streams that no longer have tracks.
Henrik Boström199e27b2018-07-04 20:51:53 +02002462 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2463 // of streams, see if the stream was removed by checking if this was the
2464 // last receiver with that stream ID.
Steve Anton3172c032018-05-03 15:30:18 -07002465 for (auto stream : media_streams) {
2466 if (stream->GetAudioTracks().empty() &&
2467 stream->GetVideoTracks().empty()) {
2468 remote_streams_->RemoveStream(stream);
2469 removed_streams.push_back(stream);
2470 }
2471 }
Steve Antondcc3c022017-12-22 16:02:54 -08002472 }
2473 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
2474 transceiver->internal()->set_current_direction(local_direction);
2475 }
2476 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002477 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2478 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002479 transceiver->Stop();
2480 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002481 if (!content->rejected &&
2482 RtpTransceiverDirectionHasRecv(local_direction)) {
2483 // Set ssrc to 0 in the case of an unsignalled ssrc.
2484 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002485 if (!media_desc->streams().empty() &&
2486 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002487 ssrc = media_desc->streams()[0].first_ssrc();
2488 }
2489 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002490 }
Steve Antondcc3c022017-12-22 16:02:54 -08002491 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002492 // Once all processing has finished, fire off callbacks.
Steve Anton3172c032018-05-03 15:30:18 -07002493 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002494 stats_->AddTrack(transceiver->receiver()->track());
Steve Anton8b815cd2018-02-16 16:14:42 -08002495 observer_->OnTrack(transceiver);
2496 observer_->OnAddTrack(transceiver->receiver(),
2497 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002498 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002499 for (auto stream : added_streams) {
2500 observer_->OnAddStream(stream);
2501 }
Steve Anton3172c032018-05-03 15:30:18 -07002502 for (auto transceiver : no_longer_receiving_transceivers) {
2503 observer_->OnRemoveTrack(transceiver->receiver());
2504 }
2505 for (auto stream : removed_streams) {
2506 observer_->OnRemoveStream(stream);
2507 }
Steve Antondcc3c022017-12-22 16:02:54 -08002508 }
2509
Henrik Boströmfdb92012017-11-09 19:55:44 +01002510 const cricket::ContentInfo* audio_content =
2511 GetFirstAudioContent(remote_description()->description());
2512 const cricket::ContentInfo* video_content =
2513 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002514 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002515 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002516 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002517 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002518 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002519 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002520
2521 // Check if the descriptions include streams, just in case the peer supports
2522 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002523 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002524 (audio_desc && !audio_desc->streams().empty()) ||
2525 (video_desc && !video_desc->streams().empty())) {
2526 remote_peer_supports_msid_ = true;
2527 }
deadbeefab9b2d12015-10-14 11:33:11 -07002528
2529 // We wait to signal new streams until we finish processing the description,
2530 // since only at that point will new streams have all their tracks.
2531 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2532
Steve Antondcc3c022017-12-22 16:02:54 -08002533 if (!IsUnifiedPlan()) {
2534 // TODO(steveanton): When removing RTP senders/receivers in response to a
2535 // rejected media section, there is some cleanup logic that expects the
2536 // voice/ video channel to still be set. But in this method the voice/video
2537 // channel would have been destroyed by the SetRemoteDescription caller
2538 // above so the cleanup that relies on them fails to run. The RemoveSenders
2539 // calls should be moved to right before the DestroyChannel calls to fix
2540 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002541
Steve Antondcc3c022017-12-22 16:02:54 -08002542 // Find all audio rtp streams and create corresponding remote AudioTracks
2543 // and MediaStreams.
2544 if (audio_content) {
2545 if (audio_content->rejected) {
2546 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2547 } else {
2548 bool default_audio_track_needed =
2549 !remote_peer_supports_msid_ &&
2550 RtpTransceiverDirectionHasSend(audio_desc->direction());
2551 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2552 default_audio_track_needed, audio_desc->type(),
2553 new_streams);
2554 }
deadbeeffaac4972015-11-12 15:33:07 -08002555 }
deadbeefab9b2d12015-10-14 11:33:11 -07002556
Steve Antondcc3c022017-12-22 16:02:54 -08002557 // Find all video rtp streams and create corresponding remote VideoTracks
2558 // and MediaStreams.
2559 if (video_content) {
2560 if (video_content->rejected) {
2561 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2562 } else {
2563 bool default_video_track_needed =
2564 !remote_peer_supports_msid_ &&
2565 RtpTransceiverDirectionHasSend(video_desc->direction());
2566 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2567 default_video_track_needed, video_desc->type(),
2568 new_streams);
2569 }
deadbeeffaac4972015-11-12 15:33:07 -08002570 }
deadbeefab9b2d12015-10-14 11:33:11 -07002571
Steve Antondcc3c022017-12-22 16:02:54 -08002572 // Update the DataChannels with the information from the remote peer.
2573 if (data_desc) {
2574 if (rtc::starts_with(data_desc->protocol().data(),
2575 cricket::kMediaProtocolRtpPrefix)) {
2576 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2577 }
deadbeefab9b2d12015-10-14 11:33:11 -07002578 }
deadbeefab9b2d12015-10-14 11:33:11 -07002579
Steve Antondcc3c022017-12-22 16:02:54 -08002580 // Iterate new_streams and notify the observer about new MediaStreams.
2581 for (size_t i = 0; i < new_streams->count(); ++i) {
2582 MediaStreamInterface* new_stream = new_streams->at(i);
2583 stats_->AddStream(new_stream);
2584 observer_->OnAddStream(
2585 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2586 }
deadbeefab9b2d12015-10-14 11:33:11 -07002587
Steve Antondcc3c022017-12-22 16:02:54 -08002588 UpdateEndedRemoteMediaStreams();
2589 }
deadbeefab9b2d12015-10-14 11:33:11 -07002590
Steve Anton8a006912017-12-04 15:25:56 -08002591 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002592}
2593
Steve Antondcc3c022017-12-22 16:02:54 -08002594RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2595 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002596 const SessionDescriptionInterface& new_session,
2597 const SessionDescriptionInterface* old_local_description,
2598 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002599 RTC_DCHECK(IsUnifiedPlan());
2600
Steve Anton7464fca2018-01-19 11:10:37 -08002601 const cricket::ContentGroup* bundle_group = nullptr;
2602 if (new_session.GetType() == SdpType::kOffer) {
2603 auto bundle_group_or_error =
2604 GetEarlyBundleGroup(*new_session.description());
2605 if (!bundle_group_or_error.ok()) {
2606 return bundle_group_or_error.MoveError();
2607 }
2608 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002609 }
Steve Antondcc3c022017-12-22 16:02:54 -08002610
Steve Antondcc3c022017-12-22 16:02:54 -08002611 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002612 for (size_t i = 0; i < new_contents.size(); ++i) {
2613 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002614 cricket::MediaType media_type = new_content.media_description()->type();
2615 seen_mids_.insert(new_content.name);
2616 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2617 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002618 const cricket::ContentInfo* old_local_content = nullptr;
2619 if (old_local_description &&
2620 i < old_local_description->description()->contents().size()) {
2621 old_local_content =
2622 &old_local_description->description()->contents()[i];
2623 }
2624 const cricket::ContentInfo* old_remote_content = nullptr;
2625 if (old_remote_description &&
2626 i < old_remote_description->description()->contents().size()) {
2627 old_remote_content =
2628 &old_remote_description->description()->contents()[i];
2629 }
Steve Antondcc3c022017-12-22 16:02:54 -08002630 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002631 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2632 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002633 if (!transceiver_or_error.ok()) {
2634 return transceiver_or_error.MoveError();
2635 }
2636 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002637 RTCError error =
2638 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2639 if (!error.ok()) {
2640 return error;
2641 }
2642 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002643 if (GetDataMid() && new_content.name != *GetDataMid()) {
2644 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002645 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2646 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002647 continue;
2648 }
2649 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2650 if (!error.ok()) {
2651 return error;
2652 }
Steve Antondcc3c022017-12-22 16:02:54 -08002653 } else {
2654 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2655 "Unknown section type.");
2656 }
2657 }
2658
2659 return RTCError::OK();
2660}
2661
2662RTCError PeerConnection::UpdateTransceiverChannel(
2663 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2664 transceiver,
2665 const cricket::ContentInfo& content,
2666 const cricket::ContentGroup* bundle_group) {
2667 RTC_DCHECK(IsUnifiedPlan());
2668 RTC_DCHECK(transceiver);
2669 cricket::BaseChannel* channel = transceiver->internal()->channel();
2670 if (content.rejected) {
2671 if (channel) {
2672 transceiver->internal()->SetChannel(nullptr);
2673 DestroyBaseChannel(channel);
2674 }
2675 } else {
2676 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002677 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002678 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002679 } else {
Steve Anton69470252018-02-09 11:43:08 -08002680 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002681 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002682 }
2683 if (!channel) {
2684 LOG_AND_RETURN_ERROR(
2685 RTCErrorType::INTERNAL_ERROR,
2686 "Failed to create channel for mid=" + content.name);
2687 }
2688 transceiver->internal()->SetChannel(channel);
2689 }
2690 }
2691 return RTCError::OK();
2692}
2693
Steve Antonfa2260d2017-12-28 16:38:23 -08002694RTCError PeerConnection::UpdateDataChannel(
2695 cricket::ContentSource source,
2696 const cricket::ContentInfo& content,
2697 const cricket::ContentGroup* bundle_group) {
2698 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002699 // If data channels are disabled, ignore this media section. CreateAnswer
2700 // will take care of rejecting it.
2701 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002702 }
2703 if (content.rejected) {
2704 DestroyDataChannel();
2705 } else {
2706 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002707 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002708 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2709 "Failed to create data channel.");
2710 }
2711 }
2712 if (source == cricket::CS_REMOTE) {
2713 const MediaContentDescription* data_desc = content.media_description();
2714 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2715 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2716 }
2717 }
2718 }
2719 return RTCError::OK();
2720}
2721
Steve Antondcc3c022017-12-22 16:02:54 -08002722RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2723PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002724 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002725 size_t mline_index,
2726 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002727 const ContentInfo* old_local_content,
2728 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002729 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002730 // If this is an offer then the m= section might be recycled. If the m=
2731 // section is being recycled (defined as: rejected in the current local or
2732 // remote description and not rejected in new description), dissociate the
2733 // currently associated RtpTransceiver by setting its mid property to null,
2734 // and discard the mapping between the transceiver and its m= section index.
2735 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2736 old_remote_content)) {
2737 // We want to dissociate the transceiver that has the rejected mid.
2738 const std::string& old_mid =
2739 (old_local_content && old_local_content->rejected)
2740 ? old_local_content->name
2741 : old_remote_content->name;
2742 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002743 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002744 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2745 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002746 old_transceiver->internal()->set_mid(absl::nullopt);
2747 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002748 }
2749 }
2750 const MediaContentDescription* media_desc = content.media_description();
2751 auto transceiver = GetAssociatedTransceiver(content.name);
2752 if (source == cricket::CS_LOCAL) {
2753 // Find the RtpTransceiver that corresponds to this m= section, using the
2754 // mapping between transceivers and m= section indices established when
2755 // creating the offer.
2756 if (!transceiver) {
2757 transceiver = GetTransceiverByMLineIndex(mline_index);
2758 }
2759 if (!transceiver) {
2760 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2761 "Unknown transceiver");
2762 }
2763 } else {
2764 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2765 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2766 // of the same type...
2767 if (!transceiver &&
2768 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2769 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2770 }
2771 // If no RtpTransceiver was found in the previous step, create one with a
2772 // recvonly direction.
2773 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002774 RTC_LOG(LS_INFO) << "Adding "
2775 << cricket::MediaTypeToString(media_desc->type())
2776 << " transceiver for MID=" << content.name
2777 << " at i=" << mline_index
2778 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002779 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002780 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002781 std::string receiver_id;
2782 if (!media_desc->streams().empty()) {
2783 receiver_id = media_desc->streams()[0].id;
2784 } else {
2785 receiver_id = rtc::CreateRandomUuid();
2786 }
2787 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002788 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002789 transceiver->internal()->set_direction(
2790 RtpTransceiverDirection::kRecvOnly);
2791 }
2792 }
2793 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002794 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002795 LOG_AND_RETURN_ERROR(
2796 RTCErrorType::INVALID_PARAMETER,
2797 "Transceiver type does not match media description type.");
2798 }
2799 // Associate the found or created RtpTransceiver with the m= section by
2800 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2801 // section, and establish a mapping between the transceiver and the index of
2802 // the m= section.
2803 transceiver->internal()->set_mid(content.name);
2804 transceiver->internal()->set_mline_index(mline_index);
2805 return std::move(transceiver);
2806}
2807
2808rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2809PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2810 RTC_DCHECK(IsUnifiedPlan());
2811 for (auto transceiver : transceivers_) {
2812 if (transceiver->mid() == mid) {
2813 return transceiver;
2814 }
2815 }
2816 return nullptr;
2817}
2818
2819rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2820PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2821 RTC_DCHECK(IsUnifiedPlan());
2822 for (auto transceiver : transceivers_) {
2823 if (transceiver->internal()->mline_index() == mline_index) {
2824 return transceiver;
2825 }
2826 }
2827 return nullptr;
2828}
2829
2830rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2831PeerConnection::FindAvailableTransceiverToReceive(
2832 cricket::MediaType media_type) const {
2833 RTC_DCHECK(IsUnifiedPlan());
2834 // From JSEP section 5.10 (Applying a Remote Description):
2835 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2836 // the same type that were added to the PeerConnection by addTrack and are not
2837 // associated with any m= section and are not stopped, find the first such
2838 // RtpTransceiver.
2839 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002840 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002841 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2842 !transceiver->stopped()) {
2843 return transceiver;
2844 }
2845 }
2846 return nullptr;
2847}
2848
Steve Antoned10bd92017-12-05 10:52:59 -08002849const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2850 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2851 transceiver,
2852 const SessionDescriptionInterface* sdesc) const {
2853 RTC_DCHECK(transceiver);
2854 RTC_DCHECK(sdesc);
2855 if (IsUnifiedPlan()) {
2856 if (!transceiver->internal()->mid()) {
2857 // This transceiver is not associated with a media section yet.
2858 return nullptr;
2859 }
2860 return sdesc->description()->GetContentByName(
2861 *transceiver->internal()->mid());
2862 } else {
2863 // Plan B only allows at most one audio and one video section, so use the
2864 // first media section of that type.
2865 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002866 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002867 }
2868}
2869
deadbeef46c73892016-11-16 19:42:04 -08002870PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2871 return configuration_;
2872}
2873
deadbeef293e9262017-01-11 12:28:30 -08002874bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2875 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002876 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002877 if (IsClosed()) {
2878 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2879 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2880 }
2881
Qingsi Wanga2d60672018-04-11 16:57:45 -07002882 // According to JSEP, after setLocalDescription, changing the candidate pool
2883 // size is not allowed, and changing the set of ICE servers will not result
2884 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002885 if (local_description() && configuration.ice_candidate_pool_size !=
2886 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002887 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2888 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002889 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002890 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002891
deadbeef293e9262017-01-11 12:28:30 -08002892 // The simplest (and most future-compatible) way to tell if the config was
2893 // modified in an invalid way is to copy each property we do support
2894 // modifying, then use operator==. There are far more properties we don't
2895 // support modifying than those we do, and more could be added.
2896 RTCConfiguration modified_config = configuration_;
2897 modified_config.servers = configuration.servers;
2898 modified_config.type = configuration.type;
2899 modified_config.ice_candidate_pool_size =
2900 configuration.ice_candidate_pool_size;
2901 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002902 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002903 modified_config.ice_check_interval_strong_connectivity =
2904 configuration.ice_check_interval_strong_connectivity;
2905 modified_config.ice_check_interval_weak_connectivity =
2906 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002907 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2908 modified_config.ice_unwritable_min_checks =
2909 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002910 modified_config.stun_candidate_keepalive_interval =
2911 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002912 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002913 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002914 modified_config.active_reset_srtp_params =
2915 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002916 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002917 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002918 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2919 }
2920
Steve Anton038834f2017-07-14 15:59:59 -07002921 // Validate the modified configuration.
2922 RTCError validate_error = ValidateConfiguration(modified_config);
2923 if (!validate_error.ok()) {
2924 return SafeSetError(std::move(validate_error), error);
2925 }
2926
deadbeef293e9262017-01-11 12:28:30 -08002927 // Note that this isn't possible through chromium, since it's an unsigned
2928 // short in WebIDL.
2929 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002930 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002931 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2932 }
2933
2934 // Parse ICE servers before hopping to network thread.
2935 cricket::ServerAddresses stun_servers;
2936 std::vector<cricket::RelayServerConfig> turn_servers;
2937 RTCErrorType parse_error =
2938 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2939 if (parse_error != RTCErrorType::NONE) {
2940 return SafeSetError(parse_error, error);
2941 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002942 // Note if STUN or TURN servers were supplied.
2943 if (!stun_servers.empty()) {
2944 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2945 }
2946 if (!turn_servers.empty()) {
2947 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2948 }
deadbeef293e9262017-01-11 12:28:30 -08002949
2950 // In theory this shouldn't fail.
2951 if (!network_thread()->Invoke<bool>(
2952 RTC_FROM_HERE,
2953 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2954 stun_servers, turn_servers, modified_config.type,
2955 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002956 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002957 modified_config.turn_customizer,
2958 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002959 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002960 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2961 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002962
deadbeefd1a38b52016-12-10 13:15:33 -08002963 // As described in JSEP, calling setConfiguration with new ICE servers or
2964 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2965 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002966 if (modified_config.servers != configuration_.servers ||
2967 modified_config.type != configuration_.type ||
2968 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002969 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002970 }
skvladd1f5fda2017-02-03 16:54:05 -08002971
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002972 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002973
Zhi Huangb57e1692018-06-12 11:41:11 -07002974 if (configuration_.active_reset_srtp_params !=
2975 modified_config.active_reset_srtp_params) {
2976 transport_controller_->SetActiveResetSrtpParams(
2977 modified_config.active_reset_srtp_params);
2978 }
2979
deadbeef293e9262017-01-11 12:28:30 -08002980 configuration_ = modified_config;
2981 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002982}
2983
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002984bool PeerConnection::AddIceCandidate(
2985 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002986 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002987 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002988 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
zhihuang29ff8442016-07-27 11:07:25 -07002989 return false;
2990 }
Steve Antond25da372017-11-06 14:50:29 -08002991
2992 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002993 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002994 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002995 return false;
2996 }
2997
2998 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002999 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Steve Antond25da372017-11-06 14:50:29 -08003000 return false;
3001 }
3002
3003 bool valid = false;
3004 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3005 if (!valid) {
3006 return false;
3007 }
3008
3009 // Add this candidate to the remote session description.
3010 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003011 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08003012 return false;
3013 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003014 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
Steve Antond25da372017-11-06 14:50:29 -08003015
3016 if (ready) {
3017 return UseCandidate(ice_candidate);
3018 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003019 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08003020 return true;
3021 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003022}
3023
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003024bool PeerConnection::RemoveIceCandidates(
3025 const std::vector<cricket::Candidate>& candidates) {
3026 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003027 if (IsClosed()) {
3028 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3029 return false;
3030 }
3031
Steve Antond25da372017-11-06 14:50:29 -08003032 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003033 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3034 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003035 return false;
3036 }
3037
3038 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003039 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003040 return false;
3041 }
3042
3043 size_t number_removed =
3044 mutable_remote_description()->RemoveCandidates(candidates);
3045 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003046 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003047 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003048 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003049 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003050 }
3051
3052 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003053 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3054 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003055 RTC_LOG(LS_ERROR)
3056 << "RemoveIceCandidates: Error when removing remote candidates: "
3057 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003058 }
3059 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003060}
3061
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003062void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003063 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
Qingsi Wanga2d60672018-04-11 16:57:45 -07003064 network_thread()->Invoke<void>(
3065 RTC_FROM_HERE,
3066 rtc::Bind(&PeerConnection::SetMetricObserver_n, this, observer));
Qingsi Wang78fef762018-07-11 18:33:52 +00003067 // Send information about IPv4/IPv6 status.
3068 if (uma_observer_) {
3069 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
3070 uma_observer_->IncrementEnumCounter(
3071 kEnumCounterAddressFamily, kPeerConnection_IPv6,
3072 kPeerConnectionAddressFamilyCounter_Max);
3073 } else {
3074 uma_observer_->IncrementEnumCounter(
3075 kEnumCounterAddressFamily, kPeerConnection_IPv4,
3076 kPeerConnectionAddressFamilyCounter_Max);
3077 }
3078 }
Qingsi Wanga2d60672018-04-11 16:57:45 -07003079}
Patrik Höglund3dc41062018-04-11 11:13:57 +00003080
Qingsi Wanga2d60672018-04-11 16:57:45 -07003081void PeerConnection::SetMetricObserver_n(UMAObserver* observer) {
3082 RTC_DCHECK(network_thread()->IsCurrent());
3083 uma_observer_ = observer;
Steve Antonc79268f2018-04-24 09:54:10 -07003084 if (transport_controller_) {
3085 transport_controller_->SetMetricsObserver(uma_observer_);
Patrik Höglund3dc41062018-04-11 11:13:57 +00003086 }
3087
3088 for (auto transceiver : transceivers_) {
3089 auto* channel = transceiver->internal()->channel();
3090 if (channel) {
3091 channel->SetMetricsObserver(uma_observer_);
3092 }
3093 }
3094
deadbeef293e9262017-01-11 12:28:30 -08003095 if (uma_observer_) {
Patrik Höglund3dc41062018-04-11 11:13:57 +00003096 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00003097 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00003098}
3099
Niels Möller0c4f7be2018-05-07 14:01:37 +02003100RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003101 if (!worker_thread()->IsCurrent()) {
3102 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003103 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003104 }
3105
Niels Möller0c4f7be2018-05-07 14:01:37 +02003106 const bool has_min = bitrate.min_bitrate_bps.has_value();
3107 const bool has_start = bitrate.start_bitrate_bps.has_value();
3108 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003109 if (has_min && *bitrate.min_bitrate_bps < 0) {
3110 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3111 "min_bitrate_bps <= 0");
3112 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003113 if (has_start) {
3114 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003115 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003116 "start_bitrate_bps < min_bitrate_bps");
3117 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003118 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3119 "curent_bitrate_bps < 0");
3120 }
3121 }
3122 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003123 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003124 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003125 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003126 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3127 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3128 "max_bitrate_bps < min_bitrate_bps");
3129 } else if (*bitrate.max_bitrate_bps < 0) {
3130 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3131 "max_bitrate_bps < 0");
3132 }
3133 }
3134
zstein4b979802017-06-02 14:37:37 -07003135 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003136 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003137
3138 return RTCError::OK();
3139}
3140
Alex Narest78609d52017-10-20 10:37:47 +02003141void PeerConnection::SetBitrateAllocationStrategy(
3142 std::unique_ptr<rtc::BitrateAllocationStrategy>
3143 bitrate_allocation_strategy) {
3144 rtc::Thread* worker_thread = factory_->worker_thread();
3145 if (!worker_thread->IsCurrent()) {
3146 rtc::BitrateAllocationStrategy* strategy_raw =
3147 bitrate_allocation_strategy.release();
3148 auto functor = [this, strategy_raw]() {
3149 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003150 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003151 };
3152 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3153 return;
3154 }
3155 RTC_DCHECK(call_.get());
3156 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3157}
3158
henrika5f6bf242017-11-01 11:06:56 +01003159void PeerConnection::SetAudioPlayout(bool playout) {
3160 if (!worker_thread()->IsCurrent()) {
3161 worker_thread()->Invoke<void>(
3162 RTC_FROM_HERE,
3163 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3164 return;
3165 }
3166 auto audio_state =
3167 factory_->channel_manager()->media_engine()->GetAudioState();
3168 audio_state->SetPlayout(playout);
3169}
3170
3171void PeerConnection::SetAudioRecording(bool recording) {
3172 if (!worker_thread()->IsCurrent()) {
3173 worker_thread()->Invoke<void>(
3174 RTC_FROM_HERE,
3175 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3176 return;
3177 }
3178 auto audio_state =
3179 factory_->channel_manager()->media_engine()->GetAudioState();
3180 audio_state->SetRecording(recording);
3181}
3182
Steve Anton8c0f7a72017-10-03 10:03:10 -07003183std::unique_ptr<rtc::SSLCertificate>
3184PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003185 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3186 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003187 return nullptr;
3188 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003189 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003190}
3191
Zhi Huang70b820f2018-01-27 14:16:15 -08003192std::unique_ptr<rtc::SSLCertChain>
3193PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003194 auto audio_transceiver = GetFirstAudioTransceiver();
3195 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003196 return nullptr;
3197 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003198 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003199 audio_transceiver->internal()->channel()->transport_name());
3200}
3201
3202rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3203PeerConnection::GetFirstAudioTransceiver() const {
3204 for (auto transceiver : transceivers_) {
3205 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3206 return transceiver;
3207 }
3208 }
3209 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003210}
3211
ivoc14d5dbe2016-07-04 07:06:55 -07003212bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3213 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003214 // TODO(eladalon): It would be better to not allow negative values into PC.
3215 const size_t max_size = (max_size_bytes < 0)
3216 ? RtcEventLog::kUnlimitedOutput
3217 : rtc::saturated_cast<size_t>(max_size_bytes);
3218 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003219 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003220 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003221}
3222
Bjorn Tereliusde939432017-11-20 17:38:14 +01003223bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3224 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003225 // TODO(eladalon): In C++14, this can be done with a lambda.
3226 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003227 bool operator()() {
3228 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3229 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003230 PeerConnection* const pc;
3231 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003232 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003233 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003234 return worker_thread()->Invoke<bool>(
3235 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003236}
3237
3238void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003239 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003240 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3241}
3242
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003243const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003244 return pending_local_description_ ? pending_local_description_.get()
3245 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246}
3247
3248const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003249 return pending_remote_description_ ? pending_remote_description_.get()
3250 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251}
3252
deadbeeffe4a8a42016-12-20 17:56:17 -08003253const SessionDescriptionInterface* PeerConnection::current_local_description()
3254 const {
Steve Anton75737c02017-11-06 10:37:17 -08003255 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003256}
3257
3258const SessionDescriptionInterface* PeerConnection::current_remote_description()
3259 const {
Steve Anton75737c02017-11-06 10:37:17 -08003260 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003261}
3262
3263const SessionDescriptionInterface* PeerConnection::pending_local_description()
3264 const {
Steve Anton75737c02017-11-06 10:37:17 -08003265 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003266}
3267
3268const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3269 const {
Steve Anton75737c02017-11-06 10:37:17 -08003270 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003271}
3272
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003273void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003274 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275 // Update stats here so that we have the most recent stats for tracks and
3276 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003277 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003278
Steve Anton75737c02017-11-06 10:37:17 -08003279 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003280 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003281
Steve Anton8af21862017-12-15 11:20:13 -08003282 for (auto transceiver : transceivers_) {
3283 transceiver->Stop();
3284 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003285
3286 // Ensure that all asynchronous stats requests are completed before destroying
3287 // the transport controller below.
3288 if (stats_collector_) {
3289 stats_collector_->WaitForPendingRequest();
3290 }
3291
3292 // Don't destroy BaseChannels until after stats has been cleaned up so that
3293 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003294 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003295
Qingsi Wang93a84392018-01-30 17:13:09 -08003296 // The event log is used in the transport controller, which must be outlived
3297 // by the former. CreateOffer by the peer connection is implemented
3298 // asynchronously and if the peer connection is closed without resetting the
3299 // WebRTC session description factory, the session description factory would
3300 // call the transport controller.
3301 webrtc_session_desc_factory_.reset();
3302 transport_controller_.reset();
3303
deadbeef42a42632017-03-10 15:18:00 -08003304 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003305 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3306 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003307
Steve Anton978b8762017-09-29 12:15:02 -07003308 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003309 call_.reset();
3310 // The event log must outlive call (and any other object that uses it).
3311 event_log_.reset();
3312 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003313 ReportUsagePattern();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003314}
3315
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00003316void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003317 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003318 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3319 SetSessionDescriptionMsg* param =
3320 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3321 param->observer->OnSuccess();
3322 delete param;
3323 break;
3324 }
3325 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3326 SetSessionDescriptionMsg* param =
3327 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003328 param->observer->OnFailure(std::move(param->error));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003329 delete param;
3330 break;
3331 }
deadbeefab9b2d12015-10-14 11:33:11 -07003332 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3333 CreateSessionDescriptionMsg* param =
3334 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003335 param->observer->OnFailure(std::move(param->error));
deadbeefab9b2d12015-10-14 11:33:11 -07003336 delete param;
3337 break;
3338 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339 case MSG_GETSTATS: {
3340 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08003341 StatsReports reports;
3342 stats_->GetStats(param->track, &reports);
3343 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003344 delete param;
3345 break;
3346 }
deadbeefbd292462015-12-14 18:15:29 -08003347 case MSG_FREE_DATACHANNELS: {
3348 sctp_data_channels_to_free_.clear();
3349 break;
3350 }
Harald Alvestrand19793842018-06-25 12:03:50 +02003351 case MSG_REPORT_USAGE_PATTERN: {
3352 ReportUsagePattern();
3353 break;
3354 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003355 default:
nisseeb4ca4e2017-01-12 02:24:27 -08003356 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357 break;
3358 }
3359}
3360
Steve Antonafb0bb72018-02-20 11:35:37 -08003361cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3362 RTC_DCHECK(!IsUnifiedPlan());
3363 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3364 GetAudioTransceiver()->internal()->channel());
3365 if (voice_channel) {
3366 return voice_channel->media_channel();
3367 } else {
3368 return nullptr;
3369 }
3370}
3371
3372cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3373 RTC_DCHECK(!IsUnifiedPlan());
3374 auto* video_channel = static_cast<cricket::VideoChannel*>(
3375 GetVideoTransceiver()->internal()->channel());
3376 if (video_channel) {
3377 return video_channel->media_channel();
3378 } else {
3379 return nullptr;
3380 }
3381}
3382
Steve Anton4171afb2017-11-20 10:20:22 -08003383void PeerConnection::CreateAudioReceiver(
3384 MediaStreamInterface* stream,
3385 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003386 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3387 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003388 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3389 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003390 auto* audio_receiver = new AudioRtpReceiver(
3391 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003392 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003393 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3394 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3395 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003396 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003397 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003398 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003399}
3400
Steve Anton4171afb2017-11-20 10:20:22 -08003401void PeerConnection::CreateVideoReceiver(
3402 MediaStreamInterface* stream,
3403 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003404 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3405 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003406 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3407 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003408 auto* video_receiver = new VideoRtpReceiver(
3409 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003410 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003411 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3412 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3413 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003414 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003415 observer_->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003416 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003417}
3418
deadbeef70ab1a12015-09-28 16:53:55 -07003419// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3420// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003421rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003422 const RtpSenderInfo& remote_sender_info) {
3423 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3424 if (!receiver) {
3425 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3426 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003427 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003428 }
Steve Anton4171afb2017-11-20 10:20:22 -08003429 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3430 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3431 } else {
3432 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3433 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003434 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003435}
3436
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003437void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3438 MediaStreamInterface* stream) {
3439 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003440 RTC_DCHECK(track);
3441 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003442 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003443 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003444 // We already have a sender for this track, so just change the stream_id
3445 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003446 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003447 return;
3448 }
3449
3450 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003451 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3452 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003453 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003454 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003455 // If the sender has already been configured in SDP, we call SetSsrc,
3456 // which will connect the sender to the underlying transport. This can
3457 // occur if a local session description that contains the ID of the sender
3458 // is set before AddStream is called. It can also occur if the local
3459 // session description is not changed and RemoveStream is called, and
3460 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003461 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003462 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003463 if (sender_info) {
3464 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003465 }
3466}
3467
3468// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3469// indefinitely, when we have unified plan SDP.
3470void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3471 MediaStreamInterface* stream) {
3472 RTC_DCHECK(!IsClosed());
3473 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003474 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003475 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3476 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003477 return;
3478 }
Steve Anton4171afb2017-11-20 10:20:22 -08003479 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003480}
3481
3482void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3483 MediaStreamInterface* stream) {
3484 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003485 RTC_DCHECK(track);
3486 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003487 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003488 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003489 // We already have a sender for this track, so just change the stream_id
3490 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003491 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003492 return;
3493 }
3494
3495 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003496 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3497 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003498 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003499 GetVideoTransceiver()->internal()->AddSender(new_sender);
3500 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003501 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003502 if (sender_info) {
3503 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003504 }
3505}
3506
3507void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3508 MediaStreamInterface* stream) {
3509 RTC_DCHECK(!IsClosed());
3510 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003511 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003512 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3513 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003514 return;
3515 }
Steve Anton4171afb2017-11-20 10:20:22 -08003516 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003517}
3518
Steve Antonba818672017-11-06 10:21:57 -08003519void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003520 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003521 if (ice_connection_state_ == new_state) {
3522 return;
3523 }
3524
deadbeefcbecd352015-09-23 11:50:27 -07003525 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003526 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003527 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003528 return;
3529 }
Steve Antonba818672017-11-06 10:21:57 -08003530
Mirko Bonadei675513b2017-11-09 11:09:25 +01003531 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3532 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003533 RTC_DCHECK(ice_connection_state_ !=
3534 PeerConnectionInterface::kIceConnectionClosed);
3535
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003536 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003537 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538}
3539
3540void PeerConnection::OnIceGatheringChange(
3541 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003542 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003543 if (IsClosed()) {
3544 return;
3545 }
3546 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00003547 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003548}
3549
jbauch81bf7b02017-03-25 08:31:12 -07003550void PeerConnection::OnIceCandidate(
3551 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003552 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003553 if (IsClosed()) {
3554 return;
3555 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003556 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
jbauch81bf7b02017-03-25 08:31:12 -07003557 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003558}
3559
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003560void PeerConnection::OnIceCandidatesRemoved(
3561 const std::vector<cricket::Candidate>& candidates) {
3562 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003563 if (IsClosed()) {
3564 return;
3565 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003566 observer_->OnIceCandidatesRemoved(candidates);
3567}
3568
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003569void PeerConnection::ChangeSignalingState(
3570 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003571 RTC_DCHECK(signaling_thread()->IsCurrent());
3572 if (signaling_state_ == signaling_state) {
3573 return;
3574 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003575 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3576 << GetSignalingStateString(signaling_state_)
3577 << " New state: "
3578 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003579 signaling_state_ = signaling_state;
3580 if (signaling_state == kClosed) {
3581 ice_connection_state_ = kIceConnectionClosed;
3582 observer_->OnIceConnectionChange(ice_connection_state_);
3583 if (ice_gathering_state_ != kIceGatheringComplete) {
3584 ice_gathering_state_ = kIceGatheringComplete;
3585 observer_->OnIceGatheringChange(ice_gathering_state_);
3586 }
3587 }
3588 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003589}
3590
deadbeefeb459812015-12-15 19:24:43 -08003591void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3592 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003593 if (IsClosed()) {
3594 return;
3595 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003596 AddAudioTrack(track, stream);
3597 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003598}
3599
deadbeefeb459812015-12-15 19:24:43 -08003600void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3601 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003602 if (IsClosed()) {
3603 return;
3604 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003605 RemoveAudioTrack(track, stream);
3606 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003607}
3608
3609void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3610 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003611 if (IsClosed()) {
3612 return;
3613 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003614 AddVideoTrack(track, stream);
3615 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003616}
3617
3618void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3619 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003620 if (IsClosed()) {
3621 return;
3622 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003623 RemoveVideoTrack(track, stream);
3624 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003625}
3626
Henrik Boström31638672017-11-23 17:48:32 +01003627void PeerConnection::PostSetSessionDescriptionSuccess(
3628 SetSessionDescriptionObserver* observer) {
3629 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3630 signaling_thread()->Post(RTC_FROM_HERE, this,
3631 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
3632}
3633
deadbeefab9b2d12015-10-14 11:33:11 -07003634void PeerConnection::PostSetSessionDescriptionFailure(
3635 SetSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003636 RTCError&& error) {
3637 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003638 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003639 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003640 signaling_thread()->Post(RTC_FROM_HERE, this,
3641 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003642}
3643
3644void PeerConnection::PostCreateSessionDescriptionFailure(
3645 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003646 RTCError error) {
3647 RTC_DCHECK(!error.ok());
deadbeefab9b2d12015-10-14 11:33:11 -07003648 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003649 msg->error = std::move(error);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003650 signaling_thread()->Post(RTC_FROM_HERE, this,
3651 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003652}
3653
zhihuang1c378ed2017-08-17 14:10:50 -07003654void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003655 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003656 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003657 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003658
Steve Antondcc3c022017-12-22 16:02:54 -08003659 if (IsUnifiedPlan()) {
3660 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3661 } else {
3662 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3663 }
3664
Steve Antonfa2260d2017-12-28 16:38:23 -08003665 // Intentionally unset the data channel type for RTP data channel with the
3666 // second condition. Otherwise the RTP data channels would be successfully
3667 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3668 // when building with chromium. We want to leave RTP data channels broken, so
3669 // people won't try to use them.
3670 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3671 session_options->data_channel_type = data_channel_type();
3672 }
3673
Steve Antondcc3c022017-12-22 16:02:54 -08003674 // Apply ICE restart flag and renomination flag.
3675 for (auto& options : session_options->media_description_options) {
3676 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3677 options.transport_options.enable_ice_renomination =
3678 configuration_.enable_ice_renomination;
3679 }
3680
3681 session_options->rtcp_cname = rtcp_cname_;
3682 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003683 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003684}
3685
3686void PeerConnection::GetOptionsForPlanBOffer(
3687 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3688 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003689 // Figure out transceiver directional preferences.
3690 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3691 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3692
3693 // By default, generate sendrecv/recvonly m= sections.
3694 bool recv_audio = true;
3695 bool recv_video = true;
3696
3697 // By default, only offer a new m= section if we have media to send with it.
3698 bool offer_new_audio_description = send_audio;
3699 bool offer_new_video_description = send_video;
3700 bool offer_new_data_description = HasDataChannels();
3701
3702 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003703 if (offer_answer_options.offer_to_receive_audio !=
3704 RTCOfferAnswerOptions::kUndefined) {
3705 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003706 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003707 offer_new_audio_description ||
3708 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003709 }
Steve Antondcc3c022017-12-22 16:02:54 -08003710 if (offer_answer_options.offer_to_receive_video !=
3711 RTCOfferAnswerOptions::kUndefined) {
3712 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003713 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003714 offer_new_video_description ||
3715 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003716 }
3717
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003718 absl::optional<size_t> audio_index;
3719 absl::optional<size_t> video_index;
3720 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003721 // If a current description exists, generate m= sections in the same order,
3722 // using the first audio/video/data section that appears and rejecting
3723 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003724 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003725 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003726 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003727 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3728 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3729 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003730 }
3731
zhihuang1c378ed2017-08-17 14:10:50 -07003732 // Add audio/video/data m= sections to the end if needed.
3733 if (!audio_index && offer_new_audio_description) {
3734 session_options->media_description_options.push_back(
3735 cricket::MediaDescriptionOptions(
3736 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003737 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3738 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003739 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003740 }
zhihuang1c378ed2017-08-17 14:10:50 -07003741 if (!video_index && offer_new_video_description) {
3742 session_options->media_description_options.push_back(
3743 cricket::MediaDescriptionOptions(
3744 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003745 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3746 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003747 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003748 }
zhihuang1c378ed2017-08-17 14:10:50 -07003749 if (!data_index && offer_new_data_description) {
3750 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003751 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003752 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003753 }
3754
3755 cricket::MediaDescriptionOptions* audio_media_description_options =
3756 !audio_index ? nullptr
3757 : &session_options->media_description_options[*audio_index];
3758 cricket::MediaDescriptionOptions* video_media_description_options =
3759 !video_index ? nullptr
3760 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003761
Steve Anton4171afb2017-11-20 10:20:22 -08003762 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003763 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003764}
3765
3766// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3767// and return a reference to it.
3768// Generated MIDs should be no more than 3 bytes long to take up less space in
3769// the RTP packet.
3770static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3771 RTC_DCHECK(used_mids);
3772 // We're boring: just generate MIDs 0, 1, 2, ...
3773 size_t i = 0;
3774 std::set<std::string>::iterator it;
3775 bool inserted;
3776 do {
3777 std::string mid = rtc::ToString(i++);
3778 auto insert_result = used_mids->insert(mid);
3779 it = insert_result.first;
3780 inserted = insert_result.second;
3781 } while (!inserted);
3782 return *it;
3783}
3784
3785static cricket::MediaDescriptionOptions
3786GetMediaDescriptionOptionsForTransceiver(
3787 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3788 transceiver,
3789 const std::string& mid) {
3790 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003791 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003792 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003793 // This behavior is specified in JSEP. The gist is that:
3794 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3795 // sendrecv.
3796 // 2. If the MSID is included, then it must be included in any subsequent
3797 // offer/answer exactly the same until the RtpTransceiver is stopped.
3798 if (!transceiver->stopped() &&
3799 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3800 transceiver->internal()->has_ever_been_used_to_send())) {
3801 cricket::SenderOptions sender_options;
3802 sender_options.track_id = transceiver->sender()->id();
3803 sender_options.stream_ids = transceiver->sender()->stream_ids();
3804 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3805 // set in the RTP parameters when the transceiver was added.
3806 sender_options.num_sim_layers = 1;
3807 media_description_options.sender_options.push_back(sender_options);
3808 }
Steve Antondcc3c022017-12-22 16:02:54 -08003809 return media_description_options;
3810}
3811
3812void PeerConnection::GetOptionsForUnifiedPlanOffer(
3813 const RTCOfferAnswerOptions& offer_answer_options,
3814 cricket::MediaSessionOptions* session_options) {
3815 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3816 // Offers) and 5.2.2 (Subsequent Offers).
3817 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3818 const ContentInfos& local_contents =
3819 (local_description() ? local_description()->description()->contents()
3820 : ContentInfos());
3821 const ContentInfos& remote_contents =
3822 (remote_description() ? remote_description()->description()->contents()
3823 : ContentInfos());
3824 // The mline indices that can be recycled. New transceivers should reuse these
3825 // slots first.
3826 std::queue<size_t> recycleable_mline_indices;
3827 // Track the MIDs used in previous offer/answer exchanges and the current
3828 // offer so that new, unique MIDs are generated.
3829 std::set<std::string> used_mids = seen_mids_;
3830 // First, go through each media section that exists in either the local or
3831 // remote description and generate a media section in this offer for the
3832 // associated transceiver. If a media section can be recycled, generate a
3833 // default, rejected media section here that can be later overwritten.
3834 for (size_t i = 0;
3835 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3836 // Either |local_content| or |remote_content| is non-null.
3837 const ContentInfo* local_content =
3838 (i < local_contents.size() ? &local_contents[i] : nullptr);
3839 const ContentInfo* remote_content =
3840 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3841 bool had_been_rejected = (local_content && local_content->rejected) ||
3842 (remote_content && remote_content->rejected);
3843 const std::string& mid =
3844 (local_content ? local_content->name : remote_content->name);
3845 cricket::MediaType media_type =
3846 (local_content ? local_content->media_description()->type()
3847 : remote_content->media_description()->type());
3848 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3849 media_type == cricket::MEDIA_TYPE_VIDEO) {
3850 auto transceiver = GetAssociatedTransceiver(mid);
3851 RTC_CHECK(transceiver);
3852 // A media section is considered eligible for recycling if it is marked as
3853 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003854 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003855 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003856 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3857 RtpTransceiverDirection::kInactive,
3858 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003859 recycleable_mline_indices.push(i);
3860 } else {
3861 session_options->media_description_options.push_back(
3862 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3863 // CreateOffer shouldn't really cause any state changes in
3864 // PeerConnection, but we need a way to match new transceivers to new
3865 // media sections in SetLocalDescription and JSEP specifies this is done
3866 // by recording the index of the media section generated for the
3867 // transceiver in the offer.
3868 transceiver->internal()->set_mline_index(i);
3869 }
3870 } else {
3871 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003872 RTC_CHECK(GetDataMid());
3873 if (had_been_rejected || mid != *GetDataMid()) {
3874 session_options->media_description_options.push_back(
3875 GetMediaDescriptionOptionsForRejectedData(mid));
3876 } else {
3877 session_options->media_description_options.push_back(
3878 GetMediaDescriptionOptionsForActiveData(mid));
3879 }
Steve Antondcc3c022017-12-22 16:02:54 -08003880 }
3881 }
3882 // Next, look for transceivers that are newly added (that is, are not stopped
3883 // and not associated). Reuse media sections marked as recyclable first,
3884 // otherwise append to the end of the offer. New media sections should be
3885 // added in the order they were added to the PeerConnection.
3886 for (auto transceiver : transceivers_) {
3887 if (transceiver->mid() || transceiver->stopped()) {
3888 continue;
3889 }
3890 size_t mline_index;
3891 if (!recycleable_mline_indices.empty()) {
3892 mline_index = recycleable_mline_indices.front();
3893 recycleable_mline_indices.pop();
3894 session_options->media_description_options[mline_index] =
3895 GetMediaDescriptionOptionsForTransceiver(transceiver,
3896 AllocateMid(&used_mids));
3897 } else {
3898 mline_index = session_options->media_description_options.size();
3899 session_options->media_description_options.push_back(
3900 GetMediaDescriptionOptionsForTransceiver(transceiver,
3901 AllocateMid(&used_mids)));
3902 }
3903 // See comment above for why CreateOffer changes the transceiver's state.
3904 transceiver->internal()->set_mline_index(mline_index);
3905 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003906 // Lastly, add a m-section if we have local data channels and an m section
3907 // does not already exist.
3908 if (!GetDataMid() && HasDataChannels()) {
3909 session_options->media_description_options.push_back(
3910 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3911 }
Steve Antondcc3c022017-12-22 16:02:54 -08003912}
3913
3914void PeerConnection::GetOptionsForAnswer(
3915 const RTCOfferAnswerOptions& offer_answer_options,
3916 cricket::MediaSessionOptions* session_options) {
3917 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3918
3919 if (IsUnifiedPlan()) {
3920 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3921 } else {
3922 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3923 }
3924
Steve Antonfa2260d2017-12-28 16:38:23 -08003925 // Intentionally unset the data channel type for RTP data channel. Otherwise
3926 // the RTP data channels would be successfully negotiated by default and the
3927 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3928 // We want to leave RTP data channels broken, so people won't try to use them.
3929 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3930 session_options->data_channel_type = data_channel_type();
3931 }
3932
Steve Antondcc3c022017-12-22 16:02:54 -08003933 // Apply ICE renomination flag.
3934 for (auto& options : session_options->media_description_options) {
3935 options.transport_options.enable_ice_renomination =
3936 configuration_.enable_ice_renomination;
3937 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003938
3939 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003940 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003941 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003942}
3943
Steve Antondcc3c022017-12-22 16:02:54 -08003944void PeerConnection::GetOptionsForPlanBAnswer(
3945 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003946 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003947 // Figure out transceiver directional preferences.
3948 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3949 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3950
3951 // By default, generate sendrecv/recvonly m= sections. The direction is also
3952 // restricted by the direction in the offer.
3953 bool recv_audio = true;
3954 bool recv_video = true;
3955
3956 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003957 if (offer_answer_options.offer_to_receive_audio !=
3958 RTCOfferAnswerOptions::kUndefined) {
3959 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003960 }
Steve Antondcc3c022017-12-22 16:02:54 -08003961 if (offer_answer_options.offer_to_receive_video !=
3962 RTCOfferAnswerOptions::kUndefined) {
3963 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003964 }
3965
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003966 absl::optional<size_t> audio_index;
3967 absl::optional<size_t> video_index;
3968 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003969
3970 // Generate m= sections that match those in the offer.
3971 // Note that mediasession.cc will handle intersection our preferred
3972 // direction with the offered direction.
3973 GenerateMediaDescriptionOptions(
3974 remote_description(),
3975 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3976 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3977 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003978
3979 cricket::MediaDescriptionOptions* audio_media_description_options =
3980 !audio_index ? nullptr
3981 : &session_options->media_description_options[*audio_index];
3982 cricket::MediaDescriptionOptions* video_media_description_options =
3983 !video_index ? nullptr
3984 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003985
Steve Anton4171afb2017-11-20 10:20:22 -08003986 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07003987 video_media_description_options);
Steve Antondcc3c022017-12-22 16:02:54 -08003988}
zhihuangaf388472016-11-02 16:49:48 -07003989
Steve Antondcc3c022017-12-22 16:02:54 -08003990void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3991 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3992 cricket::MediaSessionOptions* session_options) {
3993 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3994 // Answers) and 5.3.2 (Subsequent Answers).
3995 RTC_DCHECK(remote_description());
3996 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3997 for (const ContentInfo& content :
3998 remote_description()->description()->contents()) {
3999 cricket::MediaType media_type = content.media_description()->type();
4000 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4001 media_type == cricket::MEDIA_TYPE_VIDEO) {
4002 auto transceiver = GetAssociatedTransceiver(content.name);
4003 RTC_CHECK(transceiver);
4004 session_options->media_description_options.push_back(
4005 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4006 } else {
4007 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004008 // Reject all data sections if data channels are disabled.
4009 // Reject a data section if it has already been rejected.
4010 // Reject all data sections except for the first one.
4011 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4012 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004013 session_options->media_description_options.push_back(
4014 GetMediaDescriptionOptionsForRejectedData(content.name));
4015 } else {
4016 session_options->media_description_options.push_back(
4017 GetMediaDescriptionOptionsForActiveData(content.name));
4018 }
Steve Antondcc3c022017-12-22 16:02:54 -08004019 }
4020 }
htaa2a49d92016-03-04 02:51:39 -08004021}
4022
zhihuang1c378ed2017-08-17 14:10:50 -07004023void PeerConnection::GenerateMediaDescriptionOptions(
4024 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004025 RtpTransceiverDirection audio_direction,
4026 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004027 absl::optional<size_t>* audio_index,
4028 absl::optional<size_t>* video_index,
4029 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004030 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004031 for (const cricket::ContentInfo& content :
4032 session_desc->description()->contents()) {
4033 if (IsAudioContent(&content)) {
4034 // If we already have an audio m= section, reject this extra one.
4035 if (*audio_index) {
4036 session_options->media_description_options.push_back(
4037 cricket::MediaDescriptionOptions(
4038 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004039 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004040 } else {
4041 session_options->media_description_options.push_back(
4042 cricket::MediaDescriptionOptions(
4043 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004044 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004045 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004046 }
4047 } else if (IsVideoContent(&content)) {
4048 // If we already have an video m= section, reject this extra one.
4049 if (*video_index) {
4050 session_options->media_description_options.push_back(
4051 cricket::MediaDescriptionOptions(
4052 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004053 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004054 } else {
4055 session_options->media_description_options.push_back(
4056 cricket::MediaDescriptionOptions(
4057 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004058 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004059 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004060 }
4061 } else {
4062 RTC_DCHECK(IsDataContent(&content));
4063 // If we already have an data m= section, reject this extra one.
4064 if (*data_index) {
4065 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004066 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004067 } else {
4068 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004069 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004070 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004071 }
4072 }
htaa2a49d92016-03-04 02:51:39 -08004073 }
deadbeefab9b2d12015-10-14 11:33:11 -07004074}
4075
Steve Antonfa2260d2017-12-28 16:38:23 -08004076cricket::MediaDescriptionOptions
4077PeerConnection::GetMediaDescriptionOptionsForActiveData(
4078 const std::string& mid) const {
4079 // Direction for data sections is meaningless, but legacy endpoints might
4080 // expect sendrecv.
4081 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4082 RtpTransceiverDirection::kSendRecv,
4083 /*stopped=*/false);
4084 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4085 return options;
4086}
4087
4088cricket::MediaDescriptionOptions
4089PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4090 const std::string& mid) const {
4091 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4092 RtpTransceiverDirection::kInactive,
4093 /*stopped=*/true);
4094 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4095 return options;
4096}
4097
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004098absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004099 switch (data_channel_type_) {
4100 case cricket::DCT_RTP:
4101 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004102 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004103 }
4104 return rtp_data_channel_->content_name();
4105 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004106 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004107 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004108 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004109 }
4110}
4111
Steve Anton4171afb2017-11-20 10:20:22 -08004112void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4113 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4114 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004115 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004116}
4117
Steve Anton4171afb2017-11-20 10:20:22 -08004118void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004119 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004120 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004121 cricket::MediaType media_type,
4122 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004123 RTC_DCHECK(!IsUnifiedPlan());
4124
Steve Anton4171afb2017-11-20 10:20:22 -08004125 std::vector<RtpSenderInfo>* current_senders =
4126 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004127
Steve Anton4171afb2017-11-20 10:20:22 -08004128 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004129 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004130 for (auto sender_it = current_senders->begin();
4131 sender_it != current_senders->end();
4132 /* incremented manually */) {
4133 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004134 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004135 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004136 std::string params_stream_id;
4137 if (params) {
4138 params_stream_id =
4139 (!params->first_stream_id().empty() ? params->first_stream_id()
4140 : kDefaultStreamId);
4141 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004142 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004143 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004144 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004145 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004146 sender_exists) {
4147 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004148 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004149 OnRemoteSenderRemoved(info, media_type);
4150 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004151 }
4152 }
4153
Steve Anton4171afb2017-11-20 10:20:22 -08004154 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004155 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004156 if (!params.has_ssrcs()) {
4157 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4158 // sender, this means it is coming from a Unified Plan endpoint,so we just
4159 // create a default.
4160 default_sender_needed = true;
4161 break;
4162 }
4163
Seth Hampson845e8782018-03-02 11:34:10 -08004164 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004165 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004166 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4167 // not supported in Plan B, we just take the first here and create the
4168 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004169 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004170 (!params.first_stream_id().empty() ? params.first_stream_id()
4171 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004172 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004173 uint32_t ssrc = params.first_ssrc();
4174
4175 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004176 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004177 if (!stream) {
4178 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004179 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004180 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004181 remote_streams_->AddStream(stream);
4182 new_streams->AddStream(stream);
4183 }
4184
Steve Anton4171afb2017-11-20 10:20:22 -08004185 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004186 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004187 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004188 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004189 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004190 }
4191 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004192
Steve Anton4171afb2017-11-20 10:20:22 -08004193 // Add default sender if necessary.
4194 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004195 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004196 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004197 if (!default_stream) {
4198 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004199 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004200 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004201 remote_streams_->AddStream(default_stream);
4202 new_streams->AddStream(default_stream);
4203 }
Steve Anton4171afb2017-11-20 10:20:22 -08004204 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4205 ? kDefaultAudioSenderId
4206 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004207 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004208 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004209 if (!default_sender_info) {
4210 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004211 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004212 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004213 }
4214 }
deadbeefab9b2d12015-10-14 11:33:11 -07004215}
4216
Steve Anton4171afb2017-11-20 10:20:22 -08004217void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4218 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004219 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4220 << " receiver for track_id=" << sender_info.sender_id
4221 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004222
Steve Anton3d954a62018-04-02 11:27:23 -07004223 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004224 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004225 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004226 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004227 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004228 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004229 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004230 }
4231}
4232
Steve Anton4171afb2017-11-20 10:20:22 -08004233void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4234 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004235 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4236 << " receiver for track_id=" << sender_info.sender_id
4237 << " and stream_id=" << sender_info.stream_id;
4238
Seth Hampson845e8782018-03-02 11:34:10 -08004239 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004240
Henrik Boström933d8b02017-10-10 10:05:16 -07004241 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004242 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004243 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4244 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004245 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004246 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004247 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004248 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004249 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004250 }
4251 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004252 // Stopping or destroying a VideoRtpReceiver will end the
4253 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004254 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004255 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004256 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004257 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004258 // There's no guarantee the track is still available, e.g. the track may
4259 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004260 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004261 }
4262 } else {
nisseede5da42017-01-12 05:15:36 -08004263 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004264 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004265 if (receiver) {
4266 observer_->OnRemoveTrack(receiver);
4267 }
deadbeefab9b2d12015-10-14 11:33:11 -07004268}
4269
4270void PeerConnection::UpdateEndedRemoteMediaStreams() {
4271 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4272 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4273 MediaStreamInterface* stream = remote_streams_->at(i);
4274 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4275 streams_to_remove.push_back(stream);
4276 }
4277 }
4278
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004279 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004280 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004281 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004282 }
4283}
4284
Steve Anton4171afb2017-11-20 10:20:22 -08004285void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004286 const std::vector<cricket::StreamParams>& streams,
4287 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004288 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004289
Seth Hampson845e8782018-03-02 11:34:10 -08004290 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004291 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004292 for (auto sender_it = current_senders->begin();
4293 sender_it != current_senders->end();
4294 /* incremented manually */) {
4295 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004296 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004297 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4298 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004299 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004300 OnLocalSenderRemoved(info, media_type);
4301 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004302 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004303 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004304 }
4305 }
4306
Steve Anton4171afb2017-11-20 10:20:22 -08004307 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004308 for (const cricket::StreamParams& params : streams) {
4309 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004310 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004311 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004312 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004313 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004314 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004315 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004316 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004317 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004318 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004319 }
4320 }
4321}
4322
Steve Anton4171afb2017-11-20 10:20:22 -08004323void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4324 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004325 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004326 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004327 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004328 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4329 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004330 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004331 return;
4332 }
4333
deadbeeffac06552015-11-25 11:26:01 -08004334 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004335 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004336 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004337 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004338 }
deadbeeffac06552015-11-25 11:26:01 -08004339
Seth Hampson5b4f0752018-04-02 16:31:36 -07004340 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004341 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004342}
4343
Steve Anton4171afb2017-11-20 10:20:22 -08004344void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4345 cricket::MediaType media_type) {
4346 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004347 if (!sender) {
4348 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004349 // SessionDescriptions has been renegotiated.
4350 return;
4351 }
deadbeeffac06552015-11-25 11:26:01 -08004352
4353 // A sender has been removed from the SessionDescription but it's still
4354 // associated with the PeerConnection. This only occurs if the SDP doesn't
4355 // match with the calls to CreateSender, AddStream and RemoveStream.
4356 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004357 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004358 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004359 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004360 }
deadbeeffac06552015-11-25 11:26:01 -08004361
Steve Anton4171afb2017-11-20 10:20:22 -08004362 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004363}
4364
4365void PeerConnection::UpdateLocalRtpDataChannels(
4366 const cricket::StreamParamsVec& streams) {
4367 std::vector<std::string> existing_channels;
4368
4369 // Find new and active data channels.
4370 for (const cricket::StreamParams& params : streams) {
4371 // |it->sync_label| is actually the data channel label. The reason is that
4372 // we use the same naming of data channels as we do for
4373 // MediaStreams and Tracks.
4374 // For MediaStreams, the sync_label is the MediaStream label and the
4375 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004376 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004377 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004378 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004379 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004380 continue;
4381 }
4382 // Set the SSRC the data channel should use for sending.
4383 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4384 existing_channels.push_back(data_channel_it->first);
4385 }
4386
4387 UpdateClosingRtpDataChannels(existing_channels, true);
4388}
4389
4390void PeerConnection::UpdateRemoteRtpDataChannels(
4391 const cricket::StreamParamsVec& streams) {
4392 std::vector<std::string> existing_channels;
4393
4394 // Find new and active data channels.
4395 for (const cricket::StreamParams& params : streams) {
4396 // The data channel label is either the mslabel or the SSRC if the mslabel
4397 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004398 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004399 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004400 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004401 auto data_channel_it = rtp_data_channels_.find(label);
4402 if (data_channel_it == rtp_data_channels_.end()) {
4403 // This is a new data channel.
4404 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4405 } else {
4406 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4407 }
4408 existing_channels.push_back(label);
4409 }
4410
4411 UpdateClosingRtpDataChannels(existing_channels, false);
4412}
4413
4414void PeerConnection::UpdateClosingRtpDataChannels(
4415 const std::vector<std::string>& active_channels,
4416 bool is_local_update) {
4417 auto it = rtp_data_channels_.begin();
4418 while (it != rtp_data_channels_.end()) {
4419 DataChannel* data_channel = it->second;
4420 if (std::find(active_channels.begin(), active_channels.end(),
4421 data_channel->label()) != active_channels.end()) {
4422 ++it;
4423 continue;
4424 }
4425
4426 if (is_local_update) {
4427 data_channel->SetSendSsrc(0);
4428 } else {
4429 data_channel->RemotePeerRequestClose();
4430 }
4431
4432 if (data_channel->state() == DataChannel::kClosed) {
4433 rtp_data_channels_.erase(it);
4434 it = rtp_data_channels_.begin();
4435 } else {
4436 ++it;
4437 }
4438 }
4439}
4440
4441void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4442 uint32_t remote_ssrc) {
4443 rtc::scoped_refptr<DataChannel> channel(
4444 InternalCreateDataChannel(label, nullptr));
4445 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004446 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004447 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004448 return;
4449 }
4450 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004451 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4452 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004453 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004454}
4455
4456rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4457 const std::string& label,
4458 const InternalDataChannelInit* config) {
4459 if (IsClosed()) {
4460 return nullptr;
4461 }
Steve Anton75737c02017-11-06 10:37:17 -08004462 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004463 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004464 << "InternalCreateDataChannel: Data is not supported in this call.";
4465 return nullptr;
4466 }
4467 InternalDataChannelInit new_config =
4468 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004469 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004470 if (new_config.id < 0) {
4471 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004472 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004473 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004474 RTC_LOG(LS_ERROR)
4475 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004476 return nullptr;
4477 }
4478 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004479 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004480 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004481 return nullptr;
4482 }
4483 }
4484
Steve Anton75737c02017-11-06 10:37:17 -08004485 rtc::scoped_refptr<DataChannel> channel(
4486 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004487 if (!channel) {
4488 sid_allocator_.ReleaseSid(new_config.id);
4489 return nullptr;
4490 }
4491
4492 if (channel->data_channel_type() == cricket::DCT_RTP) {
4493 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004494 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4495 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004496 return nullptr;
4497 }
4498 rtp_data_channels_[channel->label()] = channel;
4499 } else {
4500 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4501 sctp_data_channels_.push_back(channel);
4502 channel->SignalClosed.connect(this,
4503 &PeerConnection::OnSctpDataChannelClosed);
4504 }
4505
Steve Anton2d8609c2018-01-23 16:38:46 -08004506 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004507 return channel;
4508}
4509
4510bool PeerConnection::HasDataChannels() const {
4511 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4512}
4513
4514void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4515 for (const auto& channel : sctp_data_channels_) {
4516 if (channel->id() < 0) {
4517 int sid;
4518 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004519 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004520 continue;
4521 }
4522 channel->SetSctpSid(sid);
4523 }
4524 }
4525}
4526
4527void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004528 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004529 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4530 ++it) {
4531 if (it->get() == channel) {
4532 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004533 // After the closing procedure is done, it's safe to use this ID for
4534 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004535 sid_allocator_.ReleaseSid(channel->id());
4536 }
deadbeefbd292462015-12-14 18:15:29 -08004537 // Since this method is triggered by a signal from the DataChannel,
4538 // we can't free it directly here; we need to free it asynchronously.
4539 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004540 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07004541 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4542 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004543 return;
4544 }
4545 }
4546}
4547
deadbeefab9b2d12015-10-14 11:33:11 -07004548void PeerConnection::OnDataChannelDestroyed() {
4549 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4550 // DataChannel may callback to us and try to modify the list.
4551 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4552 temp_rtp_dcs.swap(rtp_data_channels_);
4553 for (const auto& kv : temp_rtp_dcs) {
4554 kv.second->OnTransportChannelDestroyed();
4555 }
4556
4557 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4558 temp_sctp_dcs.swap(sctp_data_channels_);
4559 for (const auto& channel : temp_sctp_dcs) {
4560 channel->OnTransportChannelDestroyed();
4561 }
4562}
4563
4564void PeerConnection::OnDataChannelOpenMessage(
4565 const std::string& label,
4566 const InternalDataChannelInit& config) {
4567 rtc::scoped_refptr<DataChannel> channel(
4568 InternalCreateDataChannel(label, &config));
4569 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004570 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004571 return;
4572 }
4573
deadbeefa601f5c2016-06-06 14:27:39 -07004574 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4575 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004576 observer_->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004577 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004578}
4579
Steve Anton4171afb2017-11-20 10:20:22 -08004580rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4581PeerConnection::GetAudioTransceiver() const {
4582 // This method only works with Plan B SDP, where there is a single
4583 // audio/video transceiver.
4584 RTC_DCHECK(!IsUnifiedPlan());
4585 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004586 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004587 return transceiver;
4588 }
4589 }
4590 RTC_NOTREACHED();
4591 return nullptr;
4592}
4593
4594rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4595PeerConnection::GetVideoTransceiver() const {
4596 // This method only works with Plan B SDP, where there is a single
4597 // audio/video transceiver.
4598 RTC_DCHECK(!IsUnifiedPlan());
4599 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004600 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004601 return transceiver;
4602 }
4603 }
4604 RTC_NOTREACHED();
4605 return nullptr;
4606}
4607
4608// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4609// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004610bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004611 switch (type) {
4612 case cricket::MEDIA_TYPE_AUDIO:
4613 return !GetAudioTransceiver()->internal()->senders().empty();
4614 case cricket::MEDIA_TYPE_VIDEO:
4615 return !GetVideoTransceiver()->internal()->senders().empty();
4616 case cricket::MEDIA_TYPE_DATA:
4617 return false;
4618 }
4619 RTC_NOTREACHED();
4620 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004621}
4622
Steve Anton4171afb2017-11-20 10:20:22 -08004623rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4624PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4625 for (auto transceiver : transceivers_) {
4626 for (auto sender : transceiver->internal()->senders()) {
4627 if (sender->track() == track) {
4628 return sender;
4629 }
4630 }
4631 }
4632 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004633}
4634
Steve Anton4171afb2017-11-20 10:20:22 -08004635rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4636PeerConnection::FindSenderById(const std::string& sender_id) const {
4637 for (auto transceiver : transceivers_) {
4638 for (auto sender : transceiver->internal()->senders()) {
4639 if (sender->id() == sender_id) {
4640 return sender;
4641 }
4642 }
4643 }
4644 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004645}
4646
Steve Anton4171afb2017-11-20 10:20:22 -08004647rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4648PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4649 for (auto transceiver : transceivers_) {
4650 for (auto receiver : transceiver->internal()->receivers()) {
4651 if (receiver->id() == receiver_id) {
4652 return receiver;
4653 }
4654 }
4655 }
4656 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004657}
4658
Steve Anton4171afb2017-11-20 10:20:22 -08004659std::vector<PeerConnection::RtpSenderInfo>*
4660PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4661 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4662 media_type == cricket::MEDIA_TYPE_VIDEO);
4663 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4664 ? &remote_audio_sender_infos_
4665 : &remote_video_sender_infos_;
4666}
4667
4668std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004669 cricket::MediaType media_type) {
4670 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4671 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004672 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4673 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004674}
4675
Steve Anton4171afb2017-11-20 10:20:22 -08004676const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4677 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004678 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004679 const std::string sender_id) const {
4680 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004681 if (sender_info.stream_id == stream_id &&
4682 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004683 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004684 }
4685 }
4686 return nullptr;
4687}
4688
4689DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4690 for (const auto& channel : sctp_data_channels_) {
4691 if (channel->id() == sid) {
4692 return channel;
4693 }
4694 }
4695 return nullptr;
4696}
4697
deadbeef91dd5672016-05-18 16:55:30 -07004698bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004699 const cricket::ServerAddresses& stun_servers,
4700 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004701 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004702 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004703 // To handle both internal and externally created port allocator, we will
4704 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004705 port_allocator_flags_ = port_allocator_->flags();
4706 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4707 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4708 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004709 // If the disable-IPv6 flag was specified, we'll not override it
4710 // by experiment.
4711 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004712 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004713 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4714 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004715 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004716 }
4717
zhihuangb09b3f92017-03-07 14:40:51 -08004718 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004719 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004720 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004721 }
4722
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004723 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004724 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004725 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004726 }
4727
honghaiz60347052016-05-31 18:29:12 -07004728 if (configuration.candidate_network_policy ==
4729 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004730 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004731 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004732 }
4733
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004734 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004735 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004736 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4737 }
4738
Qingsi Wanga2d60672018-04-11 16:57:45 -07004739 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004740 // No step delay is used while allocating ports.
4741 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4742 port_allocator_->set_candidate_filter(
4743 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004744 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004745
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004746 auto turn_servers_copy = turn_servers;
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004747 if (tls_cert_verifier_ != nullptr) {
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004748 for (auto& turn_server : turn_servers_copy) {
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004749 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4750 }
4751 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004752 // Call this last since it may create pooled allocator sessions using the
4753 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004754 port_allocator_->SetConfiguration(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004755 stun_servers, turn_servers_copy, configuration.ice_candidate_pool_size,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004756 configuration.prune_turn_ports, configuration.turn_customizer,
4757 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004758 return true;
4759}
4760
deadbeef91dd5672016-05-18 16:55:30 -07004761bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004762 const cricket::ServerAddresses& stun_servers,
4763 const std::vector<cricket::RelayServerConfig>& turn_servers,
4764 IceTransportsType type,
4765 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004766 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004767 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004768 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004769 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004770 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004771 // According to JSEP, after setLocalDescription, changing the candidate pool
4772 // size is not allowed, and changing the set of ICE servers will not result
4773 // in new candidates being gathered.
4774 if (local_description()) {
4775 port_allocator_->FreezeCandidatePool();
4776 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004777 // Call this last since it may create pooled allocator sessions using the
4778 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004779 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02004780 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004781 turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004782}
4783
Steve Antonba818672017-11-06 10:21:57 -08004784cricket::ChannelManager* PeerConnection::channel_manager() const {
4785 return factory_->channel_manager();
4786}
4787
4788MetricsObserverInterface* PeerConnection::metrics_observer() const {
4789 return uma_observer_;
4790}
4791
Elad Alon99c3fe52017-10-13 16:29:40 +02004792bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004793 std::unique_ptr<RtcEventLogOutput> output,
4794 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004795 if (!event_log_) {
4796 return false;
4797 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004798 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004799}
4800
4801void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004802 if (event_log_) {
4803 event_log_->StopLogging();
4804 }
ivoc14d5dbe2016-07-04 07:06:55 -07004805}
nisseeaabdf62017-05-05 02:23:02 -07004806
Steve Anton75737c02017-11-06 10:37:17 -08004807cricket::BaseChannel* PeerConnection::GetChannel(
4808 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004809 for (auto transceiver : transceivers_) {
4810 cricket::BaseChannel* channel = transceiver->internal()->channel();
4811 if (channel && channel->content_name() == content_name) {
4812 return channel;
4813 }
Steve Anton75737c02017-11-06 10:37:17 -08004814 }
4815 if (rtp_data_channel() &&
4816 rtp_data_channel()->content_name() == content_name) {
4817 return rtp_data_channel();
4818 }
4819 return nullptr;
4820}
4821
4822bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4823 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004824 RTC_LOG(LS_INFO)
4825 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004826 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004827 return false;
4828 }
4829 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004830 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004831 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004832 return false;
4833 }
4834
Zhi Huange830e682018-03-30 10:48:35 -07004835 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4836 if (dtls_role) {
4837 *role = *dtls_role;
4838 return true;
4839 }
4840 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004841}
4842
4843bool PeerConnection::GetSslRole(const std::string& content_name,
4844 rtc::SSLRole* role) {
4845 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004846 RTC_LOG(LS_INFO)
4847 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004848 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004849 return false;
4850 }
4851
Zhi Huange830e682018-03-30 10:48:35 -07004852 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4853 if (dtls_role) {
4854 *role = *dtls_role;
4855 return true;
4856 }
4857 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004858}
4859
Steve Antonf8470812017-12-04 10:46:21 -08004860void PeerConnection::SetSessionError(SessionError error,
4861 const std::string& error_desc) {
4862 RTC_DCHECK_RUN_ON(signaling_thread());
4863 if (error != session_error_) {
4864 session_error_ = error;
4865 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004866 }
4867}
4868
Zhi Huange830e682018-03-30 10:48:35 -07004869RTCError PeerConnection::UpdateSessionState(
4870 SdpType type,
4871 cricket::ContentSource source,
4872 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004873 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004874
4875 // If there's already a pending error then no state transition should happen.
4876 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004877 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004878
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004879 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004880 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004881 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004882 }
4883
4884 // Update the signaling state according to the specified state machine (see
4885 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004886 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004887 ChangeSignalingState(source == cricket::CS_LOCAL
4888 ? PeerConnectionInterface::kHaveLocalOffer
4889 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004890 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004891 ChangeSignalingState(source == cricket::CS_LOCAL
4892 ? PeerConnectionInterface::kHaveLocalPrAnswer
4893 : PeerConnectionInterface::kHaveRemotePrAnswer);
4894 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004895 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004896 ChangeSignalingState(PeerConnectionInterface::kStable);
4897 }
4898
4899 // Update internal objects according to the session description's media
4900 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004901 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004902 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004903 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004904 }
4905
Steve Anton8a006912017-12-04 15:25:56 -08004906 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004907}
4908
Steve Anton8a006912017-12-04 15:25:56 -08004909RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004910 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004911 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004912 const SessionDescriptionInterface* sdesc =
4913 (source == cricket::CS_LOCAL ? local_description()
4914 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004915 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004916
4917 // Push down the new SDP media section for each audio/video transceiver.
4918 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004919 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004920 FindMediaSectionForTransceiver(transceiver, sdesc);
4921 cricket::BaseChannel* channel = transceiver->internal()->channel();
4922 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004923 continue;
4924 }
4925 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004926 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004927 if (!content_desc) {
4928 continue;
4929 }
4930 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004931 bool success = (source == cricket::CS_LOCAL)
4932 ? channel->SetLocalContent(content_desc, type, &error)
4933 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004934 if (!success) {
4935 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4936 }
4937 }
4938
4939 // If using the RtpDataChannel, push down the new SDP section for it too.
4940 if (rtp_data_channel_) {
4941 const ContentInfo* data_content =
4942 cricket::GetFirstDataContent(sdesc->description());
4943 if (data_content && !data_content->rejected) {
4944 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004945 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004946 if (data_desc) {
4947 std::string error;
4948 bool success =
4949 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004950 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004951 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004952 if (!success) {
4953 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4954 std::move(error));
4955 }
Steve Anton75737c02017-11-06 10:37:17 -08004956 }
4957 }
4958 }
Steve Antoned10bd92017-12-05 10:52:59 -08004959
Steve Anton75737c02017-11-06 10:37:17 -08004960 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4961 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4962 if (sctp_transport_ && local_description() && remote_description() &&
4963 cricket::GetFirstDataContent(local_description()->description()) &&
4964 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004965 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004966 RTC_FROM_HERE,
4967 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004968 if (!success) {
4969 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4970 "Failed to push down SCTP parameters.");
4971 }
Steve Anton75737c02017-11-06 10:37:17 -08004972 }
Steve Antoned10bd92017-12-05 10:52:59 -08004973
Steve Anton8a006912017-12-04 15:25:56 -08004974 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004975}
4976
4977bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4978 RTC_DCHECK(network_thread()->IsCurrent());
4979 RTC_DCHECK(local_description());
4980 RTC_DCHECK(remote_description());
4981 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4982 // When we support "max-message-size", that would also be pushed down here.
4983 return sctp_transport_->Start(
4984 GetSctpPort(local_description()->description()),
4985 GetSctpPort(remote_description()->description()));
4986}
4987
Steve Anton8a006912017-12-04 15:25:56 -08004988RTCError PeerConnection::PushdownTransportDescription(
4989 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004990 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004991 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004992
Zhi Huange830e682018-03-30 10:48:35 -07004993 if (source == cricket::CS_LOCAL) {
4994 const SessionDescriptionInterface* sdesc = local_description();
4995 RTC_DCHECK(sdesc);
4996 return transport_controller_->SetLocalDescription(type,
4997 sdesc->description());
4998 } else {
4999 const SessionDescriptionInterface* sdesc = remote_description();
5000 RTC_DCHECK(sdesc);
5001 return transport_controller_->SetRemoteDescription(type,
5002 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005003 }
Steve Anton75737c02017-11-06 10:37:17 -08005004}
5005
5006bool PeerConnection::GetTransportDescription(
5007 const SessionDescription* description,
5008 const std::string& content_name,
5009 cricket::TransportDescription* tdesc) {
5010 if (!description || !tdesc) {
5011 return false;
5012 }
5013 const TransportInfo* transport_info =
5014 description->GetTransportInfoByName(content_name);
5015 if (!transport_info) {
5016 return false;
5017 }
5018 *tdesc = transport_info->description;
5019 return true;
5020}
5021
Steve Anton75737c02017-11-06 10:37:17 -08005022cricket::IceConfig PeerConnection::ParseIceConfig(
5023 const PeerConnectionInterface::RTCConfiguration& config) const {
5024 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005025 switch (config.continual_gathering_policy) {
5026 case PeerConnectionInterface::GATHER_ONCE:
5027 gathering_policy = cricket::GATHER_ONCE;
5028 break;
5029 case PeerConnectionInterface::GATHER_CONTINUALLY:
5030 gathering_policy = cricket::GATHER_CONTINUALLY;
5031 break;
5032 default:
5033 RTC_NOTREACHED();
5034 gathering_policy = cricket::GATHER_ONCE;
5035 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005036
Steve Anton75737c02017-11-06 10:37:17 -08005037 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005038 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5039 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005040 ice_config.prioritize_most_likely_candidate_pairs =
5041 config.prioritize_most_likely_ice_candidate_pairs;
5042 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005043 RTCConfigurationToIceConfigOptionalInt(
5044 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005045 ice_config.continual_gathering_policy = gathering_policy;
5046 ice_config.presume_writable_when_fully_relayed =
5047 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005048 ice_config.ice_check_interval_strong_connectivity =
5049 config.ice_check_interval_strong_connectivity;
5050 ice_config.ice_check_interval_weak_connectivity =
5051 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005052 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005053 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005054 ice_config.regather_all_networks_interval_range =
5055 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005056 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005057 return ice_config;
5058}
5059
Steve Anton75737c02017-11-06 10:37:17 -08005060bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5061 std::string* track_id) {
5062 if (!local_description()) {
5063 return false;
5064 }
5065 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5066 track_id);
5067}
5068
5069bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5070 std::string* track_id) {
5071 if (!remote_description()) {
5072 return false;
5073 }
5074 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5075 track_id);
5076}
5077
5078bool PeerConnection::SendData(const cricket::SendDataParams& params,
5079 const rtc::CopyOnWriteBuffer& payload,
5080 cricket::SendDataResult* result) {
5081 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005082 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005083 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005084 return false;
5085 }
5086 return rtp_data_channel_
5087 ? rtp_data_channel_->SendData(params, payload, result)
5088 : network_thread()->Invoke<bool>(
5089 RTC_FROM_HERE,
5090 Bind(&cricket::SctpTransportInternal::SendData,
5091 sctp_transport_.get(), params, payload, result));
5092}
5093
5094bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5095 if (!rtp_data_channel_ && !sctp_transport_) {
5096 // Don't log an error here, because DataChannels are expected to call
5097 // ConnectDataChannel in this state. It's the only way to initially tell
5098 // whether or not the underlying transport is ready.
5099 return false;
5100 }
5101 if (rtp_data_channel_) {
5102 rtp_data_channel_->SignalReadyToSendData.connect(
5103 webrtc_data_channel, &DataChannel::OnChannelReady);
5104 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5105 &DataChannel::OnDataReceived);
5106 } else {
5107 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5108 &DataChannel::OnChannelReady);
5109 SignalSctpDataReceived.connect(webrtc_data_channel,
5110 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005111 SignalSctpClosingProcedureStartedRemotely.connect(
5112 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5113 SignalSctpClosingProcedureComplete.connect(
5114 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005115 }
5116 return true;
5117}
5118
5119void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5120 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005121 RTC_LOG(LS_ERROR)
5122 << "DisconnectDataChannel called when rtp_data_channel_ and "
5123 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005124 return;
5125 }
5126 if (rtp_data_channel_) {
5127 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5128 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5129 } else {
5130 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5131 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005132 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5133 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005134 }
5135}
5136
5137void PeerConnection::AddSctpDataStream(int sid) {
5138 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005139 RTC_LOG(LS_ERROR)
5140 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005141 return;
5142 }
5143 network_thread()->Invoke<void>(
5144 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5145 sctp_transport_.get(), sid));
5146}
5147
5148void PeerConnection::RemoveSctpDataStream(int sid) {
5149 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005150 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005151 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005152 return;
5153 }
5154 network_thread()->Invoke<void>(
5155 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5156 sctp_transport_.get(), sid));
5157}
5158
5159bool PeerConnection::ReadyToSendData() const {
5160 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5161 sctp_ready_to_send_data_;
5162}
5163
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005164absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005165 if (sctp_mid_ && transport_controller_) {
5166 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5167 if (dtls_transport) {
5168 return dtls_transport->transport_name();
5169 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005170 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005171 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005172 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005173}
5174
Qingsi Wang72a43a12018-02-20 16:03:18 -08005175cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5176 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005177 network_thread()->Invoke<void>(
5178 RTC_FROM_HERE,
5179 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5180 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005181 return candidate_states_list;
5182}
5183
Steve Anton5dfde182018-02-06 10:34:40 -08005184std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5185 const {
5186 std::map<std::string, std::string> transport_names_by_mid;
5187 for (auto transceiver : transceivers_) {
5188 cricket::BaseChannel* channel = transceiver->internal()->channel();
5189 if (channel) {
5190 transport_names_by_mid[channel->content_name()] =
5191 channel->transport_name();
5192 }
Steve Anton75737c02017-11-06 10:37:17 -08005193 }
Steve Anton5dfde182018-02-06 10:34:40 -08005194 if (rtp_data_channel_) {
5195 transport_names_by_mid[rtp_data_channel_->content_name()] =
5196 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005197 }
5198 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005199 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005200 RTC_DCHECK(transport_name);
5201 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005202 }
Steve Anton5dfde182018-02-06 10:34:40 -08005203 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005204}
5205
Steve Anton5dfde182018-02-06 10:34:40 -08005206std::map<std::string, cricket::TransportStats>
5207PeerConnection::GetTransportStatsByNames(
5208 const std::set<std::string>& transport_names) {
5209 if (!network_thread()->IsCurrent()) {
5210 return network_thread()
5211 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5212 RTC_FROM_HERE,
5213 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005214 }
Steve Anton5dfde182018-02-06 10:34:40 -08005215 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5216 for (const std::string& transport_name : transport_names) {
5217 cricket::TransportStats transport_stats;
5218 bool success =
5219 transport_controller_->GetStats(transport_name, &transport_stats);
5220 if (success) {
5221 transport_stats_by_name[transport_name] = std::move(transport_stats);
5222 } else {
5223 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5224 << transport_name;
5225 }
5226 }
5227 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005228}
5229
5230bool PeerConnection::GetLocalCertificate(
5231 const std::string& transport_name,
5232 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005233 if (!certificate) {
5234 return false;
5235 }
5236 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5237 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005238}
5239
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005240std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005241 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005242 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005243}
5244
5245cricket::DataChannelType PeerConnection::data_channel_type() const {
5246 return data_channel_type_;
5247}
5248
5249bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5250 return pending_ice_restarts_.find(content_name) !=
5251 pending_ice_restarts_.end();
5252}
5253
Steve Anton75737c02017-11-06 10:37:17 -08005254bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5255 return transport_controller_->NeedsIceRestart(content_name);
5256}
5257
5258void PeerConnection::OnCertificateReady(
5259 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5260 transport_controller_->SetLocalCertificate(certificate);
5261}
5262
5263void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005264 SetSessionError(SessionError::kTransport,
5265 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005266}
5267
5268void PeerConnection::OnTransportControllerConnectionState(
5269 cricket::IceConnectionState state) {
5270 switch (state) {
5271 case cricket::kIceConnectionConnecting:
5272 // If the current state is Connected or Completed, then there were
5273 // writable channels but now there are not, so the next state must
5274 // be Disconnected.
5275 // kIceConnectionConnecting is currently used as the default,
5276 // un-connected state by the TransportController, so its only use is
5277 // detecting disconnections.
5278 if (ice_connection_state_ ==
5279 PeerConnectionInterface::kIceConnectionConnected ||
5280 ice_connection_state_ ==
5281 PeerConnectionInterface::kIceConnectionCompleted) {
5282 SetIceConnectionState(
5283 PeerConnectionInterface::kIceConnectionDisconnected);
5284 }
5285 break;
5286 case cricket::kIceConnectionFailed:
5287 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5288 break;
5289 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005290 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005291 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005292 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005293 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005294 break;
5295 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005296 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005297 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005298 if (ice_connection_state_ !=
5299 PeerConnectionInterface::kIceConnectionConnected) {
5300 // If jumping directly from "checking" to "connected",
5301 // signal "connected" first.
5302 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5303 }
5304 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005305 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang78fef762018-07-11 18:33:52 +00005306 if (metrics_observer()) {
5307 ReportTransportStats();
5308 }
Steve Anton75737c02017-11-06 10:37:17 -08005309 break;
5310 default:
5311 RTC_NOTREACHED();
5312 }
5313}
5314
5315void PeerConnection::OnTransportControllerCandidatesGathered(
5316 const std::string& transport_name,
5317 const cricket::Candidates& candidates) {
5318 RTC_DCHECK(signaling_thread()->IsCurrent());
5319 int sdp_mline_index;
5320 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005321 RTC_LOG(LS_ERROR)
5322 << "OnTransportControllerCandidatesGathered: content name "
5323 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005324 return;
5325 }
5326
5327 for (cricket::Candidates::const_iterator citer = candidates.begin();
5328 citer != candidates.end(); ++citer) {
5329 // Use transport_name as the candidate media id.
5330 std::unique_ptr<JsepIceCandidate> candidate(
5331 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5332 if (local_description()) {
5333 mutable_local_description()->AddCandidate(candidate.get());
5334 }
5335 OnIceCandidate(std::move(candidate));
5336 }
5337}
5338
5339void PeerConnection::OnTransportControllerCandidatesRemoved(
5340 const std::vector<cricket::Candidate>& candidates) {
5341 RTC_DCHECK(signaling_thread()->IsCurrent());
5342 // Sanity check.
5343 for (const cricket::Candidate& candidate : candidates) {
5344 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005345 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005346 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005347 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005348 return;
5349 }
5350 }
5351
5352 if (local_description()) {
5353 mutable_local_description()->RemoveCandidates(candidates);
5354 }
5355 OnIceCandidatesRemoved(candidates);
5356}
5357
5358void PeerConnection::OnTransportControllerDtlsHandshakeError(
5359 rtc::SSLHandshakeError error) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005360 if (metrics_observer()) {
5361 metrics_observer()->IncrementEnumCounter(
5362 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
5363 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
5364 }
Steve Anton75737c02017-11-06 10:37:17 -08005365}
5366
Steve Antoned10bd92017-12-05 10:52:59 -08005367void PeerConnection::EnableSending() {
5368 for (auto transceiver : transceivers_) {
5369 cricket::BaseChannel* channel = transceiver->internal()->channel();
5370 if (channel && !channel->enabled()) {
5371 channel->Enable(true);
5372 }
Steve Anton75737c02017-11-06 10:37:17 -08005373 }
5374
Steve Anton4171afb2017-11-20 10:20:22 -08005375 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005376 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005377 }
Steve Anton75737c02017-11-06 10:37:17 -08005378}
5379
5380// Returns the media index for a local ice candidate given the content name.
5381bool PeerConnection::GetLocalCandidateMediaIndex(
5382 const std::string& content_name,
5383 int* sdp_mline_index) {
5384 if (!local_description() || !sdp_mline_index) {
5385 return false;
5386 }
5387
5388 bool content_found = false;
5389 const ContentInfos& contents = local_description()->description()->contents();
5390 for (size_t index = 0; index < contents.size(); ++index) {
5391 if (contents[index].name == content_name) {
5392 *sdp_mline_index = static_cast<int>(index);
5393 content_found = true;
5394 break;
5395 }
5396 }
5397 return content_found;
5398}
5399
5400bool PeerConnection::UseCandidatesInSessionDescription(
5401 const SessionDescriptionInterface* remote_desc) {
5402 if (!remote_desc) {
5403 return true;
5404 }
5405 bool ret = true;
5406
5407 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5408 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5409 for (size_t n = 0; n < candidates->count(); ++n) {
5410 const IceCandidateInterface* candidate = candidates->at(n);
5411 bool valid = false;
5412 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5413 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005414 RTC_LOG(LS_INFO)
5415 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005416 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005417 }
5418 continue;
5419 }
5420 ret = UseCandidate(candidate);
5421 if (!ret) {
5422 break;
5423 }
5424 }
5425 }
5426 return ret;
5427}
5428
5429bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5430 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5431 size_t remote_content_size =
5432 remote_description()->description()->contents().size();
5433 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005434 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005435 return false;
5436 }
5437
5438 cricket::ContentInfo content =
5439 remote_description()->description()->contents()[mediacontent_index];
5440 std::vector<cricket::Candidate> candidates;
5441 candidates.push_back(candidate->candidate());
5442 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005443 RTCError error =
5444 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005445 if (error.ok()) {
5446 // Candidates successfully submitted for checking.
5447 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5448 ice_connection_state_ ==
5449 PeerConnectionInterface::kIceConnectionDisconnected) {
5450 // If state is New, then the session has just gotten its first remote ICE
5451 // candidates, so go to Checking.
5452 // If state is Disconnected, the session is re-using old candidates or
5453 // receiving additional ones, so go to Checking.
5454 // If state is Connected, stay Connected.
5455 // TODO(bemasc): If state is Connected, and the new candidates are for a
5456 // newly added transport, then the state actually _should_ move to
5457 // checking. Add a way to distinguish that case.
5458 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5459 }
5460 // TODO(bemasc): If state is Completed, go back to Connected.
5461 } else if (error.message()) {
Zhi Huange830e682018-03-30 10:48:35 -07005462 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005463 }
5464 return true;
5465}
5466
5467void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005468 // Destroy video channel first since it may have a pointer to the
5469 // voice channel.
5470 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005471 if (!video_info || video_info->rejected) {
5472 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005473 }
5474
Steve Anton6fec8802017-12-04 10:37:29 -08005475 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5476 if (!audio_info || audio_info->rejected) {
5477 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005478 }
5479
5480 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5481 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005482 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005483 }
5484}
5485
Steve Antondcc3c022017-12-22 16:02:54 -08005486RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5487 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005488 const cricket::ContentGroup* bundle_group = nullptr;
5489 if (configuration_.bundle_policy ==
5490 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005491 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005492 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005493 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5494 "max-bundle configured but session description "
5495 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005496 }
5497 }
Steve Antondcc3c022017-12-22 16:02:54 -08005498 return std::move(bundle_group);
5499}
5500
5501RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005502 // Creating the media channels. Transports should already have been created
5503 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005504 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005505 if (voice && !voice->rejected &&
5506 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005507 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005508 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005509 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5510 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005511 }
5512 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5513 }
5514
Steve Antondcc3c022017-12-22 16:02:54 -08005515 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005516 if (video && !video->rejected &&
5517 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005518 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005519 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005520 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5521 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005522 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005523 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005524 }
5525
Steve Antondcc3c022017-12-22 16:02:54 -08005526 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005527 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5528 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005529 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005530 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5531 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005532 }
5533 }
5534
Steve Anton8a006912017-12-04 15:25:56 -08005535 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005536}
5537
Steve Anton4171afb2017-11-20 10:20:22 -08005538// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005539cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005540 const std::string& mid) {
5541 RtpTransportInternal* rtp_transport =
5542 transport_controller_->GetRtpTransport(mid);
5543 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005544 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005545 call_.get(), configuration_.media_config, rtp_transport,
5546 signaling_thread(), mid, SrtpRequired(),
5547 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005548 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005549 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005550 }
Steve Anton75737c02017-11-06 10:37:17 -08005551 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5552 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005553 voice_channel->SignalSentPacket.connect(this,
5554 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005555 voice_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005556 if (uma_observer_) {
5557 voice_channel->SetMetricsObserver(uma_observer_);
5558 }
Steve Anton4171afb2017-11-20 10:20:22 -08005559
Steve Antoneda6ccd2017-12-04 10:21:55 -08005560 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005561}
5562
Steve Anton4171afb2017-11-20 10:20:22 -08005563// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005564cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005565 const std::string& mid) {
5566 RtpTransportInternal* rtp_transport =
5567 transport_controller_->GetRtpTransport(mid);
5568 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005569 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005570 call_.get(), configuration_.media_config, rtp_transport,
5571 signaling_thread(), mid, SrtpRequired(),
5572 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005573 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005574 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005575 }
Steve Anton75737c02017-11-06 10:37:17 -08005576 video_channel->SignalDtlsSrtpSetupFailure.connect(
5577 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005578 video_channel->SignalSentPacket.connect(this,
5579 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005580 video_channel->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005581 if (uma_observer_) {
5582 video_channel->SetMetricsObserver(uma_observer_);
5583 }
Steve Anton4171afb2017-11-20 10:20:22 -08005584
Steve Antoneda6ccd2017-12-04 10:21:55 -08005585 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005586}
5587
Zhi Huange830e682018-03-30 10:48:35 -07005588bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005589 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5590 if (sctp) {
5591 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005592 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005593 << "Trying to create SCTP transport, but didn't compile with "
5594 "SCTP support (HAVE_SCTP)";
5595 return false;
5596 }
5597 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005598 RTC_FROM_HERE,
5599 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005600 return false;
5601 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005602 for (const auto& channel : sctp_data_channels_) {
5603 channel->OnTransportChannelCreated();
5604 }
Steve Anton75737c02017-11-06 10:37:17 -08005605 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005606 RtpTransportInternal* rtp_transport =
5607 transport_controller_->GetRtpTransport(mid);
5608 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005609 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005610 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5611 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005612 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005613 return false;
5614 }
Steve Anton75737c02017-11-06 10:37:17 -08005615 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5616 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5617 rtp_data_channel_->SignalSentPacket.connect(
5618 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005619 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Antondb67ba12018-03-19 17:41:42 -07005620 if (uma_observer_) {
5621 rtp_data_channel_->SetMetricsObserver(uma_observer_);
5622 }
Steve Anton75737c02017-11-06 10:37:17 -08005623 }
5624
Steve Anton75737c02017-11-06 10:37:17 -08005625 return true;
5626}
5627
5628Call::Stats PeerConnection::GetCallStats() {
5629 if (!worker_thread()->IsCurrent()) {
5630 return worker_thread()->Invoke<Call::Stats>(
5631 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5632 }
5633 if (call_) {
5634 return call_->GetStats();
5635 } else {
5636 return Call::Stats();
5637 }
5638}
5639
Zhi Huange830e682018-03-30 10:48:35 -07005640bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005641 RTC_DCHECK(network_thread()->IsCurrent());
5642 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005643 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005644 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005645 RTC_DCHECK(dtls_transport);
5646 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005647 RTC_DCHECK(sctp_transport_);
5648 sctp_invoker_.reset(new rtc::AsyncInvoker());
5649 sctp_transport_->SignalReadyToSendData.connect(
5650 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5651 sctp_transport_->SignalDataReceived.connect(
5652 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005653 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5654 // another thread. Would be nice if there was a helper class similar to
5655 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5656 // code.
5657 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5658 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5659 sctp_transport_->SignalClosingProcedureComplete.connect(
5660 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005661 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005662 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005663 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005664}
5665
5666void PeerConnection::DestroySctpTransport_n() {
5667 RTC_DCHECK(network_thread()->IsCurrent());
5668 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005669 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005670 sctp_invoker_.reset(nullptr);
5671 sctp_ready_to_send_data_ = false;
5672}
5673
5674void PeerConnection::OnSctpTransportReadyToSendData_n() {
5675 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5676 RTC_DCHECK(network_thread()->IsCurrent());
5677 // Note: Cannot use rtc::Bind here because it will grab a reference to
5678 // PeerConnection and potentially cause PeerConnection to live longer than
5679 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5680 // be destroyed before PeerConnection is destroyed, and at that point all
5681 // pending tasks will be cleared.
5682 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5683 OnSctpTransportReadyToSendData_s(true);
5684 });
5685}
5686
5687void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5688 RTC_DCHECK(signaling_thread()->IsCurrent());
5689 sctp_ready_to_send_data_ = ready;
5690 SignalSctpReadyToSendData(ready);
5691}
5692
5693void PeerConnection::OnSctpTransportDataReceived_n(
5694 const cricket::ReceiveDataParams& params,
5695 const rtc::CopyOnWriteBuffer& payload) {
5696 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5697 RTC_DCHECK(network_thread()->IsCurrent());
5698 // Note: Cannot use rtc::Bind here because it will grab a reference to
5699 // PeerConnection and potentially cause PeerConnection to live longer than
5700 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5701 // be destroyed before PeerConnection is destroyed, and at that point all
5702 // pending tasks will be cleared.
5703 sctp_invoker_->AsyncInvoke<void>(
5704 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5705 OnSctpTransportDataReceived_s(params, payload);
5706 });
5707}
5708
5709void PeerConnection::OnSctpTransportDataReceived_s(
5710 const cricket::ReceiveDataParams& params,
5711 const rtc::CopyOnWriteBuffer& payload) {
5712 RTC_DCHECK(signaling_thread()->IsCurrent());
5713 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5714 // Received OPEN message; parse and signal that a new data channel should
5715 // be created.
5716 std::string label;
5717 InternalDataChannelInit config;
5718 config.id = params.ssrc;
5719 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005720 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5721 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005722 return;
5723 }
5724 config.open_handshake_role = InternalDataChannelInit::kAcker;
5725 OnDataChannelOpenMessage(label, config);
5726 } else {
5727 // Otherwise just forward the signal.
5728 SignalSctpDataReceived(params, payload);
5729 }
5730}
5731
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005732void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005733 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5734 RTC_DCHECK(network_thread()->IsCurrent());
5735 sctp_invoker_->AsyncInvoke<void>(
5736 RTC_FROM_HERE, signaling_thread(),
5737 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005738 &SignalSctpClosingProcedureStartedRemotely, sid));
5739}
5740
5741void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5742 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5743 RTC_DCHECK(network_thread()->IsCurrent());
5744 sctp_invoker_->AsyncInvoke<void>(
5745 RTC_FROM_HERE, signaling_thread(),
5746 rtc::Bind(&sigslot::signal1<int>::operator(),
5747 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005748}
5749
5750// Returns false if bundle is enabled and rtcp_mux is disabled.
5751bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5752 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5753 if (!bundle_enabled)
5754 return true;
5755
5756 const cricket::ContentGroup* bundle_group =
5757 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5758 RTC_DCHECK(bundle_group != NULL);
5759
5760 const cricket::ContentInfos& contents = desc->contents();
5761 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5762 citer != contents.end(); ++citer) {
5763 const cricket::ContentInfo* content = (&*citer);
5764 RTC_DCHECK(content != NULL);
5765 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005766 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005767 if (!HasRtcpMuxEnabled(content))
5768 return false;
5769 }
5770 }
5771 // RTCP-MUX is enabled in all the contents.
5772 return true;
5773}
5774
5775bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005776 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005777}
5778
Steve Anton8a006912017-12-04 15:25:56 -08005779RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005780 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005781 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005782 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005783 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005784 }
5785
5786 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005787 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005788 }
5789
Steve Anton3828c062017-12-06 10:34:51 -08005790 SdpType type = sdesc->GetType();
5791 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5792 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005793 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005794 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005795 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005796 }
5797
5798 // Verify crypto settings.
5799 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005800 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5801 dtls_enabled_) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005802 RTCError crypto_error =
5803 VerifyCrypto(sdesc->description(), dtls_enabled_, uma_observer_);
Steve Anton8a006912017-12-04 15:25:56 -08005804 if (!crypto_error.ok()) {
5805 return crypto_error;
5806 }
Steve Anton75737c02017-11-06 10:37:17 -08005807 }
5808
5809 // Verify ice-ufrag and ice-pwd.
5810 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005811 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5812 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005813 }
5814
5815 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005816 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5817 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005818 }
5819
5820 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5821 // m-lines that do not rtcp-mux enabled.
5822
5823 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005824 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005825 // With an answer we want to compare the new answer session description with
5826 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005827 const cricket::SessionDescription* offer_desc =
5828 (source == cricket::CS_LOCAL) ? remote_description()->description()
5829 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005830 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5831 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5832 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005833 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5834 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005835 }
5836 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005837 // The re-offers should respect the order of m= sections in current
5838 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005839 // With a re-offer, either the current local or current remote descriptions
5840 // could be the most up to date, so we would like to check against both of
5841 // them if they exist. It could be the case that one of them has a 0 port
5842 // for a media section, but the other does not. This is important to check
5843 // against in the case that we are recycling an m= section.
5844 const cricket::SessionDescription* current_desc = nullptr;
5845 const cricket::SessionDescription* secondary_current_desc = nullptr;
5846 if (local_description()) {
5847 current_desc = local_description()->description();
5848 if (remote_description()) {
5849 secondary_current_desc = remote_description()->description();
5850 }
5851 } else if (remote_description()) {
5852 current_desc = remote_description()->description();
5853 }
Steve Anton75737c02017-11-06 10:37:17 -08005854 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005855 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5856 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005857 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5858 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005859 }
5860 }
5861
Steve Antonba42e992018-04-09 14:10:01 -07005862 if (IsUnifiedPlan()) {
5863 // Ensure that each audio and video media section has at most one
5864 // "StreamParams". This will return an error if receiving a session
5865 // description from a "Plan B" endpoint which adds multiple tracks of the
5866 // same type. With Unified Plan, there can only be at most one track per
5867 // media section.
5868 for (const ContentInfo& content : sdesc->description()->contents()) {
5869 const MediaContentDescription& desc = *content.description;
5870 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5871 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5872 desc.streams().size() > 1u) {
5873 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5874 "Media section has more than one track specified "
5875 "with a=ssrc lines which is not supported with "
5876 "Unified Plan.");
5877 }
5878 }
5879 }
5880
Steve Anton8a006912017-12-04 15:25:56 -08005881 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005882}
5883
Steve Anton3828c062017-12-06 10:34:51 -08005884bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005885 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005886 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005887 return (state == PeerConnectionInterface::kStable) ||
5888 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005889 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005890 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005891 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5892 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5893 }
5894}
5895
Steve Anton3828c062017-12-06 10:34:51 -08005896bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005897 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005898 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005899 return (state == PeerConnectionInterface::kStable) ||
5900 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005901 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005902 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005903 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5904 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5905 }
5906}
5907
Steve Antonf8470812017-12-04 10:46:21 -08005908const char* PeerConnection::SessionErrorToString(SessionError error) const {
5909 switch (error) {
5910 case SessionError::kNone:
5911 return "ERROR_NONE";
5912 case SessionError::kContent:
5913 return "ERROR_CONTENT";
5914 case SessionError::kTransport:
5915 return "ERROR_TRANSPORT";
5916 }
5917 RTC_NOTREACHED();
5918 return "";
5919}
5920
Steve Anton75737c02017-11-06 10:37:17 -08005921std::string PeerConnection::GetSessionErrorMsg() {
5922 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08005923 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5924 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005925 return desc.str();
5926}
5927
Steve Anton8e20f172018-03-06 10:55:04 -08005928void PeerConnection::ReportSdpFormatReceived(
5929 const SessionDescriptionInterface& remote_offer) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005930 if (!uma_observer_) {
5931 return;
5932 }
Steve Anton8e20f172018-03-06 10:55:04 -08005933 int num_audio_mlines = 0;
5934 int num_video_mlines = 0;
5935 int num_audio_tracks = 0;
5936 int num_video_tracks = 0;
5937 for (const ContentInfo& content : remote_offer.description()->contents()) {
5938 cricket::MediaType media_type = content.media_description()->type();
5939 int num_tracks = std::max(
5940 1, static_cast<int>(content.media_description()->streams().size()));
5941 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5942 num_audio_mlines += 1;
5943 num_audio_tracks += num_tracks;
5944 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5945 num_video_mlines += 1;
5946 num_video_tracks += num_tracks;
5947 }
5948 }
5949 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5950 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5951 format = kSdpFormatReceivedComplexUnifiedPlan;
5952 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5953 format = kSdpFormatReceivedComplexPlanB;
5954 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5955 format = kSdpFormatReceivedSimple;
5956 }
Qingsi Wang78fef762018-07-11 18:33:52 +00005957 uma_observer_->IncrementEnumCounter(kEnumCounterSdpFormatReceived, format,
5958 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005959}
5960
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005961void PeerConnection::NoteUsageEvent(UsageEvent event) {
5962 RTC_DCHECK_RUN_ON(signaling_thread());
5963 usage_event_accumulator_ |= static_cast<int>(event);
5964}
5965
5966void PeerConnection::ReportUsagePattern() const {
5967 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang78fef762018-07-11 18:33:52 +00005968 if (uma_observer_) {
5969 uma_observer_->IncrementSparseEnumCounter(kEnumCounterUsagePattern,
5970 usage_event_accumulator_);
5971 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005972}
5973
Steve Anton0ffaaa22018-02-23 10:31:30 -08005974void PeerConnection::ReportNegotiatedSdpSemantics(
5975 const SessionDescriptionInterface& answer) {
Qingsi Wang78fef762018-07-11 18:33:52 +00005976 if (!uma_observer_) {
5977 return;
5978 }
Steve Anton0ffaaa22018-02-23 10:31:30 -08005979 switch (answer.description()->msid_signaling()) {
5980 case 0:
Qingsi Wang78fef762018-07-11 18:33:52 +00005981 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5982 kSdpSemanticNegotiatedNone,
5983 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005984 break;
5985 case cricket::kMsidSignalingMediaSection:
Qingsi Wang78fef762018-07-11 18:33:52 +00005986 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5987 kSdpSemanticNegotiatedUnifiedPlan,
5988 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005989 break;
5990 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang78fef762018-07-11 18:33:52 +00005991 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5992 kSdpSemanticNegotiatedPlanB,
5993 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005994 break;
5995 case cricket::kMsidSignalingMediaSection |
5996 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang78fef762018-07-11 18:33:52 +00005997 uma_observer_->IncrementEnumCounter(kEnumCounterSdpSemanticNegotiated,
5998 kSdpSemanticNegotiatedMixed,
5999 kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006000 break;
6001 default:
6002 RTC_NOTREACHED();
6003 }
6004}
6005
Steve Anton75737c02017-11-06 10:37:17 -08006006// We need to check the local/remote description for the Transport instead of
6007// the session, because a new Transport added during renegotiation may have
6008// them unset while the session has them set from the previous negotiation.
6009// Not doing so may trigger the auto generation of transport description and
6010// mess up DTLS identity information, ICE credential, etc.
6011bool PeerConnection::ReadyToUseRemoteCandidate(
6012 const IceCandidateInterface* candidate,
6013 const SessionDescriptionInterface* remote_desc,
6014 bool* valid) {
6015 *valid = true;
6016
6017 const SessionDescriptionInterface* current_remote_desc =
6018 remote_desc ? remote_desc : remote_description();
6019
6020 if (!current_remote_desc) {
6021 return false;
6022 }
6023
6024 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6025 size_t remote_content_size =
6026 current_remote_desc->description()->contents().size();
6027 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006028 RTC_LOG(LS_ERROR)
6029 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6030 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006031
6032 *valid = false;
6033 return false;
6034 }
6035
6036 cricket::ContentInfo content =
6037 current_remote_desc->description()->contents()[mediacontent_index];
6038
6039 const std::string transport_name = GetTransportName(content.name);
6040 if (transport_name.empty()) {
6041 return false;
6042 }
Zhi Huange830e682018-03-30 10:48:35 -07006043 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006044}
6045
6046bool PeerConnection::SrtpRequired() const {
6047 return dtls_enabled_ ||
6048 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6049}
6050
6051void PeerConnection::OnTransportControllerGatheringState(
6052 cricket::IceGatheringState state) {
6053 RTC_DCHECK(signaling_thread()->IsCurrent());
6054 if (state == cricket::kIceGatheringGathering) {
6055 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6056 } else if (state == cricket::kIceGatheringComplete) {
6057 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6058 }
6059}
6060
6061void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006062 std::map<std::string, std::set<cricket::MediaType>>
6063 media_types_by_transport_name;
6064 for (auto transceiver : transceivers_) {
6065 if (transceiver->internal()->channel()) {
6066 const std::string& transport_name =
6067 transceiver->internal()->channel()->transport_name();
6068 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006069 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006070 }
Steve Anton75737c02017-11-06 10:37:17 -08006071 }
6072 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006073 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6074 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006075 }
Zhi Huange830e682018-03-30 10:48:35 -07006076
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006077 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006078 if (transport_name) {
6079 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006080 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006081 }
Zhi Huange830e682018-03-30 10:48:35 -07006082
Steve Antonc7b964c2018-02-01 14:39:45 -08006083 for (const auto& entry : media_types_by_transport_name) {
6084 const std::string& transport_name = entry.first;
6085 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006086 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006087 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006088 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006089 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006090 }
6091 }
6092}
6093// Walk through the ConnectionInfos to gather best connection usage
6094// for IPv4 and IPv6.
6095void PeerConnection::ReportBestConnectionState(
6096 const cricket::TransportStats& stats) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006097 RTC_DCHECK(metrics_observer());
Steve Antonc7b964c2018-02-01 14:39:45 -08006098 for (const cricket::TransportChannelStats& channel_stats :
6099 stats.channel_stats) {
6100 for (const cricket::ConnectionInfo& connection_info :
6101 channel_stats.connection_infos) {
6102 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006103 continue;
6104 }
6105
Qingsi Wang78fef762018-07-11 18:33:52 +00006106 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
Steve Antonc7b964c2018-02-01 14:39:45 -08006107 const cricket::Candidate& local = connection_info.local_candidate;
6108 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006109
6110 // Increment the counter for IceCandidatePairType.
6111 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6112 (local.type() == RELAY_PORT_TYPE &&
6113 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006114 type = kEnumCounterIceCandidatePairTypeTcp;
Steve Anton75737c02017-11-06 10:37:17 -08006115 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006116 type = kEnumCounterIceCandidatePairTypeUdp;
Steve Anton75737c02017-11-06 10:37:17 -08006117 } else {
6118 RTC_CHECK(0);
6119 }
Qingsi Wang78fef762018-07-11 18:33:52 +00006120 metrics_observer()->IncrementEnumCounter(
6121 type, GetIceCandidatePairCounter(local, remote),
6122 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006123
6124 // Increment the counter for IP type.
6125 if (local.address().family() == AF_INET) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006126 metrics_observer()->IncrementEnumCounter(
6127 kEnumCounterAddressFamily, kBestConnections_IPv4,
6128 kPeerConnectionAddressFamilyCounter_Max);
6129
Steve Anton75737c02017-11-06 10:37:17 -08006130 } else if (local.address().family() == AF_INET6) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006131 metrics_observer()->IncrementEnumCounter(
6132 kEnumCounterAddressFamily, kBestConnections_IPv6,
6133 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006134 } else {
6135 RTC_CHECK(0);
6136 }
6137
6138 return;
6139 }
6140 }
6141}
6142
6143void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006144 const cricket::TransportStats& stats,
6145 const std::set<cricket::MediaType>& media_types) {
Qingsi Wang78fef762018-07-11 18:33:52 +00006146 RTC_DCHECK(metrics_observer());
Steve Anton75737c02017-11-06 10:37:17 -08006147 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6148 return;
6149 }
6150
6151 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6152 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6153 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6154 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6155 return;
6156 }
6157
Qingsi Wang78fef762018-07-11 18:33:52 +00006158 for (cricket::MediaType media_type : media_types) {
6159 PeerConnectionEnumCounterType srtp_counter_type;
6160 PeerConnectionEnumCounterType ssl_counter_type;
6161 switch (media_type) {
6162 case cricket::MEDIA_TYPE_AUDIO:
6163 srtp_counter_type = kEnumCounterAudioSrtpCipher;
6164 ssl_counter_type = kEnumCounterAudioSslCipher;
6165 break;
6166 case cricket::MEDIA_TYPE_VIDEO:
6167 srtp_counter_type = kEnumCounterVideoSrtpCipher;
6168 ssl_counter_type = kEnumCounterVideoSslCipher;
6169 break;
6170 case cricket::MEDIA_TYPE_DATA:
6171 srtp_counter_type = kEnumCounterDataSrtpCipher;
6172 ssl_counter_type = kEnumCounterDataSslCipher;
6173 break;
6174 default:
6175 RTC_NOTREACHED();
6176 continue;
Steve Antonc7b964c2018-02-01 14:39:45 -08006177 }
Qingsi Wang78fef762018-07-11 18:33:52 +00006178 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6179 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
6180 srtp_crypto_suite);
6181 }
6182 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6183 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
6184 ssl_cipher_suite);
Steve Antonc7b964c2018-02-01 14:39:45 -08006185 }
Steve Anton75737c02017-11-06 10:37:17 -08006186 }
6187}
6188
6189void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6190 RTC_DCHECK(worker_thread()->IsCurrent());
6191 RTC_DCHECK(call_);
6192 call_->OnSentPacket(sent_packet);
6193}
6194
6195const std::string PeerConnection::GetTransportName(
6196 const std::string& content_name) {
6197 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006198 if (channel) {
6199 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006200 }
Steve Anton6fec8802017-12-04 10:37:29 -08006201 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006202 RTC_DCHECK(sctp_mid_);
6203 if (content_name == *sctp_mid_) {
6204 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006205 }
6206 }
6207 // Return an empty string if failed to retrieve the transport name.
6208 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006209}
6210
Steve Anton6fec8802017-12-04 10:37:29 -08006211void PeerConnection::DestroyTransceiverChannel(
6212 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6213 transceiver) {
6214 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006215
Steve Anton6fec8802017-12-04 10:37:29 -08006216 cricket::BaseChannel* channel = transceiver->internal()->channel();
6217 if (channel) {
6218 transceiver->internal()->SetChannel(nullptr);
6219 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006220 }
6221}
6222
6223void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006224 if (rtp_data_channel_) {
6225 OnDataChannelDestroyed();
6226 DestroyBaseChannel(rtp_data_channel_);
6227 rtp_data_channel_ = nullptr;
6228 }
6229
6230 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6231 // grab a reference to this PeerConnection. If this is called from the
6232 // PeerConnection destructor, the RefCountedObject vtable will have already
6233 // been destroyed (since it is a subclass of PeerConnection) and using
6234 // rtc::Bind will cause "Pure virtual function called" error to appear.
6235
6236 if (sctp_transport_) {
6237 OnDataChannelDestroyed();
6238 network_thread()->Invoke<void>(RTC_FROM_HERE,
6239 [this] { DestroySctpTransport_n(); });
6240 }
6241}
6242
6243void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6244 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006245 switch (channel->media_type()) {
6246 case cricket::MEDIA_TYPE_AUDIO:
6247 channel_manager()->DestroyVoiceChannel(
6248 static_cast<cricket::VoiceChannel*>(channel));
6249 break;
6250 case cricket::MEDIA_TYPE_VIDEO:
6251 channel_manager()->DestroyVideoChannel(
6252 static_cast<cricket::VideoChannel*>(channel));
6253 break;
6254 case cricket::MEDIA_TYPE_DATA:
6255 channel_manager()->DestroyRtpDataChannel(
6256 static_cast<cricket::RtpDataChannel*>(channel));
6257 break;
6258 default:
6259 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6260 break;
6261 }
Zhi Huange830e682018-03-30 10:48:35 -07006262}
Steve Anton6fec8802017-12-04 10:37:29 -08006263
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006264bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006265 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006266 RtpTransportInternal* rtp_transport,
6267 cricket::DtlsTransportInternal* dtls_transport) {
6268 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006269 auto base_channel = GetChannel(mid);
6270 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006271 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006272 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006273 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006274 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006275 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006276 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006277}
6278
Harald Alvestrand89061872018-01-02 14:08:34 +01006279void PeerConnection::ClearStatsCache() {
6280 if (stats_collector_) {
6281 stats_collector_->ClearCachedStatsReport();
6282 }
6283}
6284
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006285} // namespace webrtc