blob: 357e4726df028b82fb791d71de5dc25b4234e490 [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"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#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"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 10:37:17 -0800342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800389}
390
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100417
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100424 }
425}
426
Harald Alvestrand76829d72018-07-18 23:24:36 +0200427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 10:37:17 -0800432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800443 continue;
444 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800479 }
480 }
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 continue;
494 }
Steve Anton8a006912017-12-04 15:25:56 -0800495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800515 return false;
516 }
517 }
518 return true;
519}
520
521bool GetTrackIdBySsrc(const SessionDescription* session_description,
522 uint32_t ssrc,
523 std::string* track_id) {
524 RTC_DCHECK(track_id != NULL);
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::AudioContentDescription* audio_desc =
527 cricket::GetFirstAudioContentDescription(session_description);
528 if (audio_desc) {
529 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535
Steve Antonb1c1de12017-12-21 15:14:30 -0800536 const cricket::VideoContentDescription* video_desc =
537 cricket::GetFirstVideoContentDescription(session_description);
538 if (video_desc) {
539 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800540 if (found) {
541 *track_id = found->id;
542 return true;
543 }
544 }
545 return false;
546}
547
548// Get the SCTP port out of a SessionDescription.
549// Return -1 if not found.
550int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800551 const cricket::DataContentDescription* data_desc =
552 GetFirstDataContentDescription(session_description);
553 RTC_DCHECK(data_desc);
554 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800555 return -1;
556 }
Steve Anton75737c02017-11-06 10:37:17 -0800557 std::string value;
558 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
559 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800560 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800561 if (!codec.Matches(match_pattern)) {
562 continue;
563 }
564 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
565 return rtc::FromString<int>(value);
566 }
567 }
568 return -1;
569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Steve Anton75737c02017-11-06 10:37:17 -0800634} // namespace
635
Henrik Boström31638672017-11-23 17:48:32 +0100636// Upon completion, posts a task to execute the callback of the
637// SetSessionDescriptionObserver asynchronously on the same thread. At this
638// point, the state of the peer connection might no longer reflect the effects
639// of the SetRemoteDescription operation, as the peer connection could have been
640// modified during the post.
641// TODO(hbos): Remove this class once we remove the version of
642// PeerConnectionInterface::SetRemoteDescription() that takes a
643// SetSessionDescriptionObserver as an argument.
644class PeerConnection::SetRemoteDescriptionObserverAdapter
645 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
646 public:
647 SetRemoteDescriptionObserverAdapter(
648 rtc::scoped_refptr<PeerConnection> pc,
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
650 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
651
652 // SetRemoteDescriptionObserverInterface implementation.
653 void OnSetRemoteDescriptionComplete(RTCError error) override {
654 if (error.ok())
655 pc_->PostSetSessionDescriptionSuccess(wrapper_);
656 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100657 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100658 }
659
660 private:
661 rtc::scoped_refptr<PeerConnection> pc_;
662 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
663};
664
deadbeef293e9262017-01-11 12:28:30 -0800665bool PeerConnectionInterface::RTCConfiguration::operator==(
666 const PeerConnectionInterface::RTCConfiguration& o) const {
667 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700668 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800669 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000670 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700671 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800672 BundlePolicy bundle_policy;
673 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700674 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
675 int ice_candidate_pool_size;
676 bool disable_ipv6;
677 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700678 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100679 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700680 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200681 absl::optional<int> screencast_min_bitrate;
682 absl::optional<bool> combined_audio_video_bwe;
683 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800684 TcpCandidatePolicy tcp_candidate_policy;
685 CandidateNetworkPolicy candidate_network_policy;
686 int audio_jitter_buffer_max_packets;
687 bool audio_jitter_buffer_fast_accelerate;
688 int ice_connection_receiving_timeout;
689 int ice_backup_candidate_pair_ping_interval;
690 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800691 bool prioritize_most_likely_ice_candidate_pairs;
692 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800693 bool prune_turn_ports;
694 bool presume_writable_when_fully_relayed;
695 bool enable_ice_renomination;
696 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200697 absl::optional<int> ice_check_interval_strong_connectivity;
698 absl::optional<int> ice_check_interval_weak_connectivity;
699 absl::optional<int> ice_check_min_interval;
700 absl::optional<int> ice_unwritable_timeout;
701 absl::optional<int> ice_unwritable_min_checks;
702 absl::optional<int> stun_candidate_keepalive_interval;
703 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200704 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800705 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200706 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700707 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700708 bool use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -0800709 };
710 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
711 "Did you add something to RTCConfiguration and forget to "
712 "update operator==?");
713 return type == o.type && servers == o.servers &&
714 bundle_policy == o.bundle_policy &&
715 rtcp_mux_policy == o.rtcp_mux_policy &&
716 tcp_candidate_policy == o.tcp_candidate_policy &&
717 candidate_network_policy == o.candidate_network_policy &&
718 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
719 audio_jitter_buffer_fast_accelerate ==
720 o.audio_jitter_buffer_fast_accelerate &&
721 ice_connection_receiving_timeout ==
722 o.ice_connection_receiving_timeout &&
723 ice_backup_candidate_pair_ping_interval ==
724 o.ice_backup_candidate_pair_ping_interval &&
725 continual_gathering_policy == o.continual_gathering_policy &&
726 certificates == o.certificates &&
727 prioritize_most_likely_ice_candidate_pairs ==
728 o.prioritize_most_likely_ice_candidate_pairs &&
729 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800730 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700731 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100732 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800733 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800734 screencast_min_bitrate == o.screencast_min_bitrate &&
735 combined_audio_video_bwe == o.combined_audio_video_bwe &&
736 enable_dtls_srtp == o.enable_dtls_srtp &&
737 ice_candidate_pool_size == o.ice_candidate_pool_size &&
738 prune_turn_ports == o.prune_turn_ports &&
739 presume_writable_when_fully_relayed ==
740 o.presume_writable_when_fully_relayed &&
741 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800742 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800743 ice_check_interval_strong_connectivity ==
744 o.ice_check_interval_strong_connectivity &&
745 ice_check_interval_weak_connectivity ==
746 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700747 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700748 ice_unwritable_timeout == o.ice_unwritable_timeout &&
749 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800750 stun_candidate_keepalive_interval ==
751 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200752 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800753 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800754 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700755 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700756 active_reset_srtp_params == o.active_reset_srtp_params &&
757 use_media_transport == o.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -0800758}
759
760bool PeerConnectionInterface::RTCConfiguration::operator!=(
761 const PeerConnectionInterface::RTCConfiguration& o) const {
762 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800763}
764
zhihuang8f65cdf2016-05-06 18:40:30 -0700765// Generate a RTCP CNAME when a PeerConnection is created.
766std::string GenerateRtcpCname() {
767 std::string cname;
768 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100769 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800770 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700771 }
772 return cname;
773}
774
zhihuang1c378ed2017-08-17 14:10:50 -0700775bool ValidateOfferAnswerOptions(
776 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
777 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
778 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700779}
780
zhihuang1c378ed2017-08-17 14:10:50 -0700781// From |rtc_options|, fill parts of |session_options| shared by all generated
782// m= sections (in other words, nothing that involves a map/array).
783void ExtractSharedMediaSessionOptions(
784 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
785 cricket::MediaSessionOptions* session_options) {
786 session_options->vad_enabled = rtc_options.voice_activity_detection;
787 session_options->bundle_enabled = rtc_options.use_rtp_mux;
788}
zhihuanga77e6bb2017-08-14 18:17:48 -0700789
zhihuang38ede132017-06-15 12:52:32 -0700790PeerConnection::PeerConnection(PeerConnectionFactory* factory,
791 std::unique_ptr<RtcEventLog> event_log,
792 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000793 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700794 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700795 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700796 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700797 remote_streams_(StreamCollection::Create()),
798 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000799
800PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100801 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800802 RTC_DCHECK_RUN_ON(signaling_thread());
803
Steve Anton8af21862017-12-15 11:20:13 -0800804 // Need to stop transceivers before destroying the stats collector because
805 // AudioRtpSender has a reference to the StatsCollector it will update when
806 // stopping.
807 for (auto transceiver : transceivers_) {
808 transceiver->Stop();
809 }
Steve Anton4171afb2017-11-20 10:20:22 -0800810
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700811 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800812 if (stats_collector_) {
813 stats_collector_->WaitForPendingRequest();
814 stats_collector_ = nullptr;
815 }
Steve Anton75737c02017-11-06 10:37:17 -0800816
Steve Anton8af21862017-12-15 11:20:13 -0800817 // Don't destroy BaseChannels until after stats has been cleaned up so that
818 // the last stats request can still read from the channels.
819 DestroyAllChannels();
820
Mirko Bonadei675513b2017-11-09 11:09:25 +0100821 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800822
823 webrtc_session_desc_factory_.reset();
824 sctp_invoker_.reset();
825 sctp_factory_.reset();
826 transport_controller_.reset();
827
deadbeef91dd5672016-05-18 16:55:30 -0700828 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700829 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700830 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700831 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700832 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700833 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800834 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700835 event_log_.reset();
836 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000837}
838
Steve Anton8af21862017-12-15 11:20:13 -0800839void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800840 // Destroy video channels first since they may have a pointer to a voice
841 // channel.
842 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800843 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800844 DestroyTransceiverChannel(transceiver);
845 }
846 }
847 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800848 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800849 DestroyTransceiverChannel(transceiver);
850 }
851 }
852 DestroyDataChannel();
853}
854
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000855bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000856 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700857 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100858 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700859
860 RTCError config_error = ValidateConfiguration(configuration);
861 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100862 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700863 return false;
864 }
865
Benjamin Wrightcab58882018-05-02 15:12:47 -0700866 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100867 RTC_LOG(LS_ERROR)
868 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100869 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800870 return false;
871 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200872
Benjamin Wrightcab58882018-05-02 15:12:47 -0700873 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800874 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100875 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100876 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800877 return false;
878 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700879
Benjamin Wrightcab58882018-05-02 15:12:47 -0700880 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700881 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700882 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700883 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800884
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200885 cricket::ServerAddresses stun_servers;
886 std::vector<cricket::RelayServerConfig> turn_servers;
887
888 RTCErrorType parse_error =
889 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
890 if (parse_error != RTCErrorType::NONE) {
891 return false;
892 }
893
deadbeef91dd5672016-05-18 16:55:30 -0700894 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700895 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700896 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200897 RTC_FROM_HERE,
898 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
899 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000900 return false;
901 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200902 // If initialization was successful, note if STUN or TURN servers
903 // were supplied.
904 if (!stun_servers.empty()) {
905 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
906 }
907 if (!turn_servers.empty()) {
908 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
909 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000910
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700911 // Send information about IPv4/IPv6 status.
912 PeerConnectionAddressFamilyCounter address_family;
913 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
914 address_family = kPeerConnection_IPv6;
915 } else {
916 address_family = kPeerConnection_IPv4;
917 }
918 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
919 kPeerConnectionAddressFamilyCounter_Max);
920
Zhi Huange830e682018-03-30 10:48:35 -0700921 const PeerConnectionFactoryInterface::Options& options = factory_->options();
922
Steve Anton75737c02017-11-06 10:37:17 -0800923 // RFC 3264: The numeric value of the session id and version in the
924 // o line MUST be representable with a "64 bit signed integer".
925 // Due to this constraint session id |session_id_| is max limited to
926 // LLONG_MAX.
927 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700928 JsepTransportController::Config config;
929 config.redetermine_role_on_ice_restart =
930 configuration.redetermine_role_on_ice_restart;
931 config.ssl_max_version = factory_->options().ssl_max_version;
932 config.disable_encryption = options.disable_encryption;
933 config.bundle_policy = configuration.bundle_policy;
934 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
935 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700936 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700937 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700938#if defined(ENABLE_EXTERNAL_AUTH)
939 config.enable_external_auth = true;
940#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700941 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700942 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700943 signaling_thread(), network_thread(), port_allocator_.get(),
944 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700945 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800946 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700947 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800948 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700949 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800950 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700951 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800952 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
953 transport_controller_->SignalDtlsHandshakeError.connect(
954 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
955
956 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700957
deadbeefab9b2d12015-10-14 11:33:11 -0700958 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700959 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960
Steve Antonba818672017-11-06 10:21:57 -0800961 configuration_ = configuration;
962
Steve Anton75737c02017-11-06 10:37:17 -0800963 // Obtain a certificate from RTCConfiguration if any were provided (optional).
964 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
965 if (!configuration.certificates.empty()) {
966 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
967 // just picking the first one. The decision should be made based on the DTLS
968 // handshake. The DTLS negotiations need to know about all certificates.
969 certificate = configuration.certificates[0];
970 }
971
Steve Antond25da372017-11-06 14:50:29 -0800972 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800973
974 if (options.disable_encryption) {
975 dtls_enabled_ = false;
976 } else {
977 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700978 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800979 // |configuration| can override the default |dtls_enabled_| value.
980 if (configuration.enable_dtls_srtp) {
981 dtls_enabled_ = *(configuration.enable_dtls_srtp);
982 }
983 }
984
985 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
986 // It takes precendence over the disable_sctp_data_channels
987 // PeerConnectionFactoryInterface::Options.
988 if (configuration.enable_rtp_data_channel) {
989 data_channel_type_ = cricket::DCT_RTP;
990 } else {
991 // DTLS has to be enabled to use SCTP.
992 if (!options.disable_sctp_data_channels && dtls_enabled_) {
993 data_channel_type_ = cricket::DCT_SCTP;
994 }
995 }
996
997 video_options_.screencast_min_bitrate_kbps =
998 configuration.screencast_min_bitrate;
999 audio_options_.combined_audio_video_bwe =
1000 configuration.combined_audio_video_bwe;
1001
1002 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001003 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001004
1005 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001006 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001007
1008 // Whether the certificate generator/certificate is null or not determines
1009 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1010 // the right instructions by clearing the variables if needed.
1011 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001012 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001013 certificate = nullptr;
1014 } else if (certificate) {
1015 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001016 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001017 }
1018
1019 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1020 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001021 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001022 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1023 this, &PeerConnection::OnCertificateReady);
1024
1025 if (options.disable_encryption) {
1026 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1027 }
1028
1029 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001030 options.crypto_options.srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001031
Steve Anton4171afb2017-11-20 10:20:22 -08001032 // Add default audio/video transceivers for Plan B SDP.
1033 if (!IsUnifiedPlan()) {
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1037 transceivers_.push_back(
1038 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1039 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1040 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001041 int delay_ms =
1042 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001043 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1044 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001045 return true;
1046}
1047
Steve Anton038834f2017-07-14 15:59:59 -07001048RTCError PeerConnection::ValidateConfiguration(
1049 const RTCConfiguration& config) const {
1050 if (config.ice_regather_interval_range &&
1051 config.continual_gathering_policy == GATHER_ONCE) {
1052 return RTCError(RTCErrorType::INVALID_PARAMETER,
1053 "ice_regather_interval_range specified but continual "
1054 "gathering policy is GATHER_ONCE");
1055 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001056 auto result =
1057 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1058 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001059}
1060
Yves Gerey665174f2018-06-19 15:03:05 +02001061rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001062 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1063 "Plan SdpSemantics. Please use GetSenders "
1064 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001065 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001066}
1067
Yves Gerey665174f2018-06-19 15:03:05 +02001068rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001069 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1070 "Plan SdpSemantics. Please use GetReceivers "
1071 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001072 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073}
1074
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001075bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001076 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1077 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001078 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001079 if (IsClosed()) {
1080 return false;
1081 }
deadbeefab9b2d12015-10-14 11:33:11 -07001082 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001083 return false;
1084 }
deadbeefab9b2d12015-10-14 11:33:11 -07001085
1086 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001087 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1088 observer->SignalAudioTrackAdded.connect(this,
1089 &PeerConnection::OnAudioTrackAdded);
1090 observer->SignalAudioTrackRemoved.connect(
1091 this, &PeerConnection::OnAudioTrackRemoved);
1092 observer->SignalVideoTrackAdded.connect(this,
1093 &PeerConnection::OnVideoTrackAdded);
1094 observer->SignalVideoTrackRemoved.connect(
1095 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001096 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001097
deadbeefab9b2d12015-10-14 11:33:11 -07001098 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001099 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001100 }
1101 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001102 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001103 }
1104
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001105 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001106 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001107 return true;
1108}
1109
1110void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001111 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1112 "Plan SdpSemantics. Please use RemoveTrack "
1113 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001114 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001115 if (!IsClosed()) {
1116 for (const auto& track : local_stream->GetAudioTracks()) {
1117 RemoveAudioTrack(track.get(), local_stream);
1118 }
1119 for (const auto& track : local_stream->GetVideoTracks()) {
1120 RemoveVideoTrack(track.get(), local_stream);
1121 }
deadbeefab9b2d12015-10-14 11:33:11 -07001122 }
deadbeefab9b2d12015-10-14 11:33:11 -07001123 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001124 stream_observers_.erase(
1125 std::remove_if(
1126 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001127 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001128 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001129 }),
1130 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001131
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132 if (IsClosed()) {
1133 return;
1134 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001135 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001136}
1137
Steve Anton2d6c76a2018-01-05 17:10:52 -08001138RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001139 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001140 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001141 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001142 if (!track) {
1143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1144 }
1145 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1146 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1147 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1148 "Track has invalid kind: " + track->kind());
1149 }
Steve Antonf9381f02017-12-14 10:23:57 -08001150 if (IsClosed()) {
1151 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1152 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001153 }
Steve Anton4171afb2017-11-20 10:20:22 -08001154 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001155 LOG_AND_RETURN_ERROR(
1156 RTCErrorType::INVALID_PARAMETER,
1157 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001158 }
Steve Antonf9381f02017-12-14 10:23:57 -08001159 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001160 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1161 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001162 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001163 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001164 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001165 }
1166 return sender_or_error;
1167}
deadbeefe1f9d832016-01-14 15:35:42 -08001168
Steve Antonf9381f02017-12-14 10:23:57 -08001169RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1170PeerConnection::AddTrackPlanB(
1171 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001172 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001173 if (stream_ids.size() > 1u) {
1174 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1175 "AddTrack with more than one stream is not "
1176 "supported with Plan B semantics.");
1177 }
1178 std::vector<std::string> adjusted_stream_ids = stream_ids;
1179 if (adjusted_stream_ids.empty()) {
1180 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1181 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001182 cricket::MediaType media_type =
1183 (track->kind() == MediaStreamTrackInterface::kAudioKind
1184 ? cricket::MEDIA_TYPE_AUDIO
1185 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001186 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001187 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001188 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001189 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001190 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001191 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001192 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001193 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001194 if (sender_info) {
1195 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001196 }
Steve Antonf9381f02017-12-14 10:23:57 -08001197 } else {
1198 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001199 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001200 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001201 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001202 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001203 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001204 if (sender_info) {
1205 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001206 }
deadbeefe1f9d832016-01-14 15:35:42 -08001207 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001208 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001209}
deadbeefe1f9d832016-01-14 15:35:42 -08001210
Steve Antonf9381f02017-12-14 10:23:57 -08001211RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1212PeerConnection::AddTrackUnifiedPlan(
1213 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001214 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001215 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1216 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001217 RTC_LOG(LS_INFO) << "Reusing an existing "
1218 << cricket::MediaTypeToString(transceiver->media_type())
1219 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001220 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001221 transceiver->internal()->set_direction(
1222 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001223 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001224 transceiver->internal()->set_direction(
1225 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001226 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001227 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001228 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001229 } else {
1230 cricket::MediaType media_type =
1231 (track->kind() == MediaStreamTrackInterface::kAudioKind
1232 ? cricket::MEDIA_TYPE_AUDIO
1233 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001234 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1235 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001236 std::string sender_id = track->id();
1237 // Avoid creating a sender with an existing ID by generating a random ID.
1238 // This can happen if this is the second time AddTrack has created a sender
1239 // for this track.
1240 if (FindSenderById(sender_id)) {
1241 sender_id = rtc::CreateRandomUuid();
1242 }
Florent Castelli892acf02018-10-01 22:47:20 +02001243 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001244 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1245 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001246 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001247 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001248 }
Steve Antonf9381f02017-12-14 10:23:57 -08001249 return transceiver->sender();
1250}
1251
1252rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1253PeerConnection::FindFirstTransceiverForAddedTrack(
1254 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1255 RTC_DCHECK(track);
1256 for (auto transceiver : transceivers_) {
1257 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001258 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001259 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001260 !transceiver->internal()->has_ever_been_used_to_send() &&
1261 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001262 return transceiver;
1263 }
1264 }
1265 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001266}
1267
1268bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1269 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001270 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001271}
1272
Steve Anton24db5732018-07-23 10:27:33 -07001273RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001274 rtc::scoped_refptr<RtpSenderInterface> sender) {
1275 if (!sender) {
1276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1277 }
deadbeefe1f9d832016-01-14 15:35:42 -08001278 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001279 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1280 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001281 }
Steve Antonf9381f02017-12-14 10:23:57 -08001282 if (IsUnifiedPlan()) {
1283 auto transceiver = FindTransceiverBySender(sender);
1284 if (!transceiver || !sender->track()) {
1285 return RTCError::OK();
1286 }
1287 sender->SetTrack(nullptr);
1288 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001289 transceiver->internal()->set_direction(
1290 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001291 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001292 transceiver->internal()->set_direction(
1293 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001294 }
Steve Anton4171afb2017-11-20 10:20:22 -08001295 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001296 bool removed;
1297 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1298 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1299 } else {
1300 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1301 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1302 }
1303 if (!removed) {
1304 LOG_AND_RETURN_ERROR(
1305 RTCErrorType::INVALID_PARAMETER,
1306 "Couldn't find sender " + sender->id() + " to remove.");
1307 }
Steve Anton4171afb2017-11-20 10:20:22 -08001308 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001309 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001310 return RTCError::OK();
1311}
1312
1313rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1314PeerConnection::FindTransceiverBySender(
1315 rtc::scoped_refptr<RtpSenderInterface> sender) {
1316 for (auto transceiver : transceivers_) {
1317 if (transceiver->sender() == sender) {
1318 return transceiver;
1319 }
1320 }
1321 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001322}
1323
Steve Anton9158ef62017-11-27 13:01:52 -08001324RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1325PeerConnection::AddTransceiver(
1326 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1327 return AddTransceiver(track, RtpTransceiverInit());
1328}
1329
1330RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1331PeerConnection::AddTransceiver(
1332 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1333 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001334 RTC_CHECK(IsUnifiedPlan())
1335 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001336 if (!track) {
1337 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1338 }
1339 cricket::MediaType media_type;
1340 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1341 media_type = cricket::MEDIA_TYPE_AUDIO;
1342 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1343 media_type = cricket::MEDIA_TYPE_VIDEO;
1344 } else {
1345 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1346 "Track kind is not audio or video");
1347 }
1348 return AddTransceiver(media_type, track, init);
1349}
1350
1351RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1352PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1353 return AddTransceiver(media_type, RtpTransceiverInit());
1354}
1355
1356RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1357PeerConnection::AddTransceiver(cricket::MediaType media_type,
1358 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001359 RTC_CHECK(IsUnifiedPlan())
1360 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001361 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1362 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1364 "media type is not audio or video");
1365 }
1366 return AddTransceiver(media_type, nullptr, init);
1367}
1368
1369RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1370PeerConnection::AddTransceiver(
1371 cricket::MediaType media_type,
1372 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001373 const RtpTransceiverInit& init,
1374 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001375 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1376 media_type == cricket::MEDIA_TYPE_VIDEO));
1377 if (track) {
1378 RTC_DCHECK_EQ(media_type,
1379 (track->kind() == MediaStreamTrackInterface::kAudioKind
1380 ? cricket::MEDIA_TYPE_AUDIO
1381 : cricket::MEDIA_TYPE_VIDEO));
1382 }
1383
1384 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001385 if (init.send_encodings.size() > 1) {
1386 LOG_AND_RETURN_ERROR(
1387 RTCErrorType::UNSUPPORTED_PARAMETER,
1388 "Attempted to create an encoder with more than 1 encoding parameter.");
1389 }
1390
1391 for (const auto& encoding : init.send_encodings) {
1392 if (encoding.ssrc.has_value()) {
1393 LOG_AND_RETURN_ERROR(
1394 RTCErrorType::UNSUPPORTED_PARAMETER,
1395 "Attempted to set an unimplemented parameter of RtpParameters.");
1396 }
1397 }
1398
1399 RtpParameters parameters;
1400 parameters.encodings = init.send_encodings;
1401 if (UnimplementedRtpParameterHasValue(parameters)) {
1402 LOG_AND_RETURN_ERROR(
1403 RTCErrorType::UNSUPPORTED_PARAMETER,
1404 "Attempted to set an unimplemented parameter of RtpParameters.");
1405 }
Steve Anton9158ef62017-11-27 13:01:52 -08001406
Steve Anton3d954a62018-04-02 11:27:23 -07001407 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1408 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001409 // Set the sender ID equal to the track ID if the track is specified unless
1410 // that sender ID is already in use.
1411 std::string sender_id =
1412 (track && !FindSenderById(track->id()) ? track->id()
1413 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001414 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1415 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001416 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1417 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1418 transceiver->internal()->set_direction(init.direction);
1419
Steve Anton22da89f2018-01-25 13:58:07 -08001420 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001421 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001422 }
Steve Antonf9381f02017-12-14 10:23:57 -08001423
1424 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1425}
1426
Steve Anton02ee47c2018-01-10 16:26:06 -08001427rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1428PeerConnection::CreateSender(
1429 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001430 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001431 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001432 const std::vector<std::string>& stream_ids,
1433 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001434 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001435 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1436 RTC_DCHECK(!track ||
1437 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1438 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1439 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001440 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001441 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001442 } else {
1443 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1444 RTC_DCHECK(!track ||
1445 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1446 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001447 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001448 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001449 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001450 bool set_track_succeeded = sender->SetTrack(track);
1451 RTC_DCHECK(set_track_succeeded);
1452 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001453 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001454 return sender;
1455}
1456
1457rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1458PeerConnection::CreateReceiver(cricket::MediaType media_type,
1459 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001460 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1461 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001462 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001463 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001464 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1465 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001466 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001467 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001468 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001469 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001470 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1471 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001472 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001473 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001474 return receiver;
1475}
1476
1477rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1478PeerConnection::CreateAndAddTransceiver(
1479 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1480 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1481 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001482 // Ensure that the new sender does not have an ID that is already in use by
1483 // another sender.
1484 // Allow receiver IDs to conflict since those come from remote SDP (which
1485 // could be invalid, but should not cause a crash).
1486 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001487 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1488 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001489 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001490 transceiver->internal()->SignalNegotiationNeeded.connect(
1491 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001492 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001493}
1494
Steve Anton52d86772018-02-20 15:48:12 -08001495void PeerConnection::OnNegotiationNeeded() {
1496 RTC_DCHECK_RUN_ON(signaling_thread());
1497 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001498 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001499}
1500
deadbeeffac06552015-11-25 11:26:01 -08001501rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001502 const std::string& kind,
1503 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001504 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1505 "Plan SdpSemantics. Please use AddTransceiver "
1506 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001507 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001508 if (IsClosed()) {
1509 return nullptr;
1510 }
Steve Anton4171afb2017-11-20 10:20:22 -08001511
Seth Hampson5b4f0752018-04-02 16:31:36 -07001512 // Internally we need to have one stream with Plan B semantics, so we
1513 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001514 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001515 if (stream_id.empty()) {
1516 stream_ids.push_back(rtc::CreateRandomUuid());
1517 RTC_LOG(LS_INFO)
1518 << "No stream_id specified for sender. Generated stream ID: "
1519 << stream_ids[0];
1520 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001521 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001522 }
1523
Steve Anton4171afb2017-11-20 10:20:22 -08001524 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001525 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001526 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001527 auto* audio_sender = new AudioRtpSender(
1528 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001529 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001530 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001531 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001532 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001533 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001534 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001535 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001536 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001537 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001538 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001539 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001540 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001541 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001542 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001543 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001544 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001545
deadbeefe1f9d832016-01-14 15:35:42 -08001546 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001547}
1548
deadbeef70ab1a12015-09-28 16:53:55 -07001549std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1550 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001551 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001552 for (auto sender : GetSendersInternal()) {
1553 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001554 }
1555 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001556}
1557
Steve Anton4171afb2017-11-20 10:20:22 -08001558std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1559PeerConnection::GetSendersInternal() const {
1560 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1561 all_senders;
1562 for (auto transceiver : transceivers_) {
1563 auto senders = transceiver->internal()->senders();
1564 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1565 }
1566 return all_senders;
1567}
1568
deadbeef70ab1a12015-09-28 16:53:55 -07001569std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1570PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001571 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001572 for (const auto& receiver : GetReceiversInternal()) {
1573 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001574 }
1575 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001576}
1577
Steve Anton4171afb2017-11-20 10:20:22 -08001578std::vector<
1579 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1580PeerConnection::GetReceiversInternal() const {
1581 std::vector<
1582 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1583 all_receivers;
1584 for (auto transceiver : transceivers_) {
1585 auto receivers = transceiver->internal()->receivers();
1586 all_receivers.insert(all_receivers.end(), receivers.begin(),
1587 receivers.end());
1588 }
1589 return all_receivers;
1590}
1591
Steve Anton9158ef62017-11-27 13:01:52 -08001592std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1593PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001594 RTC_CHECK(IsUnifiedPlan())
1595 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001596 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1597 for (auto transceiver : transceivers_) {
1598 all_transceivers.push_back(transceiver);
1599 }
1600 return all_transceivers;
1601}
1602
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001603bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001604 MediaStreamTrackInterface* track,
1605 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001606 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001607 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001608 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001609 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001610 return false;
1611 }
1612
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001613 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001614 // The StatsCollector is used to tell if a track is valid because it may
1615 // remember tracks that the PeerConnection previously removed.
1616 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001617 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1618 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001619 return false;
1620 }
Steve Antonad182762018-09-05 20:22:40 +00001621 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1622 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001623 return true;
1624}
1625
hbos74e1a4f2016-09-15 23:33:01 -07001626void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001627 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001628 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001629 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001630 stats_collector_->GetStatsReport(callback);
1631}
1632
Henrik Boström1df1bf82018-03-20 13:24:20 +01001633void PeerConnection::GetStats(
1634 rtc::scoped_refptr<RtpSenderInterface> selector,
1635 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1636 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1637 RTC_DCHECK(callback);
1638 RTC_DCHECK(stats_collector_);
1639 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1640 if (selector) {
1641 for (const auto& proxy_transceiver : transceivers_) {
1642 for (const auto& proxy_sender :
1643 proxy_transceiver->internal()->senders()) {
1644 if (proxy_sender == selector) {
1645 internal_sender = proxy_sender->internal();
1646 break;
1647 }
1648 }
1649 if (internal_sender)
1650 break;
1651 }
1652 }
1653 // If there is no |internal_sender| then |selector| is either null or does not
1654 // belong to the PeerConnection (in Plan B, senders can be removed from the
1655 // PeerConnection). This means that "all the stats objects representing the
1656 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1657 // produces an empty stats report.
1658 stats_collector_->GetStatsReport(internal_sender, callback);
1659}
1660
1661void PeerConnection::GetStats(
1662 rtc::scoped_refptr<RtpReceiverInterface> selector,
1663 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1664 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1665 RTC_DCHECK(callback);
1666 RTC_DCHECK(stats_collector_);
1667 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1668 if (selector) {
1669 for (const auto& proxy_transceiver : transceivers_) {
1670 for (const auto& proxy_receiver :
1671 proxy_transceiver->internal()->receivers()) {
1672 if (proxy_receiver == selector) {
1673 internal_receiver = proxy_receiver->internal();
1674 break;
1675 }
1676 }
1677 if (internal_receiver)
1678 break;
1679 }
1680 }
1681 // If there is no |internal_receiver| then |selector| is either null or does
1682 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1683 // the PeerConnection). This means that "all the stats objects representing
1684 // the selector" is an empty set. Invoking GetStatsReport() with a null
1685 // selector produces an empty stats report.
1686 stats_collector_->GetStatsReport(internal_receiver, callback);
1687}
1688
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001689PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1690 return signaling_state_;
1691}
1692
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001693PeerConnectionInterface::IceConnectionState
1694PeerConnection::ice_connection_state() {
1695 return ice_connection_state_;
1696}
1697
1698PeerConnectionInterface::IceGatheringState
1699PeerConnection::ice_gathering_state() {
1700 return ice_gathering_state_;
1701}
1702
Yves Gerey665174f2018-06-19 15:03:05 +02001703rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704 const std::string& label,
1705 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001706 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001707
deadbeefab9b2d12015-10-14 11:33:11 -07001708 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001709
kwibergd1fe2812016-04-27 06:47:29 -07001710 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001711 if (config) {
1712 internal_config.reset(new InternalDataChannelInit(*config));
1713 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001714 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001715 InternalCreateDataChannel(label, internal_config.get()));
1716 if (!channel.get()) {
1717 return nullptr;
1718 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001719
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001720 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1721 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001722 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001723 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001724 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001725 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001726 return DataChannelProxy::Create(signaling_thread(), channel.get());
1727}
1728
1729void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001730 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001731 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001732
nisse7ce109a2017-01-31 00:57:56 -08001733 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001734 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001735 return;
1736 }
deadbeefab9b2d12015-10-14 11:33:11 -07001737
Steve Anton8d3444d2017-10-20 15:30:51 -07001738 if (IsClosed()) {
1739 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001740 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001741 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001742 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001743 return;
1744 }
1745
zhihuang1c378ed2017-08-17 14:10:50 -07001746 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001747 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001748 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001749 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001750 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001751 return;
1752 }
1753
Steve Anton22da89f2018-01-25 13:58:07 -08001754 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1755 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1756 if (IsUnifiedPlan()) {
1757 RTCError error = HandleLegacyOfferOptions(options);
1758 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001759 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001760 return;
1761 }
1762 }
1763
zhihuang1c378ed2017-08-17 14:10:50 -07001764 cricket::MediaSessionOptions session_options;
1765 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001766 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001767}
1768
Steve Anton22da89f2018-01-25 13:58:07 -08001769RTCError PeerConnection::HandleLegacyOfferOptions(
1770 const RTCOfferAnswerOptions& options) {
1771 RTC_DCHECK(IsUnifiedPlan());
1772
1773 if (options.offer_to_receive_audio == 0) {
1774 RemoveRecvDirectionFromReceivingTransceiversOfType(
1775 cricket::MEDIA_TYPE_AUDIO);
1776 } else if (options.offer_to_receive_audio == 1) {
1777 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1778 } else if (options.offer_to_receive_audio > 1) {
1779 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1780 "offer_to_receive_audio > 1 is not supported.");
1781 }
1782
1783 if (options.offer_to_receive_video == 0) {
1784 RemoveRecvDirectionFromReceivingTransceiversOfType(
1785 cricket::MEDIA_TYPE_VIDEO);
1786 } else if (options.offer_to_receive_video == 1) {
1787 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1788 } else if (options.offer_to_receive_video > 1) {
1789 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1790 "offer_to_receive_video > 1 is not supported.");
1791 }
1792
1793 return RTCError::OK();
1794}
1795
1796void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1797 cricket::MediaType media_type) {
1798 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001799 RtpTransceiverDirection new_direction =
1800 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1801 if (new_direction != transceiver->direction()) {
1802 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1803 << " transceiver (MID="
1804 << transceiver->mid().value_or("<not set>") << ") from "
1805 << RtpTransceiverDirectionToString(
1806 transceiver->direction())
1807 << " to "
1808 << RtpTransceiverDirectionToString(new_direction)
1809 << " since CreateOffer specified offer_to_receive=0";
1810 transceiver->internal()->set_direction(new_direction);
1811 }
Steve Anton22da89f2018-01-25 13:58:07 -08001812 }
1813}
1814
1815void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1816 cricket::MediaType media_type) {
1817 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001818 RTC_LOG(LS_INFO)
1819 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1820 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001821 RtpTransceiverInit init;
1822 init.direction = RtpTransceiverDirection::kRecvOnly;
1823 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1824 }
1825}
1826
1827std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1828PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1829 std::vector<
1830 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1831 receiving_transceivers;
1832 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001833 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001834 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1835 receiving_transceivers.push_back(transceiver);
1836 }
1837 }
1838 return receiving_transceivers;
1839}
1840
htaa2a49d92016-03-04 02:51:39 -08001841void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1842 const RTCOfferAnswerOptions& options) {
1843 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001844 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001845 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001846 return;
1847 }
1848
Steve Antondffead82018-02-06 10:31:29 -08001849 if (!(signaling_state_ == kHaveRemoteOffer ||
1850 signaling_state_ == kHaveLocalPrAnswer)) {
1851 std::string error =
1852 "PeerConnection cannot create an answer in a state other than "
1853 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001854 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001855 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001856 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001857 return;
1858 }
1859
Steve Antondffead82018-02-06 10:31:29 -08001860 // The remote description should be set if we're in the right state.
1861 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001862
Steve Anton22da89f2018-01-25 13:58:07 -08001863 if (IsUnifiedPlan()) {
1864 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1865 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1866 "supported with Unified Plan semantics. Use the "
1867 "RtpTransceiver API instead.";
1868 }
1869 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1870 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1871 "supported with Unified Plan semantics. Use the "
1872 "RtpTransceiver API instead.";
1873 }
1874 }
1875
htaa2a49d92016-03-04 02:51:39 -08001876 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001877 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001878
Steve Antond25da372017-11-06 14:50:29 -08001879 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001880}
1881
1882void PeerConnection::SetLocalDescription(
1883 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001884 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001885 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001886
Steve Anton80dd7b52018-02-16 17:08:42 -08001887 // The SetLocalDescription contract is that we take ownership of the session
1888 // description regardless of the outcome, so wrap it in a unique_ptr right
1889 // away. Ideally, SetLocalDescription's signature will be changed to take the
1890 // description as a unique_ptr argument to formalize this agreement.
1891 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1892
nisse7ce109a2017-01-31 00:57:56 -08001893 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001894 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001895 return;
1896 }
Steve Anton8a006912017-12-04 15:25:56 -08001897
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001898 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001899 PostSetSessionDescriptionFailure(
1900 observer,
1901 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001902 return;
1903 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001904
Steve Anton80dd7b52018-02-16 17:08:42 -08001905 // If a session error has occurred the PeerConnection is in a possibly
1906 // inconsistent state so fail right away.
1907 if (session_error() != SessionError::kNone) {
1908 std::string error_message = GetSessionErrorMsg();
1909 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001910 PostSetSessionDescriptionFailure(
1911 observer,
1912 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001913 return;
1914 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001915
Steve Anton80dd7b52018-02-16 17:08:42 -08001916 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1917 if (!error.ok()) {
1918 std::string error_message = GetSetDescriptionErrorMessage(
1919 cricket::CS_LOCAL, desc->GetType(), error);
1920 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001921 PostSetSessionDescriptionFailure(
1922 observer,
1923 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001924 return;
1925 }
1926
1927 // Grab the description type before moving ownership to ApplyLocalDescription,
1928 // which may destroy it before returning.
1929 const SdpType type = desc->GetType();
1930
1931 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001932 // |desc| may be destroyed at this point.
1933
1934 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001935 // If ApplyLocalDescription fails, the PeerConnection could be in an
1936 // inconsistent state, so act conservatively here and set the session error
1937 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1938 SetSessionError(SessionError::kContent, error.message());
1939 std::string error_message =
1940 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1941 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001942 PostSetSessionDescriptionFailure(
1943 observer,
1944 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001945 return;
1946 }
Steve Anton8a006912017-12-04 15:25:56 -08001947 RTC_DCHECK(local_description());
1948
1949 PostSetSessionDescriptionSuccess(observer);
1950
Steve Antonad182762018-09-05 20:22:40 +00001951 // MaybeStartGathering needs to be called after posting
1952 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1953 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001954 transport_controller_->MaybeStartGathering();
1955
Steve Antona3a92c22017-12-07 10:27:41 -08001956 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001957 // TODO(deadbeef): We already had to hop to the network thread for
1958 // MaybeStartGathering...
1959 network_thread()->Invoke<void>(
1960 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1961 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001962 // Make UMA notes about what was agreed to.
1963 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001964 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001965 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001966}
1967
1968RTCError PeerConnection::ApplyLocalDescription(
1969 std::unique_ptr<SessionDescriptionInterface> desc) {
1970 RTC_DCHECK_RUN_ON(signaling_thread());
1971 RTC_DCHECK(desc);
1972
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 // Update stats here so that we have the most recent stats for tracks and
1974 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001975 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001976
Steve Antondcc3c022017-12-22 16:02:54 -08001977 // Take a reference to the old local description since it's used below to
1978 // compare against the new local description. When setting the new local
1979 // description, grab ownership of the replaced session description in case it
1980 // is the same as |old_local_description|, to keep it alive for the duration
1981 // of the method.
1982 const SessionDescriptionInterface* old_local_description =
1983 local_description();
1984 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001985 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001986 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001987 replaced_local_description = pending_local_description_
1988 ? std::move(pending_local_description_)
1989 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001990 current_local_description_ = std::move(desc);
1991 pending_local_description_ = nullptr;
1992 current_remote_description_ = std::move(pending_remote_description_);
1993 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001994 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001995 pending_local_description_ = std::move(desc);
1996 }
1997 // The session description to apply now must be accessed by
1998 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001999 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002000
Zhi Huange830e682018-03-30 10:48:35 -07002001 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2002 if (!error.ok()) {
2003 return error;
2004 }
2005
Steve Antondcc3c022017-12-22 16:02:54 -08002006 if (IsUnifiedPlan()) {
2007 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002008 cricket::CS_LOCAL, *local_description(), old_local_description,
2009 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002010 if (!error.ok()) {
2011 return error;
2012 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002013 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2014 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002015 for (auto transceiver : transceivers_) {
2016 const ContentInfo* content =
2017 FindMediaSectionForTransceiver(transceiver, local_description());
2018 if (!content) {
2019 continue;
2020 }
2021 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002022 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2023 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002024 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002025 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2026 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2027 // "recvonly", process the removal of a remote track for the media
2028 // description, given transceiver, removeList, and muteTracks.
2029 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2030 (transceiver->internal()->fired_direction() &&
2031 RtpTransceiverDirectionHasRecv(
2032 *transceiver->internal()->fired_direction()))) {
2033 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2034 &removed_streams);
2035 }
2036 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2037 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002038 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002039 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002040 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002041 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002042 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002043 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002044 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002045 }
2046 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002047 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002048 }
2049 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002050 // Media channels will be created only when offer is set. These may use new
2051 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002052 if (type == SdpType::kOffer) {
2053 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2054 // description is applied. Restore back to old description.
2055 RTCError error = CreateChannels(*local_description()->description());
2056 if (!error.ok()) {
2057 return error;
2058 }
2059 }
Steve Antondcc3c022017-12-22 16:02:54 -08002060 // Remove unused channels if MediaContentDescription is rejected.
2061 RemoveUnusedChannels(local_description()->description());
2062 }
Steve Anton8a006912017-12-04 15:25:56 -08002063
Zhi Huange830e682018-03-30 10:48:35 -07002064 error = UpdateSessionState(type, cricket::CS_LOCAL,
2065 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002066 if (!error.ok()) {
2067 return error;
2068 }
Steve Antondcc3c022017-12-22 16:02:54 -08002069
Steve Anton8a006912017-12-04 15:25:56 -08002070 if (remote_description()) {
2071 // Now that we have a local description, we can push down remote candidates.
2072 UseCandidatesInSessionDescription(remote_description());
2073 }
2074
2075 pending_ice_restarts_.clear();
2076 if (session_error() != SessionError::kNone) {
2077 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2078 }
2079
deadbeefab9b2d12015-10-14 11:33:11 -07002080 // If setting the description decided our SSL role, allocate any necessary
2081 // SCTP sids.
2082 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002083 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002084 AllocateSctpSids(role);
2085 }
2086
Steve Antond3679212018-01-17 17:41:02 -08002087 if (IsUnifiedPlan()) {
2088 for (auto transceiver : transceivers_) {
2089 const ContentInfo* content =
2090 FindMediaSectionForTransceiver(transceiver, local_description());
2091 if (!content) {
2092 continue;
2093 }
Steve Anton74255ff2018-01-24 18:32:57 -08002094 const auto& streams = content->media_description()->streams();
2095 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002096 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002097 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002098 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002099 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002100 } else {
2101 // 0 is a special value meaning "this sender has no associated send
2102 // stream". Need to call this so the sender won't attempt to configure
2103 // a no longer existing stream and run into DCHECKs in the lower
2104 // layers.
2105 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002106 }
2107 }
2108 } else {
2109 // Plan B semantics.
2110
Steve Antondcc3c022017-12-22 16:02:54 -08002111 // Update state and SSRC of local MediaStreams and DataChannels based on the
2112 // local session description.
2113 const cricket::ContentInfo* audio_content =
2114 GetFirstAudioContent(local_description()->description());
2115 if (audio_content) {
2116 if (audio_content->rejected) {
2117 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2118 } else {
2119 const cricket::AudioContentDescription* audio_desc =
2120 audio_content->media_description()->as_audio();
2121 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2122 }
deadbeeffaac4972015-11-12 15:33:07 -08002123 }
deadbeefab9b2d12015-10-14 11:33:11 -07002124
Steve Antondcc3c022017-12-22 16:02:54 -08002125 const cricket::ContentInfo* video_content =
2126 GetFirstVideoContent(local_description()->description());
2127 if (video_content) {
2128 if (video_content->rejected) {
2129 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2130 } else {
2131 const cricket::VideoContentDescription* video_desc =
2132 video_content->media_description()->as_video();
2133 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2134 }
deadbeeffaac4972015-11-12 15:33:07 -08002135 }
deadbeefab9b2d12015-10-14 11:33:11 -07002136 }
2137
2138 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002139 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002140 if (data_content) {
2141 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002142 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002143 if (rtc::starts_with(data_desc->protocol().data(),
2144 cricket::kMediaProtocolRtpPrefix)) {
2145 UpdateLocalRtpDataChannels(data_desc->streams());
2146 }
2147 }
2148
Steve Anton8a006912017-12-04 15:25:56 -08002149 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002150}
2151
2152void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002153 SetSessionDescriptionObserver* observer,
2154 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002155 SetRemoteDescription(
2156 std::unique_ptr<SessionDescriptionInterface>(desc),
2157 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2158 new SetRemoteDescriptionObserverAdapter(this, observer)));
2159}
2160
2161void PeerConnection::SetRemoteDescription(
2162 std::unique_ptr<SessionDescriptionInterface> desc,
2163 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002164 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002165
nisse7ce109a2017-01-31 00:57:56 -08002166 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002167 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002168 return;
2169 }
Steve Anton8a006912017-12-04 15:25:56 -08002170
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002171 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002172 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002173 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002174 return;
2175 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002176
Steve Anton80dd7b52018-02-16 17:08:42 -08002177 // If a session error has occurred the PeerConnection is in a possibly
2178 // inconsistent state so fail right away.
2179 if (session_error() != SessionError::kNone) {
2180 std::string error_message = GetSessionErrorMsg();
2181 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2182 observer->OnSetRemoteDescriptionComplete(
2183 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2184 return;
2185 }
Steve Anton71439a62018-02-15 11:53:06 -08002186
Steve Antonba42e992018-04-09 14:10:01 -07002187 if (desc->GetType() == SdpType::kOffer) {
2188 // Report to UMA the format of the received offer.
2189 ReportSdpFormatReceived(*desc);
2190 }
2191
Steve Anton80dd7b52018-02-16 17:08:42 -08002192 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002193 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002194 std::string error_message = GetSetDescriptionErrorMessage(
2195 cricket::CS_REMOTE, desc->GetType(), error);
2196 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002197 observer->OnSetRemoteDescriptionComplete(
2198 RTCError(error.type(), std::move(error_message)));
2199 return;
2200 }
Steve Anton71439a62018-02-15 11:53:06 -08002201
Steve Anton80dd7b52018-02-16 17:08:42 -08002202 // Grab the description type before moving ownership to
2203 // ApplyRemoteDescription, which may destroy it before returning.
2204 const SdpType type = desc->GetType();
2205
2206 error = ApplyRemoteDescription(std::move(desc));
2207 // |desc| may be destroyed at this point.
2208
2209 if (!error.ok()) {
2210 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2211 // inconsistent state, so act conservatively here and set the session error
2212 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2213 SetSessionError(SessionError::kContent, error.message());
2214 std::string error_message =
2215 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2216 RTC_LOG(LS_ERROR) << error_message;
2217 observer->OnSetRemoteDescriptionComplete(
2218 RTCError(error.type(), std::move(error_message)));
2219 return;
2220 }
2221 RTC_DCHECK(remote_description());
2222
2223 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002224 // TODO(deadbeef): We already had to hop to the network thread for
2225 // MaybeStartGathering...
2226 network_thread()->Invoke<void>(
2227 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2228 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002229 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002230 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002231 }
2232
2233 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002234 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002235}
2236
2237RTCError PeerConnection::ApplyRemoteDescription(
2238 std::unique_ptr<SessionDescriptionInterface> desc) {
2239 RTC_DCHECK_RUN_ON(signaling_thread());
2240 RTC_DCHECK(desc);
2241
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242 // Update stats here so that we have the most recent stats for tracks and
2243 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002244 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002245
Steve Antondcc3c022017-12-22 16:02:54 -08002246 // Take a reference to the old remote description since it's used below to
2247 // compare against the new remote description. When setting the new remote
2248 // description, grab ownership of the replaced session description in case it
2249 // is the same as |old_remote_description|, to keep it alive for the duration
2250 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002251 const SessionDescriptionInterface* old_remote_description =
2252 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002253 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002254 SdpType type = desc->GetType();
2255 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002256 replaced_remote_description = pending_remote_description_
2257 ? std::move(pending_remote_description_)
2258 : std::move(current_remote_description_);
2259 current_remote_description_ = std::move(desc);
2260 pending_remote_description_ = nullptr;
2261 current_local_description_ = std::move(pending_local_description_);
2262 } else {
2263 replaced_remote_description = std::move(pending_remote_description_);
2264 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002265 }
Steve Anton8a006912017-12-04 15:25:56 -08002266 // The session description to apply now must be accessed by
2267 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002268 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002269
Zhi Huange830e682018-03-30 10:48:35 -07002270 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2271 if (!error.ok()) {
2272 return error;
2273 }
Steve Anton8a006912017-12-04 15:25:56 -08002274 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002275 if (IsUnifiedPlan()) {
2276 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002277 cricket::CS_REMOTE, *remote_description(), local_description(),
2278 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002279 if (!error.ok()) {
2280 return error;
2281 }
Steve Antondcc3c022017-12-22 16:02:54 -08002282 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002283 // Media channels will be created only when offer is set. These may use new
2284 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002285 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002286 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002287 // description is applied. Restore back to old description.
2288 RTCError error = CreateChannels(*remote_description()->description());
2289 if (!error.ok()) {
2290 return error;
2291 }
2292 }
Steve Antondcc3c022017-12-22 16:02:54 -08002293 // Remove unused channels if MediaContentDescription is rejected.
2294 RemoveUnusedChannels(remote_description()->description());
2295 }
Steve Anton8a006912017-12-04 15:25:56 -08002296
Zhi Huange830e682018-03-30 10:48:35 -07002297 // NOTE: Candidates allocation will be initiated only when
2298 // SetLocalDescription is called.
2299 error = UpdateSessionState(type, cricket::CS_REMOTE,
2300 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002301 if (!error.ok()) {
2302 return error;
2303 }
2304
2305 if (local_description() &&
2306 !UseCandidatesInSessionDescription(remote_description())) {
2307 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2308 }
2309
2310 if (old_remote_description) {
2311 for (const cricket::ContentInfo& content :
2312 old_remote_description->description()->contents()) {
2313 // Check if this new SessionDescription contains new ICE ufrag and
2314 // password that indicates the remote peer requests an ICE restart.
2315 // TODO(deadbeef): When we start storing both the current and pending
2316 // remote description, this should reset pending_ice_restarts and compare
2317 // against the current description.
2318 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2319 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002320 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002321 pending_ice_restarts_.insert(content.name);
2322 }
2323 } else {
2324 // We retain all received candidates only if ICE is not restarted.
2325 // When ICE is restarted, all previous candidates belong to an old
2326 // generation and should not be kept.
2327 // TODO(deadbeef): This goes against the W3C spec which says the remote
2328 // description should only contain candidates from the last set remote
2329 // description plus any candidates added since then. We should remove
2330 // this once we're sure it won't break anything.
2331 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2332 old_remote_description, content.name, mutable_remote_description());
2333 }
2334 }
2335 }
2336
2337 if (session_error() != SessionError::kNone) {
2338 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2339 }
2340
2341 // Set the the ICE connection state to connecting since the connection may
2342 // become writable with peer reflexive candidates before any remote candidate
2343 // is signaled.
2344 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2345 // is to have a new signal the indicates a change in checking state from the
2346 // transport and expose a new checking() member from transport that can be
2347 // read to determine the current checking state. The existing SignalConnecting
2348 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002349 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002350 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002351 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2352 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2353 }
2354
deadbeefab9b2d12015-10-14 11:33:11 -07002355 // If setting the description decided our SSL role, allocate any necessary
2356 // SCTP sids.
2357 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002358 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002359 AllocateSctpSids(role);
2360 }
2361
Steve Antondcc3c022017-12-22 16:02:54 -08002362 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002363 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002364 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002365 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002366 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002367 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002368 for (auto transceiver : transceivers_) {
2369 const ContentInfo* content =
2370 FindMediaSectionForTransceiver(transceiver, remote_description());
2371 if (!content) {
2372 continue;
2373 }
2374 const MediaContentDescription* media_desc = content->media_description();
2375 RtpTransceiverDirection local_direction =
2376 RtpTransceiverDirectionReversed(media_desc->direction());
2377 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2378 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2379 // transceiver's current direction is neither sendrecv nor recvonly,
2380 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002381 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002382 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002383 // The remote description has signaled the stream IDs.
2384 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002385 }
Steve Antondcc3c022017-12-22 16:02:54 -08002386 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002387 (!transceiver->fired_direction() ||
2388 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002389 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002390 << content->name << " (added to "
2391 << GetStreamIdsString(stream_ids) << ").";
2392
2393 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2394 for (const std::string& stream_id : stream_ids) {
2395 rtc::scoped_refptr<MediaStreamInterface> stream =
2396 remote_streams_->find(stream_id);
2397 if (!stream) {
2398 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2399 MediaStream::Create(stream_id));
2400 remote_streams_->AddStream(stream);
2401 added_streams.push_back(stream);
2402 }
2403 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002404 }
Steve Anton3172c032018-05-03 15:30:18 -07002405 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002406 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2407 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002408 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002409 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002410 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002411 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2412 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2413 // removal of a remote track for the media description, given transceiver,
2414 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002415 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002416 (transceiver->fired_direction() &&
2417 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2418 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2419 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002420 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002421 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2422 transceiver->internal()->set_fired_direction(local_direction);
2423 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2424 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002425 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002426 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2427 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002428 transceiver->internal()->set_current_direction(local_direction);
2429 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002430 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2431 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002432 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002433 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2434 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002435 transceiver->Stop();
2436 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002437 if (!content->rejected &&
2438 RtpTransceiverDirectionHasRecv(local_direction)) {
2439 // Set ssrc to 0 in the case of an unsignalled ssrc.
2440 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002441 if (!media_desc->streams().empty() &&
2442 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002443 ssrc = media_desc->streams()[0].first_ssrc();
2444 }
2445 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002446 }
Steve Antondcc3c022017-12-22 16:02:54 -08002447 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002448 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002449 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002450 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002451 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002452 observer->OnTrack(transceiver);
2453 observer->OnAddTrack(transceiver->receiver(),
2454 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002455 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002456 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002457 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002458 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002459 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002460 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002461 }
2462 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002463 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002464 }
Steve Antondcc3c022017-12-22 16:02:54 -08002465 }
2466
Henrik Boströmfdb92012017-11-09 19:55:44 +01002467 const cricket::ContentInfo* audio_content =
2468 GetFirstAudioContent(remote_description()->description());
2469 const cricket::ContentInfo* video_content =
2470 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002471 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002472 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002473 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002474 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002475 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002476 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002477
2478 // Check if the descriptions include streams, just in case the peer supports
2479 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002480 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002481 (audio_desc && !audio_desc->streams().empty()) ||
2482 (video_desc && !video_desc->streams().empty())) {
2483 remote_peer_supports_msid_ = true;
2484 }
deadbeefab9b2d12015-10-14 11:33:11 -07002485
2486 // We wait to signal new streams until we finish processing the description,
2487 // since only at that point will new streams have all their tracks.
2488 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2489
Steve Antondcc3c022017-12-22 16:02:54 -08002490 if (!IsUnifiedPlan()) {
2491 // TODO(steveanton): When removing RTP senders/receivers in response to a
2492 // rejected media section, there is some cleanup logic that expects the
2493 // voice/ video channel to still be set. But in this method the voice/video
2494 // channel would have been destroyed by the SetRemoteDescription caller
2495 // above so the cleanup that relies on them fails to run. The RemoveSenders
2496 // calls should be moved to right before the DestroyChannel calls to fix
2497 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002498
Steve Antondcc3c022017-12-22 16:02:54 -08002499 // Find all audio rtp streams and create corresponding remote AudioTracks
2500 // and MediaStreams.
2501 if (audio_content) {
2502 if (audio_content->rejected) {
2503 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2504 } else {
2505 bool default_audio_track_needed =
2506 !remote_peer_supports_msid_ &&
2507 RtpTransceiverDirectionHasSend(audio_desc->direction());
2508 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2509 default_audio_track_needed, audio_desc->type(),
2510 new_streams);
2511 }
deadbeeffaac4972015-11-12 15:33:07 -08002512 }
deadbeefab9b2d12015-10-14 11:33:11 -07002513
Steve Antondcc3c022017-12-22 16:02:54 -08002514 // Find all video rtp streams and create corresponding remote VideoTracks
2515 // and MediaStreams.
2516 if (video_content) {
2517 if (video_content->rejected) {
2518 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2519 } else {
2520 bool default_video_track_needed =
2521 !remote_peer_supports_msid_ &&
2522 RtpTransceiverDirectionHasSend(video_desc->direction());
2523 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2524 default_video_track_needed, video_desc->type(),
2525 new_streams);
2526 }
deadbeeffaac4972015-11-12 15:33:07 -08002527 }
deadbeefab9b2d12015-10-14 11:33:11 -07002528
Steve Antondcc3c022017-12-22 16:02:54 -08002529 // Update the DataChannels with the information from the remote peer.
2530 if (data_desc) {
2531 if (rtc::starts_with(data_desc->protocol().data(),
2532 cricket::kMediaProtocolRtpPrefix)) {
2533 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2534 }
deadbeefab9b2d12015-10-14 11:33:11 -07002535 }
deadbeefab9b2d12015-10-14 11:33:11 -07002536
Steve Antondcc3c022017-12-22 16:02:54 -08002537 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002538 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002539 for (size_t i = 0; i < new_streams->count(); ++i) {
2540 MediaStreamInterface* new_stream = new_streams->at(i);
2541 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002542 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002543 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2544 }
deadbeefab9b2d12015-10-14 11:33:11 -07002545
Steve Antondcc3c022017-12-22 16:02:54 -08002546 UpdateEndedRemoteMediaStreams();
2547 }
deadbeefab9b2d12015-10-14 11:33:11 -07002548
Steve Anton8a006912017-12-04 15:25:56 -08002549 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002550}
2551
Steve Anton0f5400a2018-07-17 14:25:36 -07002552void PeerConnection::ProcessRemovalOfRemoteTrack(
2553 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2554 transceiver,
2555 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2556 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2557 RTC_DCHECK(transceiver->mid());
2558 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2559 << *transceiver->mid();
2560 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2561 transceiver->internal()->receiver_internal()->streams();
2562 // This will remove the remote track from the streams.
2563 transceiver->internal()->receiver_internal()->set_stream_ids({});
2564 remove_list->push_back(transceiver);
2565 // Remove any streams that no longer have tracks.
2566 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2567 // of streams, see if the stream was removed by checking if this was the
2568 // last receiver with that stream ID.
2569 for (auto stream : media_streams) {
2570 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2571 remote_streams_->RemoveStream(stream);
2572 removed_streams->push_back(stream);
2573 }
2574 }
2575}
2576
Steve Antondcc3c022017-12-22 16:02:54 -08002577RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2578 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002579 const SessionDescriptionInterface& new_session,
2580 const SessionDescriptionInterface* old_local_description,
2581 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002582 RTC_DCHECK(IsUnifiedPlan());
2583
Steve Anton7464fca2018-01-19 11:10:37 -08002584 const cricket::ContentGroup* bundle_group = nullptr;
2585 if (new_session.GetType() == SdpType::kOffer) {
2586 auto bundle_group_or_error =
2587 GetEarlyBundleGroup(*new_session.description());
2588 if (!bundle_group_or_error.ok()) {
2589 return bundle_group_or_error.MoveError();
2590 }
2591 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002592 }
Steve Antondcc3c022017-12-22 16:02:54 -08002593
Steve Antondcc3c022017-12-22 16:02:54 -08002594 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002595 for (size_t i = 0; i < new_contents.size(); ++i) {
2596 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002597 cricket::MediaType media_type = new_content.media_description()->type();
2598 seen_mids_.insert(new_content.name);
2599 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2600 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002601 const cricket::ContentInfo* old_local_content = nullptr;
2602 if (old_local_description &&
2603 i < old_local_description->description()->contents().size()) {
2604 old_local_content =
2605 &old_local_description->description()->contents()[i];
2606 }
2607 const cricket::ContentInfo* old_remote_content = nullptr;
2608 if (old_remote_description &&
2609 i < old_remote_description->description()->contents().size()) {
2610 old_remote_content =
2611 &old_remote_description->description()->contents()[i];
2612 }
Steve Antondcc3c022017-12-22 16:02:54 -08002613 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002614 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2615 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002616 if (!transceiver_or_error.ok()) {
2617 return transceiver_or_error.MoveError();
2618 }
2619 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002620 RTCError error =
2621 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2622 if (!error.ok()) {
2623 return error;
2624 }
2625 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002626 if (GetDataMid() && new_content.name != *GetDataMid()) {
2627 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002628 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2629 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002630 continue;
2631 }
2632 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2633 if (!error.ok()) {
2634 return error;
2635 }
Steve Antondcc3c022017-12-22 16:02:54 -08002636 } else {
2637 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2638 "Unknown section type.");
2639 }
2640 }
2641
2642 return RTCError::OK();
2643}
2644
2645RTCError PeerConnection::UpdateTransceiverChannel(
2646 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2647 transceiver,
2648 const cricket::ContentInfo& content,
2649 const cricket::ContentGroup* bundle_group) {
2650 RTC_DCHECK(IsUnifiedPlan());
2651 RTC_DCHECK(transceiver);
2652 cricket::BaseChannel* channel = transceiver->internal()->channel();
2653 if (content.rejected) {
2654 if (channel) {
2655 transceiver->internal()->SetChannel(nullptr);
2656 DestroyBaseChannel(channel);
2657 }
2658 } else {
2659 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002660 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002661 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002662 } else {
Steve Anton69470252018-02-09 11:43:08 -08002663 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002664 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002665 }
2666 if (!channel) {
2667 LOG_AND_RETURN_ERROR(
2668 RTCErrorType::INTERNAL_ERROR,
2669 "Failed to create channel for mid=" + content.name);
2670 }
2671 transceiver->internal()->SetChannel(channel);
2672 }
2673 }
2674 return RTCError::OK();
2675}
2676
Steve Antonfa2260d2017-12-28 16:38:23 -08002677RTCError PeerConnection::UpdateDataChannel(
2678 cricket::ContentSource source,
2679 const cricket::ContentInfo& content,
2680 const cricket::ContentGroup* bundle_group) {
2681 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002682 // If data channels are disabled, ignore this media section. CreateAnswer
2683 // will take care of rejecting it.
2684 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002685 }
2686 if (content.rejected) {
2687 DestroyDataChannel();
2688 } else {
2689 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002690 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002691 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2692 "Failed to create data channel.");
2693 }
2694 }
2695 if (source == cricket::CS_REMOTE) {
2696 const MediaContentDescription* data_desc = content.media_description();
2697 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2698 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2699 }
2700 }
2701 }
2702 return RTCError::OK();
2703}
2704
Steve Antondcc3c022017-12-22 16:02:54 -08002705RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2706PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002707 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002708 size_t mline_index,
2709 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002710 const ContentInfo* old_local_content,
2711 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002712 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002713 // If this is an offer then the m= section might be recycled. If the m=
2714 // section is being recycled (defined as: rejected in the current local or
2715 // remote description and not rejected in new description), dissociate the
2716 // currently associated RtpTransceiver by setting its mid property to null,
2717 // and discard the mapping between the transceiver and its m= section index.
2718 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2719 old_remote_content)) {
2720 // We want to dissociate the transceiver that has the rejected mid.
2721 const std::string& old_mid =
2722 (old_local_content && old_local_content->rejected)
2723 ? old_local_content->name
2724 : old_remote_content->name;
2725 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002726 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002727 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2728 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002729 old_transceiver->internal()->set_mid(absl::nullopt);
2730 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002731 }
2732 }
2733 const MediaContentDescription* media_desc = content.media_description();
2734 auto transceiver = GetAssociatedTransceiver(content.name);
2735 if (source == cricket::CS_LOCAL) {
2736 // Find the RtpTransceiver that corresponds to this m= section, using the
2737 // mapping between transceivers and m= section indices established when
2738 // creating the offer.
2739 if (!transceiver) {
2740 transceiver = GetTransceiverByMLineIndex(mline_index);
2741 }
2742 if (!transceiver) {
2743 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2744 "Unknown transceiver");
2745 }
2746 } else {
2747 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2748 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2749 // of the same type...
2750 if (!transceiver &&
2751 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2752 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2753 }
2754 // If no RtpTransceiver was found in the previous step, create one with a
2755 // recvonly direction.
2756 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002757 RTC_LOG(LS_INFO) << "Adding "
2758 << cricket::MediaTypeToString(media_desc->type())
2759 << " transceiver for MID=" << content.name
2760 << " at i=" << mline_index
2761 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002762 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002763 auto sender =
2764 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002765 std::string receiver_id;
2766 if (!media_desc->streams().empty()) {
2767 receiver_id = media_desc->streams()[0].id;
2768 } else {
2769 receiver_id = rtc::CreateRandomUuid();
2770 }
2771 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002772 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002773 transceiver->internal()->set_direction(
2774 RtpTransceiverDirection::kRecvOnly);
2775 }
2776 }
2777 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002778 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002779 LOG_AND_RETURN_ERROR(
2780 RTCErrorType::INVALID_PARAMETER,
2781 "Transceiver type does not match media description type.");
2782 }
2783 // Associate the found or created RtpTransceiver with the m= section by
2784 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2785 // section, and establish a mapping between the transceiver and the index of
2786 // the m= section.
2787 transceiver->internal()->set_mid(content.name);
2788 transceiver->internal()->set_mline_index(mline_index);
2789 return std::move(transceiver);
2790}
2791
2792rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2793PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2794 RTC_DCHECK(IsUnifiedPlan());
2795 for (auto transceiver : transceivers_) {
2796 if (transceiver->mid() == mid) {
2797 return transceiver;
2798 }
2799 }
2800 return nullptr;
2801}
2802
2803rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2804PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2805 RTC_DCHECK(IsUnifiedPlan());
2806 for (auto transceiver : transceivers_) {
2807 if (transceiver->internal()->mline_index() == mline_index) {
2808 return transceiver;
2809 }
2810 }
2811 return nullptr;
2812}
2813
2814rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2815PeerConnection::FindAvailableTransceiverToReceive(
2816 cricket::MediaType media_type) const {
2817 RTC_DCHECK(IsUnifiedPlan());
2818 // From JSEP section 5.10 (Applying a Remote Description):
2819 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2820 // the same type that were added to the PeerConnection by addTrack and are not
2821 // associated with any m= section and are not stopped, find the first such
2822 // RtpTransceiver.
2823 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002824 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002825 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2826 !transceiver->stopped()) {
2827 return transceiver;
2828 }
2829 }
2830 return nullptr;
2831}
2832
Steve Antoned10bd92017-12-05 10:52:59 -08002833const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2834 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2835 transceiver,
2836 const SessionDescriptionInterface* sdesc) const {
2837 RTC_DCHECK(transceiver);
2838 RTC_DCHECK(sdesc);
2839 if (IsUnifiedPlan()) {
2840 if (!transceiver->internal()->mid()) {
2841 // This transceiver is not associated with a media section yet.
2842 return nullptr;
2843 }
2844 return sdesc->description()->GetContentByName(
2845 *transceiver->internal()->mid());
2846 } else {
2847 // Plan B only allows at most one audio and one video section, so use the
2848 // first media section of that type.
2849 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002850 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002851 }
2852}
2853
deadbeef46c73892016-11-16 19:42:04 -08002854PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2855 return configuration_;
2856}
2857
deadbeef293e9262017-01-11 12:28:30 -08002858bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2859 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002860 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002861 if (IsClosed()) {
2862 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2863 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2864 }
2865
Qingsi Wanga2d60672018-04-11 16:57:45 -07002866 // According to JSEP, after setLocalDescription, changing the candidate pool
2867 // size is not allowed, and changing the set of ICE servers will not result
2868 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002869 if (local_description() && configuration.ice_candidate_pool_size !=
2870 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002871 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2872 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002873 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002874 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002875
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002876 if (local_description() &&
2877 configuration.use_media_transport != configuration_.use_media_transport) {
2878 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2879 "SetLocalDescription.";
2880 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2881 }
2882
2883 if (remote_description() &&
2884 configuration.use_media_transport != configuration_.use_media_transport) {
2885 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2886 "SetRemoteDescription.";
2887 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2888 }
2889
deadbeef293e9262017-01-11 12:28:30 -08002890 // The simplest (and most future-compatible) way to tell if the config was
2891 // modified in an invalid way is to copy each property we do support
2892 // modifying, then use operator==. There are far more properties we don't
2893 // support modifying than those we do, and more could be added.
2894 RTCConfiguration modified_config = configuration_;
2895 modified_config.servers = configuration.servers;
2896 modified_config.type = configuration.type;
2897 modified_config.ice_candidate_pool_size =
2898 configuration.ice_candidate_pool_size;
2899 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002900 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002901 modified_config.ice_check_interval_strong_connectivity =
2902 configuration.ice_check_interval_strong_connectivity;
2903 modified_config.ice_check_interval_weak_connectivity =
2904 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002905 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2906 modified_config.ice_unwritable_min_checks =
2907 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002908 modified_config.stun_candidate_keepalive_interval =
2909 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002910 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002911 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002912 modified_config.active_reset_srtp_params =
2913 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002914 modified_config.use_media_transport = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08002915 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002916 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002917 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2918 }
2919
Steve Anton038834f2017-07-14 15:59:59 -07002920 // Validate the modified configuration.
2921 RTCError validate_error = ValidateConfiguration(modified_config);
2922 if (!validate_error.ok()) {
2923 return SafeSetError(std::move(validate_error), error);
2924 }
2925
deadbeef293e9262017-01-11 12:28:30 -08002926 // Note that this isn't possible through chromium, since it's an unsigned
2927 // short in WebIDL.
2928 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002929 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002930 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2931 }
2932
2933 // Parse ICE servers before hopping to network thread.
2934 cricket::ServerAddresses stun_servers;
2935 std::vector<cricket::RelayServerConfig> turn_servers;
2936 RTCErrorType parse_error =
2937 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2938 if (parse_error != RTCErrorType::NONE) {
2939 return SafeSetError(parse_error, error);
2940 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002941 // Note if STUN or TURN servers were supplied.
2942 if (!stun_servers.empty()) {
2943 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2944 }
2945 if (!turn_servers.empty()) {
2946 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2947 }
deadbeef293e9262017-01-11 12:28:30 -08002948
2949 // In theory this shouldn't fail.
2950 if (!network_thread()->Invoke<bool>(
2951 RTC_FROM_HERE,
2952 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2953 stun_servers, turn_servers, modified_config.type,
2954 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002955 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002956 modified_config.turn_customizer,
2957 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002958 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002959 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2960 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002961
deadbeefd1a38b52016-12-10 13:15:33 -08002962 // As described in JSEP, calling setConfiguration with new ICE servers or
2963 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2964 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002965 if (modified_config.servers != configuration_.servers ||
2966 modified_config.type != configuration_.type ||
2967 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002968 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002969 }
skvladd1f5fda2017-02-03 16:54:05 -08002970
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002971 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002972
Zhi Huangb57e1692018-06-12 11:41:11 -07002973 if (configuration_.active_reset_srtp_params !=
2974 modified_config.active_reset_srtp_params) {
2975 transport_controller_->SetActiveResetSrtpParams(
2976 modified_config.active_reset_srtp_params);
2977 }
2978
deadbeef293e9262017-01-11 12:28:30 -08002979 configuration_ = modified_config;
2980 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002981}
2982
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002983bool PeerConnection::AddIceCandidate(
2984 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002985 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002986 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002987 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002988 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
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.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002995 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002996 return false;
2997 }
2998
2999 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003000 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003001 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003002 return false;
3003 }
3004
3005 bool valid = false;
3006 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3007 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003008 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003009 return false;
3010 }
3011
3012 // Add this candidate to the remote session description.
3013 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003014 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003015 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003016 return false;
3017 }
3018
3019 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003020 bool result = UseCandidate(ice_candidate);
3021 if (result) {
3022 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3023 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3024 } else {
3025 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3026 }
3027 return result;
Steve Antond25da372017-11-06 14:50:29 -08003028 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003029 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003030 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003031 return true;
3032 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003033}
3034
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003035bool PeerConnection::RemoveIceCandidates(
3036 const std::vector<cricket::Candidate>& candidates) {
3037 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003038 if (IsClosed()) {
3039 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3040 return false;
3041 }
3042
Steve Antond25da372017-11-06 14:50:29 -08003043 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003044 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3045 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003046 return false;
3047 }
3048
3049 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003050 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003051 return false;
3052 }
3053
3054 size_t number_removed =
3055 mutable_remote_description()->RemoveCandidates(candidates);
3056 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003057 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003058 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003059 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003060 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003061 }
3062
3063 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003064 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3065 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003066 RTC_LOG(LS_ERROR)
3067 << "RemoveIceCandidates: Error when removing remote candidates: "
3068 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003069 }
3070 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003071}
3072
Niels Möller0c4f7be2018-05-07 14:01:37 +02003073RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003074 if (!worker_thread()->IsCurrent()) {
3075 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003076 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003077 }
3078
Niels Möller0c4f7be2018-05-07 14:01:37 +02003079 const bool has_min = bitrate.min_bitrate_bps.has_value();
3080 const bool has_start = bitrate.start_bitrate_bps.has_value();
3081 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003082 if (has_min && *bitrate.min_bitrate_bps < 0) {
3083 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3084 "min_bitrate_bps <= 0");
3085 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003086 if (has_start) {
3087 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003088 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003089 "start_bitrate_bps < min_bitrate_bps");
3090 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3092 "curent_bitrate_bps < 0");
3093 }
3094 }
3095 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003096 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003097 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003098 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003099 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3100 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3101 "max_bitrate_bps < min_bitrate_bps");
3102 } else if (*bitrate.max_bitrate_bps < 0) {
3103 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3104 "max_bitrate_bps < 0");
3105 }
3106 }
3107
zstein4b979802017-06-02 14:37:37 -07003108 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003109 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003110
3111 return RTCError::OK();
3112}
3113
Alex Narest78609d52017-10-20 10:37:47 +02003114void PeerConnection::SetBitrateAllocationStrategy(
3115 std::unique_ptr<rtc::BitrateAllocationStrategy>
3116 bitrate_allocation_strategy) {
3117 rtc::Thread* worker_thread = factory_->worker_thread();
3118 if (!worker_thread->IsCurrent()) {
3119 rtc::BitrateAllocationStrategy* strategy_raw =
3120 bitrate_allocation_strategy.release();
3121 auto functor = [this, strategy_raw]() {
3122 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003123 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003124 };
3125 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3126 return;
3127 }
3128 RTC_DCHECK(call_.get());
3129 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3130}
3131
henrika5f6bf242017-11-01 11:06:56 +01003132void PeerConnection::SetAudioPlayout(bool playout) {
3133 if (!worker_thread()->IsCurrent()) {
3134 worker_thread()->Invoke<void>(
3135 RTC_FROM_HERE,
3136 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3137 return;
3138 }
3139 auto audio_state =
3140 factory_->channel_manager()->media_engine()->GetAudioState();
3141 audio_state->SetPlayout(playout);
3142}
3143
3144void PeerConnection::SetAudioRecording(bool recording) {
3145 if (!worker_thread()->IsCurrent()) {
3146 worker_thread()->Invoke<void>(
3147 RTC_FROM_HERE,
3148 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3149 return;
3150 }
3151 auto audio_state =
3152 factory_->channel_manager()->media_engine()->GetAudioState();
3153 audio_state->SetRecording(recording);
3154}
3155
Steve Anton8c0f7a72017-10-03 10:03:10 -07003156std::unique_ptr<rtc::SSLCertificate>
3157PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003158 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3159 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003160 return nullptr;
3161 }
Steve Antonf25303e2018-10-16 15:23:31 -07003162 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003163}
3164
Zhi Huang70b820f2018-01-27 14:16:15 -08003165std::unique_ptr<rtc::SSLCertChain>
3166PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003167 auto audio_transceiver = GetFirstAudioTransceiver();
3168 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003169 return nullptr;
3170 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003171 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003172 audio_transceiver->internal()->channel()->transport_name());
3173}
3174
3175rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3176PeerConnection::GetFirstAudioTransceiver() const {
3177 for (auto transceiver : transceivers_) {
3178 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3179 return transceiver;
3180 }
3181 }
3182 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003183}
3184
ivoc14d5dbe2016-07-04 07:06:55 -07003185bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3186 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003187 // TODO(eladalon): It would be better to not allow negative values into PC.
3188 const size_t max_size = (max_size_bytes < 0)
3189 ? RtcEventLog::kUnlimitedOutput
3190 : rtc::saturated_cast<size_t>(max_size_bytes);
3191 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003192 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003193 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003194}
3195
Bjorn Tereliusde939432017-11-20 17:38:14 +01003196bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3197 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003198 // TODO(eladalon): In C++14, this can be done with a lambda.
3199 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003200 bool operator()() {
3201 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3202 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003203 PeerConnection* const pc;
3204 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003205 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003206 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003207 return worker_thread()->Invoke<bool>(
3208 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003209}
3210
3211void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003212 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003213 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3214}
3215
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003216const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003217 return pending_local_description_ ? pending_local_description_.get()
3218 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003219}
3220
3221const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003222 return pending_remote_description_ ? pending_remote_description_.get()
3223 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003224}
3225
deadbeeffe4a8a42016-12-20 17:56:17 -08003226const SessionDescriptionInterface* PeerConnection::current_local_description()
3227 const {
Steve Anton75737c02017-11-06 10:37:17 -08003228 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003229}
3230
3231const SessionDescriptionInterface* PeerConnection::current_remote_description()
3232 const {
Steve Anton75737c02017-11-06 10:37:17 -08003233 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003234}
3235
3236const SessionDescriptionInterface* PeerConnection::pending_local_description()
3237 const {
Steve Anton75737c02017-11-06 10:37:17 -08003238 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003239}
3240
3241const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3242 const {
Steve Anton75737c02017-11-06 10:37:17 -08003243 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003244}
3245
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003246void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003247 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248 // Update stats here so that we have the most recent stats for tracks and
3249 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003250 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003251
Steve Anton75737c02017-11-06 10:37:17 -08003252 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003253 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003254
Steve Anton8af21862017-12-15 11:20:13 -08003255 for (auto transceiver : transceivers_) {
3256 transceiver->Stop();
3257 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003258
3259 // Ensure that all asynchronous stats requests are completed before destroying
3260 // the transport controller below.
3261 if (stats_collector_) {
3262 stats_collector_->WaitForPendingRequest();
3263 }
3264
3265 // Don't destroy BaseChannels until after stats has been cleaned up so that
3266 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003267 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003268
Qingsi Wang93a84392018-01-30 17:13:09 -08003269 // The event log is used in the transport controller, which must be outlived
3270 // by the former. CreateOffer by the peer connection is implemented
3271 // asynchronously and if the peer connection is closed without resetting the
3272 // WebRTC session description factory, the session description factory would
3273 // call the transport controller.
3274 webrtc_session_desc_factory_.reset();
3275 transport_controller_.reset();
3276
deadbeef42a42632017-03-10 15:18:00 -08003277 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003278 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3279 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003280
Steve Anton978b8762017-09-29 12:15:02 -07003281 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003282 call_.reset();
3283 // The event log must outlive call (and any other object that uses it).
3284 event_log_.reset();
3285 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003286 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003287 // The .h file says that observer can be discarded after close() returns.
3288 // Make sure this is true.
3289 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003290}
3291
Steve Antonad182762018-09-05 20:22:40 +00003292void PeerConnection::OnMessage(rtc::Message* msg) {
3293 switch (msg->message_id) {
3294 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3295 SetSessionDescriptionMsg* param =
3296 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3297 param->observer->OnSuccess();
3298 delete param;
3299 break;
3300 }
3301 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3302 SetSessionDescriptionMsg* param =
3303 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3304 param->observer->OnFailure(std::move(param->error));
3305 delete param;
3306 break;
3307 }
3308 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3309 CreateSessionDescriptionMsg* param =
3310 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3311 param->observer->OnFailure(std::move(param->error));
3312 delete param;
3313 break;
3314 }
3315 case MSG_GETSTATS: {
3316 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3317 StatsReports reports;
3318 stats_->GetStats(param->track, &reports);
3319 param->observer->OnComplete(reports);
3320 delete param;
3321 break;
3322 }
3323 case MSG_FREE_DATACHANNELS: {
3324 sctp_data_channels_to_free_.clear();
3325 break;
3326 }
3327 case MSG_REPORT_USAGE_PATTERN: {
3328 ReportUsagePattern();
3329 break;
3330 }
3331 default:
3332 RTC_NOTREACHED() << "Not implemented";
3333 break;
3334 }
3335}
3336
Steve Antonafb0bb72018-02-20 11:35:37 -08003337cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3338 RTC_DCHECK(!IsUnifiedPlan());
3339 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3340 GetAudioTransceiver()->internal()->channel());
3341 if (voice_channel) {
3342 return voice_channel->media_channel();
3343 } else {
3344 return nullptr;
3345 }
3346}
3347
3348cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3349 RTC_DCHECK(!IsUnifiedPlan());
3350 auto* video_channel = static_cast<cricket::VideoChannel*>(
3351 GetVideoTransceiver()->internal()->channel());
3352 if (video_channel) {
3353 return video_channel->media_channel();
3354 } else {
3355 return nullptr;
3356 }
3357}
3358
Steve Anton4171afb2017-11-20 10:20:22 -08003359void PeerConnection::CreateAudioReceiver(
3360 MediaStreamInterface* stream,
3361 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003362 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3363 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003364 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3365 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003366 auto* audio_receiver = new AudioRtpReceiver(
3367 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003368 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003369 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3370 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3371 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003372 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003373 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003374 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375}
3376
Steve Anton4171afb2017-11-20 10:20:22 -08003377void PeerConnection::CreateVideoReceiver(
3378 MediaStreamInterface* stream,
3379 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003380 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3381 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003382 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3383 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003384 auto* video_receiver = new VideoRtpReceiver(
3385 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003386 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003387 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3388 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3389 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003390 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003391 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003392 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393}
3394
deadbeef70ab1a12015-09-28 16:53:55 -07003395// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3396// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003397rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003398 const RtpSenderInfo& remote_sender_info) {
3399 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3400 if (!receiver) {
3401 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3402 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003403 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003404 }
Steve Anton4171afb2017-11-20 10:20:22 -08003405 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3406 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3407 } else {
3408 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3409 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003410 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003411}
3412
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003413void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3414 MediaStreamInterface* stream) {
3415 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003416 RTC_DCHECK(track);
3417 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003418 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003419 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003420 // We already have a sender for this track, so just change the stream_id
3421 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003422 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003423 return;
3424 }
3425
3426 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003427 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003428 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003429 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003430 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003431 // If the sender has already been configured in SDP, we call SetSsrc,
3432 // which will connect the sender to the underlying transport. This can
3433 // occur if a local session description that contains the ID of the sender
3434 // is set before AddStream is called. It can also occur if the local
3435 // session description is not changed and RemoveStream is called, and
3436 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003437 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003438 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003439 if (sender_info) {
3440 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003441 }
3442}
3443
3444// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3445// indefinitely, when we have unified plan SDP.
3446void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3447 MediaStreamInterface* stream) {
3448 RTC_DCHECK(!IsClosed());
3449 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003450 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003451 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3452 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003453 return;
3454 }
Steve Anton4171afb2017-11-20 10:20:22 -08003455 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003456}
3457
3458void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3459 MediaStreamInterface* stream) {
3460 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003461 RTC_DCHECK(track);
3462 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003463 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003464 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003465 // We already have a sender for this track, so just change the stream_id
3466 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003467 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003468 return;
3469 }
3470
3471 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003472 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003473 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003474 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003475 GetVideoTransceiver()->internal()->AddSender(new_sender);
3476 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003477 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003478 if (sender_info) {
3479 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003480 }
3481}
3482
3483void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3484 MediaStreamInterface* stream) {
3485 RTC_DCHECK(!IsClosed());
3486 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003487 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003488 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3489 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003490 return;
3491 }
Steve Anton4171afb2017-11-20 10:20:22 -08003492 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003493}
3494
Steve Antonba818672017-11-06 10:21:57 -08003495void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003496 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003497 if (ice_connection_state_ == new_state) {
3498 return;
3499 }
3500
deadbeefcbecd352015-09-23 11:50:27 -07003501 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003502 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003503 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003504 return;
3505 }
Steve Antonba818672017-11-06 10:21:57 -08003506
Mirko Bonadei675513b2017-11-09 11:09:25 +01003507 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3508 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003509 RTC_DCHECK(ice_connection_state_ !=
3510 PeerConnectionInterface::kIceConnectionClosed);
3511
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003512 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003513 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003514}
3515
3516void PeerConnection::OnIceGatheringChange(
3517 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003518 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003519 if (IsClosed()) {
3520 return;
3521 }
3522 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003523 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003524}
3525
jbauch81bf7b02017-03-25 08:31:12 -07003526void PeerConnection::OnIceCandidate(
3527 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003528 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003529 if (IsClosed()) {
3530 return;
3531 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003532 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003533 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3534 candidate->candidate().address().IsPrivateIP()) {
3535 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3536 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003537 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538}
3539
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003540void PeerConnection::OnIceCandidatesRemoved(
3541 const std::vector<cricket::Candidate>& candidates) {
3542 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003543 if (IsClosed()) {
3544 return;
3545 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003546 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003547}
3548
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003549void PeerConnection::ChangeSignalingState(
3550 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003551 RTC_DCHECK(signaling_thread()->IsCurrent());
3552 if (signaling_state_ == signaling_state) {
3553 return;
3554 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003555 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3556 << GetSignalingStateString(signaling_state_)
3557 << " New state: "
3558 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003559 signaling_state_ = signaling_state;
3560 if (signaling_state == kClosed) {
3561 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003562 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003563 if (ice_gathering_state_ != kIceGatheringComplete) {
3564 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003565 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003566 }
3567 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003568 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003569}
3570
deadbeefeb459812015-12-15 19:24:43 -08003571void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3572 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003573 if (IsClosed()) {
3574 return;
3575 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003576 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003577 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003578}
3579
deadbeefeb459812015-12-15 19:24:43 -08003580void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3581 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003582 if (IsClosed()) {
3583 return;
3584 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003585 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003586 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003587}
3588
3589void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3590 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003591 if (IsClosed()) {
3592 return;
3593 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003594 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003595 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003596}
3597
3598void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3599 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003600 if (IsClosed()) {
3601 return;
3602 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003603 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003604 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003605}
3606
Henrik Boström31638672017-11-23 17:48:32 +01003607void PeerConnection::PostSetSessionDescriptionSuccess(
3608 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003609 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3610 signaling_thread()->Post(RTC_FROM_HERE, this,
3611 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003612}
3613
deadbeefab9b2d12015-10-14 11:33:11 -07003614void PeerConnection::PostSetSessionDescriptionFailure(
3615 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003616 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003617 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003618 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3619 msg->error = std::move(error);
3620 signaling_thread()->Post(RTC_FROM_HERE, this,
3621 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003622}
3623
3624void PeerConnection::PostCreateSessionDescriptionFailure(
3625 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003626 RTCError error) {
3627 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003628 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3629 msg->error = std::move(error);
3630 signaling_thread()->Post(RTC_FROM_HERE, this,
3631 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003632}
3633
zhihuang1c378ed2017-08-17 14:10:50 -07003634void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003635 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003636 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003637 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003638
Steve Antondcc3c022017-12-22 16:02:54 -08003639 if (IsUnifiedPlan()) {
3640 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3641 } else {
3642 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3643 }
3644
Steve Antonfa2260d2017-12-28 16:38:23 -08003645 // Intentionally unset the data channel type for RTP data channel with the
3646 // second condition. Otherwise the RTP data channels would be successfully
3647 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3648 // when building with chromium. We want to leave RTP data channels broken, so
3649 // people won't try to use them.
3650 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3651 session_options->data_channel_type = data_channel_type();
3652 }
3653
Steve Antondcc3c022017-12-22 16:02:54 -08003654 // Apply ICE restart flag and renomination flag.
3655 for (auto& options : session_options->media_description_options) {
3656 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3657 options.transport_options.enable_ice_renomination =
3658 configuration_.enable_ice_renomination;
3659 }
3660
3661 session_options->rtcp_cname = rtcp_cname_;
3662 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003663 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003664 session_options->pooled_ice_credentials =
3665 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3666 RTC_FROM_HERE,
3667 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3668 port_allocator_.get()));
Steve Antondcc3c022017-12-22 16:02:54 -08003669}
3670
3671void PeerConnection::GetOptionsForPlanBOffer(
3672 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3673 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003674 // Figure out transceiver directional preferences.
3675 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3676 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3677
3678 // By default, generate sendrecv/recvonly m= sections.
3679 bool recv_audio = true;
3680 bool recv_video = true;
3681
3682 // By default, only offer a new m= section if we have media to send with it.
3683 bool offer_new_audio_description = send_audio;
3684 bool offer_new_video_description = send_video;
3685 bool offer_new_data_description = HasDataChannels();
3686
3687 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003688 if (offer_answer_options.offer_to_receive_audio !=
3689 RTCOfferAnswerOptions::kUndefined) {
3690 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003691 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003692 offer_new_audio_description ||
3693 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003694 }
Steve Antondcc3c022017-12-22 16:02:54 -08003695 if (offer_answer_options.offer_to_receive_video !=
3696 RTCOfferAnswerOptions::kUndefined) {
3697 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003698 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003699 offer_new_video_description ||
3700 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003701 }
3702
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003703 absl::optional<size_t> audio_index;
3704 absl::optional<size_t> video_index;
3705 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003706 // If a current description exists, generate m= sections in the same order,
3707 // using the first audio/video/data section that appears and rejecting
3708 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003709 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003710 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003711 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003712 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3713 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3714 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003715 }
3716
zhihuang1c378ed2017-08-17 14:10:50 -07003717 // Add audio/video/data m= sections to the end if needed.
3718 if (!audio_index && offer_new_audio_description) {
3719 session_options->media_description_options.push_back(
3720 cricket::MediaDescriptionOptions(
3721 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003722 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3723 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003724 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003725 }
zhihuang1c378ed2017-08-17 14:10:50 -07003726 if (!video_index && offer_new_video_description) {
3727 session_options->media_description_options.push_back(
3728 cricket::MediaDescriptionOptions(
3729 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003730 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3731 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003732 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003733 }
zhihuang1c378ed2017-08-17 14:10:50 -07003734 if (!data_index && offer_new_data_description) {
3735 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003736 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003737 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003738 }
3739
3740 cricket::MediaDescriptionOptions* audio_media_description_options =
3741 !audio_index ? nullptr
3742 : &session_options->media_description_options[*audio_index];
3743 cricket::MediaDescriptionOptions* video_media_description_options =
3744 !video_index ? nullptr
3745 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003746
Steve Anton4171afb2017-11-20 10:20:22 -08003747 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003748 video_media_description_options,
3749 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003750}
3751
3752// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3753// and return a reference to it.
3754// Generated MIDs should be no more than 3 bytes long to take up less space in
3755// the RTP packet.
3756static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3757 RTC_DCHECK(used_mids);
3758 // We're boring: just generate MIDs 0, 1, 2, ...
3759 size_t i = 0;
3760 std::set<std::string>::iterator it;
3761 bool inserted;
3762 do {
3763 std::string mid = rtc::ToString(i++);
3764 auto insert_result = used_mids->insert(mid);
3765 it = insert_result.first;
3766 inserted = insert_result.second;
3767 } while (!inserted);
3768 return *it;
3769}
3770
3771static cricket::MediaDescriptionOptions
3772GetMediaDescriptionOptionsForTransceiver(
3773 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3774 transceiver,
3775 const std::string& mid) {
3776 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003777 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003778 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003779 // This behavior is specified in JSEP. The gist is that:
3780 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3781 // sendrecv.
3782 // 2. If the MSID is included, then it must be included in any subsequent
3783 // offer/answer exactly the same until the RtpTransceiver is stopped.
3784 if (!transceiver->stopped() &&
3785 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3786 transceiver->internal()->has_ever_been_used_to_send())) {
3787 cricket::SenderOptions sender_options;
3788 sender_options.track_id = transceiver->sender()->id();
3789 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003790 int num_send_encoding_layers =
3791 transceiver->sender()->init_send_encodings().size();
3792 sender_options.num_sim_layers =
3793 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003794 media_description_options.sender_options.push_back(sender_options);
3795 }
Steve Antondcc3c022017-12-22 16:02:54 -08003796 return media_description_options;
3797}
3798
3799void PeerConnection::GetOptionsForUnifiedPlanOffer(
3800 const RTCOfferAnswerOptions& offer_answer_options,
3801 cricket::MediaSessionOptions* session_options) {
3802 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3803 // Offers) and 5.2.2 (Subsequent Offers).
3804 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3805 const ContentInfos& local_contents =
3806 (local_description() ? local_description()->description()->contents()
3807 : ContentInfos());
3808 const ContentInfos& remote_contents =
3809 (remote_description() ? remote_description()->description()->contents()
3810 : ContentInfos());
3811 // The mline indices that can be recycled. New transceivers should reuse these
3812 // slots first.
3813 std::queue<size_t> recycleable_mline_indices;
3814 // Track the MIDs used in previous offer/answer exchanges and the current
3815 // offer so that new, unique MIDs are generated.
3816 std::set<std::string> used_mids = seen_mids_;
3817 // First, go through each media section that exists in either the local or
3818 // remote description and generate a media section in this offer for the
3819 // associated transceiver. If a media section can be recycled, generate a
3820 // default, rejected media section here that can be later overwritten.
3821 for (size_t i = 0;
3822 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3823 // Either |local_content| or |remote_content| is non-null.
3824 const ContentInfo* local_content =
3825 (i < local_contents.size() ? &local_contents[i] : nullptr);
3826 const ContentInfo* remote_content =
3827 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3828 bool had_been_rejected = (local_content && local_content->rejected) ||
3829 (remote_content && remote_content->rejected);
3830 const std::string& mid =
3831 (local_content ? local_content->name : remote_content->name);
3832 cricket::MediaType media_type =
3833 (local_content ? local_content->media_description()->type()
3834 : remote_content->media_description()->type());
3835 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3836 media_type == cricket::MEDIA_TYPE_VIDEO) {
3837 auto transceiver = GetAssociatedTransceiver(mid);
3838 RTC_CHECK(transceiver);
3839 // A media section is considered eligible for recycling if it is marked as
3840 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003841 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003842 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003843 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3844 RtpTransceiverDirection::kInactive,
3845 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003846 recycleable_mline_indices.push(i);
3847 } else {
3848 session_options->media_description_options.push_back(
3849 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3850 // CreateOffer shouldn't really cause any state changes in
3851 // PeerConnection, but we need a way to match new transceivers to new
3852 // media sections in SetLocalDescription and JSEP specifies this is done
3853 // by recording the index of the media section generated for the
3854 // transceiver in the offer.
3855 transceiver->internal()->set_mline_index(i);
3856 }
3857 } else {
3858 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003859 RTC_CHECK(GetDataMid());
3860 if (had_been_rejected || mid != *GetDataMid()) {
3861 session_options->media_description_options.push_back(
3862 GetMediaDescriptionOptionsForRejectedData(mid));
3863 } else {
3864 session_options->media_description_options.push_back(
3865 GetMediaDescriptionOptionsForActiveData(mid));
3866 }
Steve Antondcc3c022017-12-22 16:02:54 -08003867 }
3868 }
3869 // Next, look for transceivers that are newly added (that is, are not stopped
3870 // and not associated). Reuse media sections marked as recyclable first,
3871 // otherwise append to the end of the offer. New media sections should be
3872 // added in the order they were added to the PeerConnection.
3873 for (auto transceiver : transceivers_) {
3874 if (transceiver->mid() || transceiver->stopped()) {
3875 continue;
3876 }
3877 size_t mline_index;
3878 if (!recycleable_mline_indices.empty()) {
3879 mline_index = recycleable_mline_indices.front();
3880 recycleable_mline_indices.pop();
3881 session_options->media_description_options[mline_index] =
3882 GetMediaDescriptionOptionsForTransceiver(transceiver,
3883 AllocateMid(&used_mids));
3884 } else {
3885 mline_index = session_options->media_description_options.size();
3886 session_options->media_description_options.push_back(
3887 GetMediaDescriptionOptionsForTransceiver(transceiver,
3888 AllocateMid(&used_mids)));
3889 }
3890 // See comment above for why CreateOffer changes the transceiver's state.
3891 transceiver->internal()->set_mline_index(mline_index);
3892 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003893 // Lastly, add a m-section if we have local data channels and an m section
3894 // does not already exist.
3895 if (!GetDataMid() && HasDataChannels()) {
3896 session_options->media_description_options.push_back(
3897 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3898 }
Steve Antondcc3c022017-12-22 16:02:54 -08003899}
3900
3901void PeerConnection::GetOptionsForAnswer(
3902 const RTCOfferAnswerOptions& offer_answer_options,
3903 cricket::MediaSessionOptions* session_options) {
3904 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3905
3906 if (IsUnifiedPlan()) {
3907 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3908 } else {
3909 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3910 }
3911
Steve Antonfa2260d2017-12-28 16:38:23 -08003912 // Intentionally unset the data channel type for RTP data channel. Otherwise
3913 // the RTP data channels would be successfully negotiated by default and the
3914 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3915 // We want to leave RTP data channels broken, so people won't try to use them.
3916 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3917 session_options->data_channel_type = data_channel_type();
3918 }
3919
Steve Antondcc3c022017-12-22 16:02:54 -08003920 // Apply ICE renomination flag.
3921 for (auto& options : session_options->media_description_options) {
3922 options.transport_options.enable_ice_renomination =
3923 configuration_.enable_ice_renomination;
3924 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003925
3926 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003927 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003928 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003929 session_options->pooled_ice_credentials =
3930 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3931 RTC_FROM_HERE,
3932 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3933 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07003934}
3935
Steve Antondcc3c022017-12-22 16:02:54 -08003936void PeerConnection::GetOptionsForPlanBAnswer(
3937 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003938 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003939 // Figure out transceiver directional preferences.
3940 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3941 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3942
3943 // By default, generate sendrecv/recvonly m= sections. The direction is also
3944 // restricted by the direction in the offer.
3945 bool recv_audio = true;
3946 bool recv_video = true;
3947
3948 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003949 if (offer_answer_options.offer_to_receive_audio !=
3950 RTCOfferAnswerOptions::kUndefined) {
3951 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003952 }
Steve Antondcc3c022017-12-22 16:02:54 -08003953 if (offer_answer_options.offer_to_receive_video !=
3954 RTCOfferAnswerOptions::kUndefined) {
3955 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003956 }
3957
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003958 absl::optional<size_t> audio_index;
3959 absl::optional<size_t> video_index;
3960 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003961
3962 // Generate m= sections that match those in the offer.
3963 // Note that mediasession.cc will handle intersection our preferred
3964 // direction with the offered direction.
3965 GenerateMediaDescriptionOptions(
3966 remote_description(),
3967 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3968 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3969 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003970
3971 cricket::MediaDescriptionOptions* audio_media_description_options =
3972 !audio_index ? nullptr
3973 : &session_options->media_description_options[*audio_index];
3974 cricket::MediaDescriptionOptions* video_media_description_options =
3975 !video_index ? nullptr
3976 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003977
Steve Anton4171afb2017-11-20 10:20:22 -08003978 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003979 video_media_description_options,
3980 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003981}
zhihuangaf388472016-11-02 16:49:48 -07003982
Steve Antondcc3c022017-12-22 16:02:54 -08003983void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3984 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3985 cricket::MediaSessionOptions* session_options) {
3986 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3987 // Answers) and 5.3.2 (Subsequent Answers).
3988 RTC_DCHECK(remote_description());
3989 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3990 for (const ContentInfo& content :
3991 remote_description()->description()->contents()) {
3992 cricket::MediaType media_type = content.media_description()->type();
3993 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3994 media_type == cricket::MEDIA_TYPE_VIDEO) {
3995 auto transceiver = GetAssociatedTransceiver(content.name);
3996 RTC_CHECK(transceiver);
3997 session_options->media_description_options.push_back(
3998 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3999 } else {
4000 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004001 // Reject all data sections if data channels are disabled.
4002 // Reject a data section if it has already been rejected.
4003 // Reject all data sections except for the first one.
4004 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4005 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004006 session_options->media_description_options.push_back(
4007 GetMediaDescriptionOptionsForRejectedData(content.name));
4008 } else {
4009 session_options->media_description_options.push_back(
4010 GetMediaDescriptionOptionsForActiveData(content.name));
4011 }
Steve Antondcc3c022017-12-22 16:02:54 -08004012 }
4013 }
htaa2a49d92016-03-04 02:51:39 -08004014}
4015
zhihuang1c378ed2017-08-17 14:10:50 -07004016void PeerConnection::GenerateMediaDescriptionOptions(
4017 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004018 RtpTransceiverDirection audio_direction,
4019 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004020 absl::optional<size_t>* audio_index,
4021 absl::optional<size_t>* video_index,
4022 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004023 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004024 for (const cricket::ContentInfo& content :
4025 session_desc->description()->contents()) {
4026 if (IsAudioContent(&content)) {
4027 // If we already have an audio m= section, reject this extra one.
4028 if (*audio_index) {
4029 session_options->media_description_options.push_back(
4030 cricket::MediaDescriptionOptions(
4031 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004032 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004033 } else {
4034 session_options->media_description_options.push_back(
4035 cricket::MediaDescriptionOptions(
4036 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004037 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004038 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004039 }
4040 } else if (IsVideoContent(&content)) {
4041 // If we already have an video m= section, reject this extra one.
4042 if (*video_index) {
4043 session_options->media_description_options.push_back(
4044 cricket::MediaDescriptionOptions(
4045 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004046 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004047 } else {
4048 session_options->media_description_options.push_back(
4049 cricket::MediaDescriptionOptions(
4050 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004051 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004052 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004053 }
4054 } else {
4055 RTC_DCHECK(IsDataContent(&content));
4056 // If we already have an data m= section, reject this extra one.
4057 if (*data_index) {
4058 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004059 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004060 } else {
4061 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004062 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004063 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004064 }
4065 }
htaa2a49d92016-03-04 02:51:39 -08004066 }
deadbeefab9b2d12015-10-14 11:33:11 -07004067}
4068
Steve Antonfa2260d2017-12-28 16:38:23 -08004069cricket::MediaDescriptionOptions
4070PeerConnection::GetMediaDescriptionOptionsForActiveData(
4071 const std::string& mid) const {
4072 // Direction for data sections is meaningless, but legacy endpoints might
4073 // expect sendrecv.
4074 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4075 RtpTransceiverDirection::kSendRecv,
4076 /*stopped=*/false);
4077 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4078 return options;
4079}
4080
4081cricket::MediaDescriptionOptions
4082PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4083 const std::string& mid) const {
4084 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4085 RtpTransceiverDirection::kInactive,
4086 /*stopped=*/true);
4087 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4088 return options;
4089}
4090
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004091absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004092 switch (data_channel_type_) {
4093 case cricket::DCT_RTP:
4094 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004095 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004096 }
4097 return rtp_data_channel_->content_name();
4098 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004099 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004100 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004101 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004102 }
4103}
4104
Steve Anton4171afb2017-11-20 10:20:22 -08004105void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4106 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4107 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004108 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004109}
4110
Steve Anton4171afb2017-11-20 10:20:22 -08004111void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004112 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004113 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004114 cricket::MediaType media_type,
4115 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004116 RTC_DCHECK(!IsUnifiedPlan());
4117
Steve Anton4171afb2017-11-20 10:20:22 -08004118 std::vector<RtpSenderInfo>* current_senders =
4119 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004120
Steve Anton4171afb2017-11-20 10:20:22 -08004121 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004122 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004123 for (auto sender_it = current_senders->begin();
4124 sender_it != current_senders->end();
4125 /* incremented manually */) {
4126 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004127 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004128 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004129 std::string params_stream_id;
4130 if (params) {
4131 params_stream_id =
4132 (!params->first_stream_id().empty() ? params->first_stream_id()
4133 : kDefaultStreamId);
4134 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004135 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004136 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004137 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004138 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004139 sender_exists) {
4140 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004141 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004142 OnRemoteSenderRemoved(info, media_type);
4143 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004144 }
4145 }
4146
Steve Anton4171afb2017-11-20 10:20:22 -08004147 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004148 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004149 if (!params.has_ssrcs()) {
4150 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4151 // sender, this means it is coming from a Unified Plan endpoint,so we just
4152 // create a default.
4153 default_sender_needed = true;
4154 break;
4155 }
4156
Seth Hampson845e8782018-03-02 11:34:10 -08004157 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004158 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004159 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4160 // not supported in Plan B, we just take the first here and create the
4161 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004162 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004163 (!params.first_stream_id().empty() ? params.first_stream_id()
4164 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004165 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004166 uint32_t ssrc = params.first_ssrc();
4167
4168 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004169 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004170 if (!stream) {
4171 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004172 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004173 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004174 remote_streams_->AddStream(stream);
4175 new_streams->AddStream(stream);
4176 }
4177
Steve Anton4171afb2017-11-20 10:20:22 -08004178 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004179 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004180 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004181 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004182 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004183 }
4184 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004185
Steve Anton4171afb2017-11-20 10:20:22 -08004186 // Add default sender if necessary.
4187 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004188 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004189 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004190 if (!default_stream) {
4191 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004192 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004193 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004194 remote_streams_->AddStream(default_stream);
4195 new_streams->AddStream(default_stream);
4196 }
Steve Anton4171afb2017-11-20 10:20:22 -08004197 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4198 ? kDefaultAudioSenderId
4199 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004200 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004201 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004202 if (!default_sender_info) {
4203 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004204 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004205 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004206 }
4207 }
deadbeefab9b2d12015-10-14 11:33:11 -07004208}
4209
Steve Anton4171afb2017-11-20 10:20:22 -08004210void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4211 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004212 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4213 << " receiver for track_id=" << sender_info.sender_id
4214 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004215
Steve Anton3d954a62018-04-02 11:27:23 -07004216 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004217 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004218 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004219 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004220 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004221 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004222 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004223 }
4224}
4225
Steve Anton4171afb2017-11-20 10:20:22 -08004226void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4227 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004228 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4229 << " receiver for track_id=" << sender_info.sender_id
4230 << " and stream_id=" << sender_info.stream_id;
4231
Seth Hampson845e8782018-03-02 11:34:10 -08004232 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004233
Henrik Boström933d8b02017-10-10 10:05:16 -07004234 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004235 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004236 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4237 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004238 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004239 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004240 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004241 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004242 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004243 }
4244 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004245 // Stopping or destroying a VideoRtpReceiver will end the
4246 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004247 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004248 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004249 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004250 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004251 // There's no guarantee the track is still available, e.g. the track may
4252 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004253 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004254 }
4255 } else {
nisseede5da42017-01-12 05:15:36 -08004256 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004257 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004258 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004259 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004260 }
deadbeefab9b2d12015-10-14 11:33:11 -07004261}
4262
4263void PeerConnection::UpdateEndedRemoteMediaStreams() {
4264 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4265 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4266 MediaStreamInterface* stream = remote_streams_->at(i);
4267 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4268 streams_to_remove.push_back(stream);
4269 }
4270 }
4271
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004272 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004273 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004274 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004275 }
4276}
4277
Steve Anton4171afb2017-11-20 10:20:22 -08004278void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004279 const std::vector<cricket::StreamParams>& streams,
4280 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004281 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004282
Seth Hampson845e8782018-03-02 11:34:10 -08004283 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004284 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004285 for (auto sender_it = current_senders->begin();
4286 sender_it != current_senders->end();
4287 /* incremented manually */) {
4288 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004289 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004290 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4291 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004292 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004293 OnLocalSenderRemoved(info, media_type);
4294 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004295 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004296 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004297 }
4298 }
4299
Steve Anton4171afb2017-11-20 10:20:22 -08004300 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004301 for (const cricket::StreamParams& params : streams) {
4302 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004303 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004304 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004305 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004306 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004307 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004308 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004309 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004310 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004311 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004312 }
4313 }
4314}
4315
Steve Anton4171afb2017-11-20 10:20:22 -08004316void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4317 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004318 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004319 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004320 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004321 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4322 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004323 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004324 return;
4325 }
4326
deadbeeffac06552015-11-25 11:26:01 -08004327 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004328 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004329 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004330 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004331 }
deadbeeffac06552015-11-25 11:26:01 -08004332
Seth Hampson5b4f0752018-04-02 16:31:36 -07004333 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004334 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004335}
4336
Steve Anton4171afb2017-11-20 10:20:22 -08004337void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4338 cricket::MediaType media_type) {
4339 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004340 if (!sender) {
4341 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004342 // SessionDescriptions has been renegotiated.
4343 return;
4344 }
deadbeeffac06552015-11-25 11:26:01 -08004345
4346 // A sender has been removed from the SessionDescription but it's still
4347 // associated with the PeerConnection. This only occurs if the SDP doesn't
4348 // match with the calls to CreateSender, AddStream and RemoveStream.
4349 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004350 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004351 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004352 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004353 }
deadbeeffac06552015-11-25 11:26:01 -08004354
Steve Anton4171afb2017-11-20 10:20:22 -08004355 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004356}
4357
4358void PeerConnection::UpdateLocalRtpDataChannels(
4359 const cricket::StreamParamsVec& streams) {
4360 std::vector<std::string> existing_channels;
4361
4362 // Find new and active data channels.
4363 for (const cricket::StreamParams& params : streams) {
4364 // |it->sync_label| is actually the data channel label. The reason is that
4365 // we use the same naming of data channels as we do for
4366 // MediaStreams and Tracks.
4367 // For MediaStreams, the sync_label is the MediaStream label and the
4368 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004369 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004370 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004371 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004372 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004373 continue;
4374 }
4375 // Set the SSRC the data channel should use for sending.
4376 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4377 existing_channels.push_back(data_channel_it->first);
4378 }
4379
4380 UpdateClosingRtpDataChannels(existing_channels, true);
4381}
4382
4383void PeerConnection::UpdateRemoteRtpDataChannels(
4384 const cricket::StreamParamsVec& streams) {
4385 std::vector<std::string> existing_channels;
4386
4387 // Find new and active data channels.
4388 for (const cricket::StreamParams& params : streams) {
4389 // The data channel label is either the mslabel or the SSRC if the mslabel
4390 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004391 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004392 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004393 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004394 auto data_channel_it = rtp_data_channels_.find(label);
4395 if (data_channel_it == rtp_data_channels_.end()) {
4396 // This is a new data channel.
4397 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4398 } else {
4399 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4400 }
4401 existing_channels.push_back(label);
4402 }
4403
4404 UpdateClosingRtpDataChannels(existing_channels, false);
4405}
4406
4407void PeerConnection::UpdateClosingRtpDataChannels(
4408 const std::vector<std::string>& active_channels,
4409 bool is_local_update) {
4410 auto it = rtp_data_channels_.begin();
4411 while (it != rtp_data_channels_.end()) {
4412 DataChannel* data_channel = it->second;
4413 if (std::find(active_channels.begin(), active_channels.end(),
4414 data_channel->label()) != active_channels.end()) {
4415 ++it;
4416 continue;
4417 }
4418
4419 if (is_local_update) {
4420 data_channel->SetSendSsrc(0);
4421 } else {
4422 data_channel->RemotePeerRequestClose();
4423 }
4424
4425 if (data_channel->state() == DataChannel::kClosed) {
4426 rtp_data_channels_.erase(it);
4427 it = rtp_data_channels_.begin();
4428 } else {
4429 ++it;
4430 }
4431 }
4432}
4433
4434void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4435 uint32_t remote_ssrc) {
4436 rtc::scoped_refptr<DataChannel> channel(
4437 InternalCreateDataChannel(label, nullptr));
4438 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004439 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004440 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004441 return;
4442 }
4443 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004444 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4445 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004446 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004447}
4448
4449rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4450 const std::string& label,
4451 const InternalDataChannelInit* config) {
4452 if (IsClosed()) {
4453 return nullptr;
4454 }
Steve Anton75737c02017-11-06 10:37:17 -08004455 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004456 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004457 << "InternalCreateDataChannel: Data is not supported in this call.";
4458 return nullptr;
4459 }
4460 InternalDataChannelInit new_config =
4461 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004462 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004463 if (new_config.id < 0) {
4464 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004465 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004466 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004467 RTC_LOG(LS_ERROR)
4468 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004469 return nullptr;
4470 }
4471 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004472 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004473 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004474 return nullptr;
4475 }
4476 }
4477
Steve Anton75737c02017-11-06 10:37:17 -08004478 rtc::scoped_refptr<DataChannel> channel(
4479 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004480 if (!channel) {
4481 sid_allocator_.ReleaseSid(new_config.id);
4482 return nullptr;
4483 }
4484
4485 if (channel->data_channel_type() == cricket::DCT_RTP) {
4486 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004487 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4488 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004489 return nullptr;
4490 }
4491 rtp_data_channels_[channel->label()] = channel;
4492 } else {
4493 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4494 sctp_data_channels_.push_back(channel);
4495 channel->SignalClosed.connect(this,
4496 &PeerConnection::OnSctpDataChannelClosed);
4497 }
4498
Steve Anton2d8609c2018-01-23 16:38:46 -08004499 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004500 return channel;
4501}
4502
4503bool PeerConnection::HasDataChannels() const {
4504 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4505}
4506
4507void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4508 for (const auto& channel : sctp_data_channels_) {
4509 if (channel->id() < 0) {
4510 int sid;
4511 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004512 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004513 continue;
4514 }
4515 channel->SetSctpSid(sid);
4516 }
4517 }
4518}
4519
4520void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004521 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004522 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4523 ++it) {
4524 if (it->get() == channel) {
4525 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004526 // After the closing procedure is done, it's safe to use this ID for
4527 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004528 sid_allocator_.ReleaseSid(channel->id());
4529 }
deadbeefbd292462015-12-14 18:15:29 -08004530 // Since this method is triggered by a signal from the DataChannel,
4531 // we can't free it directly here; we need to free it asynchronously.
4532 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004533 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004534 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4535 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004536 return;
4537 }
4538 }
4539}
4540
deadbeefab9b2d12015-10-14 11:33:11 -07004541void PeerConnection::OnDataChannelDestroyed() {
4542 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4543 // DataChannel may callback to us and try to modify the list.
4544 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4545 temp_rtp_dcs.swap(rtp_data_channels_);
4546 for (const auto& kv : temp_rtp_dcs) {
4547 kv.second->OnTransportChannelDestroyed();
4548 }
4549
4550 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4551 temp_sctp_dcs.swap(sctp_data_channels_);
4552 for (const auto& channel : temp_sctp_dcs) {
4553 channel->OnTransportChannelDestroyed();
4554 }
4555}
4556
4557void PeerConnection::OnDataChannelOpenMessage(
4558 const std::string& label,
4559 const InternalDataChannelInit& config) {
4560 rtc::scoped_refptr<DataChannel> channel(
4561 InternalCreateDataChannel(label, &config));
4562 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004563 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004564 return;
4565 }
4566
deadbeefa601f5c2016-06-06 14:27:39 -07004567 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4568 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004569 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004570 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004571}
4572
Steve Anton4171afb2017-11-20 10:20:22 -08004573rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4574PeerConnection::GetAudioTransceiver() const {
4575 // This method only works with Plan B SDP, where there is a single
4576 // audio/video transceiver.
4577 RTC_DCHECK(!IsUnifiedPlan());
4578 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004579 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004580 return transceiver;
4581 }
4582 }
4583 RTC_NOTREACHED();
4584 return nullptr;
4585}
4586
4587rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4588PeerConnection::GetVideoTransceiver() const {
4589 // This method only works with Plan B SDP, where there is a single
4590 // audio/video transceiver.
4591 RTC_DCHECK(!IsUnifiedPlan());
4592 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004593 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004594 return transceiver;
4595 }
4596 }
4597 RTC_NOTREACHED();
4598 return nullptr;
4599}
4600
4601// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4602// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004603bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004604 switch (type) {
4605 case cricket::MEDIA_TYPE_AUDIO:
4606 return !GetAudioTransceiver()->internal()->senders().empty();
4607 case cricket::MEDIA_TYPE_VIDEO:
4608 return !GetVideoTransceiver()->internal()->senders().empty();
4609 case cricket::MEDIA_TYPE_DATA:
4610 return false;
4611 }
4612 RTC_NOTREACHED();
4613 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004614}
4615
Steve Anton4171afb2017-11-20 10:20:22 -08004616rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4617PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4618 for (auto transceiver : transceivers_) {
4619 for (auto sender : transceiver->internal()->senders()) {
4620 if (sender->track() == track) {
4621 return sender;
4622 }
4623 }
4624 }
4625 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004626}
4627
Steve Anton4171afb2017-11-20 10:20:22 -08004628rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4629PeerConnection::FindSenderById(const std::string& sender_id) const {
4630 for (auto transceiver : transceivers_) {
4631 for (auto sender : transceiver->internal()->senders()) {
4632 if (sender->id() == sender_id) {
4633 return sender;
4634 }
4635 }
4636 }
4637 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004638}
4639
Steve Anton4171afb2017-11-20 10:20:22 -08004640rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4641PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4642 for (auto transceiver : transceivers_) {
4643 for (auto receiver : transceiver->internal()->receivers()) {
4644 if (receiver->id() == receiver_id) {
4645 return receiver;
4646 }
4647 }
4648 }
4649 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004650}
4651
Steve Anton4171afb2017-11-20 10:20:22 -08004652std::vector<PeerConnection::RtpSenderInfo>*
4653PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4654 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4655 media_type == cricket::MEDIA_TYPE_VIDEO);
4656 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4657 ? &remote_audio_sender_infos_
4658 : &remote_video_sender_infos_;
4659}
4660
4661std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004662 cricket::MediaType media_type) {
4663 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4664 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004665 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4666 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004667}
4668
Steve Anton4171afb2017-11-20 10:20:22 -08004669const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4670 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004671 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004672 const std::string sender_id) const {
4673 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004674 if (sender_info.stream_id == stream_id &&
4675 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004676 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004677 }
4678 }
4679 return nullptr;
4680}
4681
4682DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4683 for (const auto& channel : sctp_data_channels_) {
4684 if (channel->id() == sid) {
4685 return channel;
4686 }
4687 }
4688 return nullptr;
4689}
4690
deadbeef91dd5672016-05-18 16:55:30 -07004691bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004692 const cricket::ServerAddresses& stun_servers,
4693 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004694 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004695 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004696 // To handle both internal and externally created port allocator, we will
4697 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004698 port_allocator_flags_ = port_allocator_->flags();
4699 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4700 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4701 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004702 // If the disable-IPv6 flag was specified, we'll not override it
4703 // by experiment.
4704 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004705 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004706 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4707 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004708 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004709 }
4710
zhihuangb09b3f92017-03-07 14:40:51 -08004711 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004712 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004713 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004714 }
4715
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004716 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004717 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004718 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004719 }
4720
honghaiz60347052016-05-31 18:29:12 -07004721 if (configuration.candidate_network_policy ==
4722 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004723 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004724 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004725 }
4726
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004727 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004728 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004729 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4730 }
4731
Qingsi Wanga2d60672018-04-11 16:57:45 -07004732 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004733 // No step delay is used while allocating ports.
4734 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4735 port_allocator_->set_candidate_filter(
4736 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004737 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004738
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004739 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004740 for (auto& turn_server : turn_servers_copy) {
4741 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004742 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004743 // Call this last since it may create pooled allocator sessions using the
4744 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004745 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004746 stun_servers, std::move(turn_servers_copy),
4747 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4748 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004749 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004750 return true;
4751}
4752
deadbeef91dd5672016-05-18 16:55:30 -07004753bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004754 const cricket::ServerAddresses& stun_servers,
4755 const std::vector<cricket::RelayServerConfig>& turn_servers,
4756 IceTransportsType type,
4757 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004758 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004759 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004760 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004761 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004762 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004763 // According to JSEP, after setLocalDescription, changing the candidate pool
4764 // size is not allowed, and changing the set of ICE servers will not result
4765 // in new candidates being gathered.
4766 if (local_description()) {
4767 port_allocator_->FreezeCandidatePool();
4768 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004769 // Add the custom tls turn servers if they exist.
4770 auto turn_servers_copy = turn_servers;
4771 for (auto& turn_server : turn_servers_copy) {
4772 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4773 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004774 // Call this last since it may create pooled allocator sessions using the
4775 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004776 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004777 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4778 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004779}
4780
Steve Antonba818672017-11-06 10:21:57 -08004781cricket::ChannelManager* PeerConnection::channel_manager() const {
4782 return factory_->channel_manager();
4783}
4784
Elad Alon99c3fe52017-10-13 16:29:40 +02004785bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004786 std::unique_ptr<RtcEventLogOutput> output,
4787 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004788 if (!event_log_) {
4789 return false;
4790 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004791 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004792}
4793
4794void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004795 if (event_log_) {
4796 event_log_->StopLogging();
4797 }
ivoc14d5dbe2016-07-04 07:06:55 -07004798}
nisseeaabdf62017-05-05 02:23:02 -07004799
Steve Anton75737c02017-11-06 10:37:17 -08004800cricket::BaseChannel* PeerConnection::GetChannel(
4801 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004802 for (auto transceiver : transceivers_) {
4803 cricket::BaseChannel* channel = transceiver->internal()->channel();
4804 if (channel && channel->content_name() == content_name) {
4805 return channel;
4806 }
Steve Anton75737c02017-11-06 10:37:17 -08004807 }
4808 if (rtp_data_channel() &&
4809 rtp_data_channel()->content_name() == content_name) {
4810 return rtp_data_channel();
4811 }
4812 return nullptr;
4813}
4814
4815bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4816 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004817 RTC_LOG(LS_INFO)
4818 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004819 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004820 return false;
4821 }
4822 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004823 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004824 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004825 return false;
4826 }
4827
Zhi Huange830e682018-03-30 10:48:35 -07004828 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4829 if (dtls_role) {
4830 *role = *dtls_role;
4831 return true;
4832 }
4833 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004834}
4835
4836bool PeerConnection::GetSslRole(const std::string& content_name,
4837 rtc::SSLRole* role) {
4838 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004839 RTC_LOG(LS_INFO)
4840 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004841 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004842 return false;
4843 }
4844
Zhi Huange830e682018-03-30 10:48:35 -07004845 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4846 if (dtls_role) {
4847 *role = *dtls_role;
4848 return true;
4849 }
4850 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004851}
4852
Steve Antonf8470812017-12-04 10:46:21 -08004853void PeerConnection::SetSessionError(SessionError error,
4854 const std::string& error_desc) {
4855 RTC_DCHECK_RUN_ON(signaling_thread());
4856 if (error != session_error_) {
4857 session_error_ = error;
4858 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004859 }
4860}
4861
Zhi Huange830e682018-03-30 10:48:35 -07004862RTCError PeerConnection::UpdateSessionState(
4863 SdpType type,
4864 cricket::ContentSource source,
4865 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004866 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004867
4868 // If there's already a pending error then no state transition should happen.
4869 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004870 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004871
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004872 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004873 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004874 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004875 }
4876
4877 // Update the signaling state according to the specified state machine (see
4878 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004879 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004880 ChangeSignalingState(source == cricket::CS_LOCAL
4881 ? PeerConnectionInterface::kHaveLocalOffer
4882 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004883 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004884 ChangeSignalingState(source == cricket::CS_LOCAL
4885 ? PeerConnectionInterface::kHaveLocalPrAnswer
4886 : PeerConnectionInterface::kHaveRemotePrAnswer);
4887 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004888 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004889 ChangeSignalingState(PeerConnectionInterface::kStable);
4890 }
4891
4892 // Update internal objects according to the session description's media
4893 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004894 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004895 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004896 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004897 }
4898
Steve Anton8a006912017-12-04 15:25:56 -08004899 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004900}
4901
Steve Anton8a006912017-12-04 15:25:56 -08004902RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004903 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004904 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004905 const SessionDescriptionInterface* sdesc =
4906 (source == cricket::CS_LOCAL ? local_description()
4907 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004908 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004909
4910 // Push down the new SDP media section for each audio/video transceiver.
4911 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004912 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004913 FindMediaSectionForTransceiver(transceiver, sdesc);
4914 cricket::BaseChannel* channel = transceiver->internal()->channel();
4915 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004916 continue;
4917 }
4918 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004919 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004920 if (!content_desc) {
4921 continue;
4922 }
4923 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004924 bool success = (source == cricket::CS_LOCAL)
4925 ? channel->SetLocalContent(content_desc, type, &error)
4926 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004927 if (!success) {
4928 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4929 }
4930 }
4931
4932 // If using the RtpDataChannel, push down the new SDP section for it too.
4933 if (rtp_data_channel_) {
4934 const ContentInfo* data_content =
4935 cricket::GetFirstDataContent(sdesc->description());
4936 if (data_content && !data_content->rejected) {
4937 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004938 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004939 if (data_desc) {
4940 std::string error;
4941 bool success =
4942 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004943 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004944 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004945 if (!success) {
4946 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4947 std::move(error));
4948 }
Steve Anton75737c02017-11-06 10:37:17 -08004949 }
4950 }
4951 }
Steve Antoned10bd92017-12-05 10:52:59 -08004952
Steve Anton75737c02017-11-06 10:37:17 -08004953 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4954 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4955 if (sctp_transport_ && local_description() && remote_description() &&
4956 cricket::GetFirstDataContent(local_description()->description()) &&
4957 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004958 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004959 RTC_FROM_HERE,
4960 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004961 if (!success) {
4962 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4963 "Failed to push down SCTP parameters.");
4964 }
Steve Anton75737c02017-11-06 10:37:17 -08004965 }
Steve Antoned10bd92017-12-05 10:52:59 -08004966
Steve Anton8a006912017-12-04 15:25:56 -08004967 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004968}
4969
4970bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4971 RTC_DCHECK(network_thread()->IsCurrent());
4972 RTC_DCHECK(local_description());
4973 RTC_DCHECK(remote_description());
4974 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4975 // When we support "max-message-size", that would also be pushed down here.
4976 return sctp_transport_->Start(
4977 GetSctpPort(local_description()->description()),
4978 GetSctpPort(remote_description()->description()));
4979}
4980
Steve Anton8a006912017-12-04 15:25:56 -08004981RTCError PeerConnection::PushdownTransportDescription(
4982 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004983 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004984 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004985
Zhi Huange830e682018-03-30 10:48:35 -07004986 if (source == cricket::CS_LOCAL) {
4987 const SessionDescriptionInterface* sdesc = local_description();
4988 RTC_DCHECK(sdesc);
4989 return transport_controller_->SetLocalDescription(type,
4990 sdesc->description());
4991 } else {
4992 const SessionDescriptionInterface* sdesc = remote_description();
4993 RTC_DCHECK(sdesc);
4994 return transport_controller_->SetRemoteDescription(type,
4995 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004996 }
Steve Anton75737c02017-11-06 10:37:17 -08004997}
4998
4999bool PeerConnection::GetTransportDescription(
5000 const SessionDescription* description,
5001 const std::string& content_name,
5002 cricket::TransportDescription* tdesc) {
5003 if (!description || !tdesc) {
5004 return false;
5005 }
5006 const TransportInfo* transport_info =
5007 description->GetTransportInfoByName(content_name);
5008 if (!transport_info) {
5009 return false;
5010 }
5011 *tdesc = transport_info->description;
5012 return true;
5013}
5014
Steve Anton75737c02017-11-06 10:37:17 -08005015cricket::IceConfig PeerConnection::ParseIceConfig(
5016 const PeerConnectionInterface::RTCConfiguration& config) const {
5017 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005018 switch (config.continual_gathering_policy) {
5019 case PeerConnectionInterface::GATHER_ONCE:
5020 gathering_policy = cricket::GATHER_ONCE;
5021 break;
5022 case PeerConnectionInterface::GATHER_CONTINUALLY:
5023 gathering_policy = cricket::GATHER_CONTINUALLY;
5024 break;
5025 default:
5026 RTC_NOTREACHED();
5027 gathering_policy = cricket::GATHER_ONCE;
5028 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005029
Steve Anton75737c02017-11-06 10:37:17 -08005030 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005031 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5032 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005033 ice_config.prioritize_most_likely_candidate_pairs =
5034 config.prioritize_most_likely_ice_candidate_pairs;
5035 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005036 RTCConfigurationToIceConfigOptionalInt(
5037 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005038 ice_config.continual_gathering_policy = gathering_policy;
5039 ice_config.presume_writable_when_fully_relayed =
5040 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005041 ice_config.ice_check_interval_strong_connectivity =
5042 config.ice_check_interval_strong_connectivity;
5043 ice_config.ice_check_interval_weak_connectivity =
5044 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005045 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005046 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005047 ice_config.regather_all_networks_interval_range =
5048 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005049 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005050 return ice_config;
5051}
5052
Steve Anton75737c02017-11-06 10:37:17 -08005053bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5054 std::string* track_id) {
5055 if (!local_description()) {
5056 return false;
5057 }
5058 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5059 track_id);
5060}
5061
5062bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5063 std::string* track_id) {
5064 if (!remote_description()) {
5065 return false;
5066 }
5067 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5068 track_id);
5069}
5070
5071bool PeerConnection::SendData(const cricket::SendDataParams& params,
5072 const rtc::CopyOnWriteBuffer& payload,
5073 cricket::SendDataResult* result) {
5074 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005075 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005076 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005077 return false;
5078 }
5079 return rtp_data_channel_
5080 ? rtp_data_channel_->SendData(params, payload, result)
5081 : network_thread()->Invoke<bool>(
5082 RTC_FROM_HERE,
5083 Bind(&cricket::SctpTransportInternal::SendData,
5084 sctp_transport_.get(), params, payload, result));
5085}
5086
5087bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5088 if (!rtp_data_channel_ && !sctp_transport_) {
5089 // Don't log an error here, because DataChannels are expected to call
5090 // ConnectDataChannel in this state. It's the only way to initially tell
5091 // whether or not the underlying transport is ready.
5092 return false;
5093 }
5094 if (rtp_data_channel_) {
5095 rtp_data_channel_->SignalReadyToSendData.connect(
5096 webrtc_data_channel, &DataChannel::OnChannelReady);
5097 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5098 &DataChannel::OnDataReceived);
5099 } else {
5100 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5101 &DataChannel::OnChannelReady);
5102 SignalSctpDataReceived.connect(webrtc_data_channel,
5103 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005104 SignalSctpClosingProcedureStartedRemotely.connect(
5105 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5106 SignalSctpClosingProcedureComplete.connect(
5107 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005108 }
5109 return true;
5110}
5111
5112void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5113 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005114 RTC_LOG(LS_ERROR)
5115 << "DisconnectDataChannel called when rtp_data_channel_ and "
5116 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005117 return;
5118 }
5119 if (rtp_data_channel_) {
5120 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5121 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5122 } else {
5123 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5124 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005125 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5126 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005127 }
5128}
5129
5130void PeerConnection::AddSctpDataStream(int sid) {
5131 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005132 RTC_LOG(LS_ERROR)
5133 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005134 return;
5135 }
5136 network_thread()->Invoke<void>(
5137 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5138 sctp_transport_.get(), sid));
5139}
5140
5141void PeerConnection::RemoveSctpDataStream(int sid) {
5142 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005143 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005144 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005145 return;
5146 }
5147 network_thread()->Invoke<void>(
5148 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5149 sctp_transport_.get(), sid));
5150}
5151
5152bool PeerConnection::ReadyToSendData() const {
5153 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5154 sctp_ready_to_send_data_;
5155}
5156
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005157absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005158 if (sctp_mid_ && transport_controller_) {
5159 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5160 if (dtls_transport) {
5161 return dtls_transport->transport_name();
5162 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005163 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005164 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005165 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005166}
5167
Qingsi Wang72a43a12018-02-20 16:03:18 -08005168cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5169 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005170 network_thread()->Invoke<void>(
5171 RTC_FROM_HERE,
5172 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5173 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005174 return candidate_states_list;
5175}
5176
Steve Anton5dfde182018-02-06 10:34:40 -08005177std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5178 const {
5179 std::map<std::string, std::string> transport_names_by_mid;
5180 for (auto transceiver : transceivers_) {
5181 cricket::BaseChannel* channel = transceiver->internal()->channel();
5182 if (channel) {
5183 transport_names_by_mid[channel->content_name()] =
5184 channel->transport_name();
5185 }
Steve Anton75737c02017-11-06 10:37:17 -08005186 }
Steve Anton5dfde182018-02-06 10:34:40 -08005187 if (rtp_data_channel_) {
5188 transport_names_by_mid[rtp_data_channel_->content_name()] =
5189 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005190 }
5191 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005192 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005193 RTC_DCHECK(transport_name);
5194 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005195 }
Steve Anton5dfde182018-02-06 10:34:40 -08005196 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005197}
5198
Steve Anton5dfde182018-02-06 10:34:40 -08005199std::map<std::string, cricket::TransportStats>
5200PeerConnection::GetTransportStatsByNames(
5201 const std::set<std::string>& transport_names) {
5202 if (!network_thread()->IsCurrent()) {
5203 return network_thread()
5204 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5205 RTC_FROM_HERE,
5206 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005207 }
Steve Anton5dfde182018-02-06 10:34:40 -08005208 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5209 for (const std::string& transport_name : transport_names) {
5210 cricket::TransportStats transport_stats;
5211 bool success =
5212 transport_controller_->GetStats(transport_name, &transport_stats);
5213 if (success) {
5214 transport_stats_by_name[transport_name] = std::move(transport_stats);
5215 } else {
5216 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5217 << transport_name;
5218 }
5219 }
5220 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005221}
5222
5223bool PeerConnection::GetLocalCertificate(
5224 const std::string& transport_name,
5225 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005226 if (!certificate) {
5227 return false;
5228 }
5229 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5230 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005231}
5232
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005233std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005234 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005235 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005236}
5237
5238cricket::DataChannelType PeerConnection::data_channel_type() const {
5239 return data_channel_type_;
5240}
5241
5242bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5243 return pending_ice_restarts_.find(content_name) !=
5244 pending_ice_restarts_.end();
5245}
5246
Steve Anton75737c02017-11-06 10:37:17 -08005247bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5248 return transport_controller_->NeedsIceRestart(content_name);
5249}
5250
5251void PeerConnection::OnCertificateReady(
5252 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5253 transport_controller_->SetLocalCertificate(certificate);
5254}
5255
5256void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005257 SetSessionError(SessionError::kTransport,
5258 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005259}
5260
5261void PeerConnection::OnTransportControllerConnectionState(
5262 cricket::IceConnectionState state) {
5263 switch (state) {
5264 case cricket::kIceConnectionConnecting:
5265 // If the current state is Connected or Completed, then there were
5266 // writable channels but now there are not, so the next state must
5267 // be Disconnected.
5268 // kIceConnectionConnecting is currently used as the default,
5269 // un-connected state by the TransportController, so its only use is
5270 // detecting disconnections.
5271 if (ice_connection_state_ ==
5272 PeerConnectionInterface::kIceConnectionConnected ||
5273 ice_connection_state_ ==
5274 PeerConnectionInterface::kIceConnectionCompleted) {
5275 SetIceConnectionState(
5276 PeerConnectionInterface::kIceConnectionDisconnected);
5277 }
5278 break;
5279 case cricket::kIceConnectionFailed:
5280 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5281 break;
5282 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005283 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005284 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005285 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005286 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005287 break;
5288 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005289 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005290 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005291 if (ice_connection_state_ !=
5292 PeerConnectionInterface::kIceConnectionConnected) {
5293 // If jumping directly from "checking" to "connected",
5294 // signal "connected" first.
5295 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5296 }
5297 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005298 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005299 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005300 break;
5301 default:
5302 RTC_NOTREACHED();
5303 }
5304}
5305
5306void PeerConnection::OnTransportControllerCandidatesGathered(
5307 const std::string& transport_name,
5308 const cricket::Candidates& candidates) {
5309 RTC_DCHECK(signaling_thread()->IsCurrent());
5310 int sdp_mline_index;
5311 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005312 RTC_LOG(LS_ERROR)
5313 << "OnTransportControllerCandidatesGathered: content name "
5314 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005315 return;
5316 }
5317
5318 for (cricket::Candidates::const_iterator citer = candidates.begin();
5319 citer != candidates.end(); ++citer) {
5320 // Use transport_name as the candidate media id.
5321 std::unique_ptr<JsepIceCandidate> candidate(
5322 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5323 if (local_description()) {
5324 mutable_local_description()->AddCandidate(candidate.get());
5325 }
5326 OnIceCandidate(std::move(candidate));
5327 }
5328}
5329
5330void PeerConnection::OnTransportControllerCandidatesRemoved(
5331 const std::vector<cricket::Candidate>& candidates) {
5332 RTC_DCHECK(signaling_thread()->IsCurrent());
5333 // Sanity check.
5334 for (const cricket::Candidate& candidate : candidates) {
5335 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005336 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005337 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005338 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005339 return;
5340 }
5341 }
5342
5343 if (local_description()) {
5344 mutable_local_description()->RemoveCandidates(candidates);
5345 }
5346 OnIceCandidatesRemoved(candidates);
5347}
5348
5349void PeerConnection::OnTransportControllerDtlsHandshakeError(
5350 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005351 RTC_HISTOGRAM_ENUMERATION(
5352 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5353 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005354}
5355
Steve Antoned10bd92017-12-05 10:52:59 -08005356void PeerConnection::EnableSending() {
5357 for (auto transceiver : transceivers_) {
5358 cricket::BaseChannel* channel = transceiver->internal()->channel();
5359 if (channel && !channel->enabled()) {
5360 channel->Enable(true);
5361 }
Steve Anton75737c02017-11-06 10:37:17 -08005362 }
5363
Steve Anton4171afb2017-11-20 10:20:22 -08005364 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005365 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005366 }
Steve Anton75737c02017-11-06 10:37:17 -08005367}
5368
5369// Returns the media index for a local ice candidate given the content name.
5370bool PeerConnection::GetLocalCandidateMediaIndex(
5371 const std::string& content_name,
5372 int* sdp_mline_index) {
5373 if (!local_description() || !sdp_mline_index) {
5374 return false;
5375 }
5376
5377 bool content_found = false;
5378 const ContentInfos& contents = local_description()->description()->contents();
5379 for (size_t index = 0; index < contents.size(); ++index) {
5380 if (contents[index].name == content_name) {
5381 *sdp_mline_index = static_cast<int>(index);
5382 content_found = true;
5383 break;
5384 }
5385 }
5386 return content_found;
5387}
5388
5389bool PeerConnection::UseCandidatesInSessionDescription(
5390 const SessionDescriptionInterface* remote_desc) {
5391 if (!remote_desc) {
5392 return true;
5393 }
5394 bool ret = true;
5395
5396 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5397 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5398 for (size_t n = 0; n < candidates->count(); ++n) {
5399 const IceCandidateInterface* candidate = candidates->at(n);
5400 bool valid = false;
5401 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5402 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005403 RTC_LOG(LS_INFO)
5404 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005405 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005406 }
5407 continue;
5408 }
5409 ret = UseCandidate(candidate);
5410 if (!ret) {
5411 break;
5412 }
5413 }
5414 }
5415 return ret;
5416}
5417
5418bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5419 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5420 size_t remote_content_size =
5421 remote_description()->description()->contents().size();
5422 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005423 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005424 return false;
5425 }
5426
5427 cricket::ContentInfo content =
5428 remote_description()->description()->contents()[mediacontent_index];
5429 std::vector<cricket::Candidate> candidates;
5430 candidates.push_back(candidate->candidate());
5431 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005432 RTCError error =
5433 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005434 if (error.ok()) {
5435 // Candidates successfully submitted for checking.
5436 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5437 ice_connection_state_ ==
5438 PeerConnectionInterface::kIceConnectionDisconnected) {
5439 // If state is New, then the session has just gotten its first remote ICE
5440 // candidates, so go to Checking.
5441 // If state is Disconnected, the session is re-using old candidates or
5442 // receiving additional ones, so go to Checking.
5443 // If state is Connected, stay Connected.
5444 // TODO(bemasc): If state is Connected, and the new candidates are for a
5445 // newly added transport, then the state actually _should_ move to
5446 // checking. Add a way to distinguish that case.
5447 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5448 }
5449 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005450 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005451 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005452 }
5453 return true;
5454}
5455
5456void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005457 // Destroy video channel first since it may have a pointer to the
5458 // voice channel.
5459 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005460 if (!video_info || video_info->rejected) {
5461 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005462 }
5463
Steve Anton6fec8802017-12-04 10:37:29 -08005464 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5465 if (!audio_info || audio_info->rejected) {
5466 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005467 }
5468
5469 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5470 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005471 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005472 }
5473}
5474
Steve Antondcc3c022017-12-22 16:02:54 -08005475RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5476 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005477 const cricket::ContentGroup* bundle_group = nullptr;
5478 if (configuration_.bundle_policy ==
5479 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005480 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005481 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005482 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5483 "max-bundle configured but session description "
5484 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005485 }
5486 }
Steve Antondcc3c022017-12-22 16:02:54 -08005487 return std::move(bundle_group);
5488}
5489
5490RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005491 // Creating the media channels. Transports should already have been created
5492 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005493 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005494 if (voice && !voice->rejected &&
5495 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005496 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005497 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005498 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5499 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005500 }
5501 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5502 }
5503
Steve Antondcc3c022017-12-22 16:02:54 -08005504 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005505 if (video && !video->rejected &&
5506 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005507 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005508 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005509 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5510 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005511 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005512 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005513 }
5514
Steve Antondcc3c022017-12-22 16:02:54 -08005515 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005516 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5517 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005518 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005519 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5520 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005521 }
5522 }
5523
Steve Anton8a006912017-12-04 15:25:56 -08005524 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005525}
5526
Steve Anton4171afb2017-11-20 10:20:22 -08005527// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005528cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005529 const std::string& mid) {
Oleh Prypin9accc9f2018-10-16 18:49:31 +00005530 RtpTransportInternal* rtp_transport =
5531 transport_controller_->GetRtpTransport(mid);
5532 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005533 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Oleh Prypin9accc9f2018-10-16 18:49:31 +00005534 call_.get(), configuration_.media_config, rtp_transport,
Zhi Huange830e682018-03-30 10:48:35 -07005535 signaling_thread(), mid, SrtpRequired(),
5536 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005537 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005538 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005539 }
Steve Anton75737c02017-11-06 10:37:17 -08005540 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5541 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005542 voice_channel->SignalSentPacket.connect(this,
5543 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005544 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005545
Steve Antoneda6ccd2017-12-04 10:21:55 -08005546 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005547}
5548
Steve Anton4171afb2017-11-20 10:20:22 -08005549// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005550cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005551 const std::string& mid) {
Oleh Prypin9accc9f2018-10-16 18:49:31 +00005552 RtpTransportInternal* rtp_transport =
5553 transport_controller_->GetRtpTransport(mid);
5554 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005555 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005556 call_.get(), configuration_.media_config, rtp_transport,
5557 signaling_thread(), mid, SrtpRequired(),
5558 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005559 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005560 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005561 }
Steve Anton75737c02017-11-06 10:37:17 -08005562 video_channel->SignalDtlsSrtpSetupFailure.connect(
5563 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005564 video_channel->SignalSentPacket.connect(this,
5565 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005566 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005567
Steve Antoneda6ccd2017-12-04 10:21:55 -08005568 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005569}
5570
Zhi Huange830e682018-03-30 10:48:35 -07005571bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005572 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5573 if (sctp) {
5574 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005575 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005576 << "Trying to create SCTP transport, but didn't compile with "
5577 "SCTP support (HAVE_SCTP)";
5578 return false;
5579 }
5580 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005581 RTC_FROM_HERE,
5582 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005583 return false;
5584 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005585 for (const auto& channel : sctp_data_channels_) {
5586 channel->OnTransportChannelCreated();
5587 }
Steve Anton75737c02017-11-06 10:37:17 -08005588 } else {
Oleh Prypin9accc9f2018-10-16 18:49:31 +00005589 RtpTransportInternal* rtp_transport =
5590 transport_controller_->GetRtpTransport(mid);
5591 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005592 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005593 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5594 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005595 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005596 return false;
5597 }
Steve Anton75737c02017-11-06 10:37:17 -08005598 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5599 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5600 rtp_data_channel_->SignalSentPacket.connect(
5601 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005602 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005603 }
5604
Steve Anton75737c02017-11-06 10:37:17 -08005605 return true;
5606}
5607
5608Call::Stats PeerConnection::GetCallStats() {
5609 if (!worker_thread()->IsCurrent()) {
5610 return worker_thread()->Invoke<Call::Stats>(
5611 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5612 }
5613 if (call_) {
5614 return call_->GetStats();
5615 } else {
5616 return Call::Stats();
5617 }
5618}
5619
Zhi Huange830e682018-03-30 10:48:35 -07005620bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005621 RTC_DCHECK(network_thread()->IsCurrent());
5622 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005623 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005624 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005625 RTC_DCHECK(dtls_transport);
5626 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005627 RTC_DCHECK(sctp_transport_);
5628 sctp_invoker_.reset(new rtc::AsyncInvoker());
5629 sctp_transport_->SignalReadyToSendData.connect(
5630 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5631 sctp_transport_->SignalDataReceived.connect(
5632 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005633 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5634 // another thread. Would be nice if there was a helper class similar to
5635 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5636 // code.
5637 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5638 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5639 sctp_transport_->SignalClosingProcedureComplete.connect(
5640 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005641 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005642 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005643 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005644}
5645
5646void PeerConnection::DestroySctpTransport_n() {
5647 RTC_DCHECK(network_thread()->IsCurrent());
5648 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005649 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005650 sctp_invoker_.reset(nullptr);
5651 sctp_ready_to_send_data_ = false;
5652}
5653
5654void PeerConnection::OnSctpTransportReadyToSendData_n() {
5655 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5656 RTC_DCHECK(network_thread()->IsCurrent());
5657 // Note: Cannot use rtc::Bind here because it will grab a reference to
5658 // PeerConnection and potentially cause PeerConnection to live longer than
5659 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5660 // be destroyed before PeerConnection is destroyed, and at that point all
5661 // pending tasks will be cleared.
5662 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5663 OnSctpTransportReadyToSendData_s(true);
5664 });
5665}
5666
5667void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5668 RTC_DCHECK(signaling_thread()->IsCurrent());
5669 sctp_ready_to_send_data_ = ready;
5670 SignalSctpReadyToSendData(ready);
5671}
5672
5673void PeerConnection::OnSctpTransportDataReceived_n(
5674 const cricket::ReceiveDataParams& params,
5675 const rtc::CopyOnWriteBuffer& payload) {
5676 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5677 RTC_DCHECK(network_thread()->IsCurrent());
5678 // Note: Cannot use rtc::Bind here because it will grab a reference to
5679 // PeerConnection and potentially cause PeerConnection to live longer than
5680 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5681 // be destroyed before PeerConnection is destroyed, and at that point all
5682 // pending tasks will be cleared.
5683 sctp_invoker_->AsyncInvoke<void>(
5684 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5685 OnSctpTransportDataReceived_s(params, payload);
5686 });
5687}
5688
5689void PeerConnection::OnSctpTransportDataReceived_s(
5690 const cricket::ReceiveDataParams& params,
5691 const rtc::CopyOnWriteBuffer& payload) {
5692 RTC_DCHECK(signaling_thread()->IsCurrent());
5693 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5694 // Received OPEN message; parse and signal that a new data channel should
5695 // be created.
5696 std::string label;
5697 InternalDataChannelInit config;
5698 config.id = params.ssrc;
5699 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005700 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5701 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005702 return;
5703 }
5704 config.open_handshake_role = InternalDataChannelInit::kAcker;
5705 OnDataChannelOpenMessage(label, config);
5706 } else {
5707 // Otherwise just forward the signal.
5708 SignalSctpDataReceived(params, payload);
5709 }
5710}
5711
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005712void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005713 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5714 RTC_DCHECK(network_thread()->IsCurrent());
5715 sctp_invoker_->AsyncInvoke<void>(
5716 RTC_FROM_HERE, signaling_thread(),
5717 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005718 &SignalSctpClosingProcedureStartedRemotely, sid));
5719}
5720
5721void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5722 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5723 RTC_DCHECK(network_thread()->IsCurrent());
5724 sctp_invoker_->AsyncInvoke<void>(
5725 RTC_FROM_HERE, signaling_thread(),
5726 rtc::Bind(&sigslot::signal1<int>::operator(),
5727 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005728}
5729
5730// Returns false if bundle is enabled and rtcp_mux is disabled.
5731bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5732 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5733 if (!bundle_enabled)
5734 return true;
5735
5736 const cricket::ContentGroup* bundle_group =
5737 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5738 RTC_DCHECK(bundle_group != NULL);
5739
5740 const cricket::ContentInfos& contents = desc->contents();
5741 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5742 citer != contents.end(); ++citer) {
5743 const cricket::ContentInfo* content = (&*citer);
5744 RTC_DCHECK(content != NULL);
5745 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005746 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005747 if (!HasRtcpMuxEnabled(content))
5748 return false;
5749 }
5750 }
5751 // RTCP-MUX is enabled in all the contents.
5752 return true;
5753}
5754
5755bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005756 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005757}
5758
Steve Anton8a006912017-12-04 15:25:56 -08005759RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005760 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005761 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005762 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005763 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005764 }
5765
5766 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005767 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005768 }
5769
Steve Anton3828c062017-12-06 10:34:51 -08005770 SdpType type = sdesc->GetType();
5771 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5772 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005773 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005774 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005775 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005776 }
5777
5778 // Verify crypto settings.
5779 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005780 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5781 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005782 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005783 if (!crypto_error.ok()) {
5784 return crypto_error;
5785 }
Steve Anton75737c02017-11-06 10:37:17 -08005786 }
5787
5788 // Verify ice-ufrag and ice-pwd.
5789 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005790 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5791 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005792 }
5793
5794 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005795 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5796 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005797 }
5798
5799 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5800 // m-lines that do not rtcp-mux enabled.
5801
5802 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005803 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005804 // With an answer we want to compare the new answer session description with
5805 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005806 const cricket::SessionDescription* offer_desc =
5807 (source == cricket::CS_LOCAL) ? remote_description()->description()
5808 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005809 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5810 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5811 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005812 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5813 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005814 }
5815 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005816 // The re-offers should respect the order of m= sections in current
5817 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005818 // With a re-offer, either the current local or current remote descriptions
5819 // could be the most up to date, so we would like to check against both of
5820 // them if they exist. It could be the case that one of them has a 0 port
5821 // for a media section, but the other does not. This is important to check
5822 // against in the case that we are recycling an m= section.
5823 const cricket::SessionDescription* current_desc = nullptr;
5824 const cricket::SessionDescription* secondary_current_desc = nullptr;
5825 if (local_description()) {
5826 current_desc = local_description()->description();
5827 if (remote_description()) {
5828 secondary_current_desc = remote_description()->description();
5829 }
5830 } else if (remote_description()) {
5831 current_desc = remote_description()->description();
5832 }
Steve Anton75737c02017-11-06 10:37:17 -08005833 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005834 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5835 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005836 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5837 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005838 }
5839 }
5840
Steve Antonba42e992018-04-09 14:10:01 -07005841 if (IsUnifiedPlan()) {
5842 // Ensure that each audio and video media section has at most one
5843 // "StreamParams". This will return an error if receiving a session
5844 // description from a "Plan B" endpoint which adds multiple tracks of the
5845 // same type. With Unified Plan, there can only be at most one track per
5846 // media section.
5847 for (const ContentInfo& content : sdesc->description()->contents()) {
5848 const MediaContentDescription& desc = *content.description;
5849 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5850 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5851 desc.streams().size() > 1u) {
5852 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5853 "Media section has more than one track specified "
5854 "with a=ssrc lines which is not supported with "
5855 "Unified Plan.");
5856 }
5857 }
5858 }
5859
Steve Anton8a006912017-12-04 15:25:56 -08005860 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005861}
5862
Steve Anton3828c062017-12-06 10:34:51 -08005863bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005864 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005865 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005866 return (state == PeerConnectionInterface::kStable) ||
5867 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005868 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005869 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005870 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5871 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5872 }
5873}
5874
Steve Anton3828c062017-12-06 10:34:51 -08005875bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005876 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005877 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005878 return (state == PeerConnectionInterface::kStable) ||
5879 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005880 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005881 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005882 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5883 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5884 }
5885}
5886
Steve Antonf8470812017-12-04 10:46:21 -08005887const char* PeerConnection::SessionErrorToString(SessionError error) const {
5888 switch (error) {
5889 case SessionError::kNone:
5890 return "ERROR_NONE";
5891 case SessionError::kContent:
5892 return "ERROR_CONTENT";
5893 case SessionError::kTransport:
5894 return "ERROR_TRANSPORT";
5895 }
5896 RTC_NOTREACHED();
5897 return "";
5898}
5899
Steve Anton75737c02017-11-06 10:37:17 -08005900std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02005901 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08005902 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5903 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02005904 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08005905}
5906
Steve Anton8e20f172018-03-06 10:55:04 -08005907void PeerConnection::ReportSdpFormatReceived(
5908 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005909 int num_audio_mlines = 0;
5910 int num_video_mlines = 0;
5911 int num_audio_tracks = 0;
5912 int num_video_tracks = 0;
5913 for (const ContentInfo& content : remote_offer.description()->contents()) {
5914 cricket::MediaType media_type = content.media_description()->type();
5915 int num_tracks = std::max(
5916 1, static_cast<int>(content.media_description()->streams().size()));
5917 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5918 num_audio_mlines += 1;
5919 num_audio_tracks += num_tracks;
5920 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5921 num_video_mlines += 1;
5922 num_video_tracks += num_tracks;
5923 }
5924 }
5925 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5926 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5927 format = kSdpFormatReceivedComplexUnifiedPlan;
5928 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5929 format = kSdpFormatReceivedComplexPlanB;
5930 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5931 format = kSdpFormatReceivedSimple;
5932 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005933 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5934 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005935}
5936
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005937void PeerConnection::NoteUsageEvent(UsageEvent event) {
5938 RTC_DCHECK_RUN_ON(signaling_thread());
5939 usage_event_accumulator_ |= static_cast<int>(event);
5940}
5941
5942void PeerConnection::ReportUsagePattern() const {
5943 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005944 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5945 usage_event_accumulator_,
5946 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005947 const int bad_bits =
5948 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5949 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5950 const int good_bits =
5951 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5952 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5953 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5954 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5955 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005956 // If called after close(), we can't report, because observer may have
5957 // been deallocated, and therefore pointer is null. Write to log instead.
5958 if (observer_) {
5959 Observer()->OnInterestingUsage(usage_event_accumulator_);
5960 } else {
5961 RTC_LOG(LS_INFO) << "Interesting usage signature "
5962 << usage_event_accumulator_
5963 << " observed after observer shutdown";
5964 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005965 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005966}
5967
Steve Anton0ffaaa22018-02-23 10:31:30 -08005968void PeerConnection::ReportNegotiatedSdpSemantics(
5969 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005970 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005971 switch (answer.description()->msid_signaling()) {
5972 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005973 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005974 break;
5975 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005976 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005977 break;
5978 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005979 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005980 break;
5981 case cricket::kMsidSignalingMediaSection |
5982 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005983 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005984 break;
5985 default:
5986 RTC_NOTREACHED();
5987 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005988 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5989 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005990}
5991
Steve Anton75737c02017-11-06 10:37:17 -08005992// We need to check the local/remote description for the Transport instead of
5993// the session, because a new Transport added during renegotiation may have
5994// them unset while the session has them set from the previous negotiation.
5995// Not doing so may trigger the auto generation of transport description and
5996// mess up DTLS identity information, ICE credential, etc.
5997bool PeerConnection::ReadyToUseRemoteCandidate(
5998 const IceCandidateInterface* candidate,
5999 const SessionDescriptionInterface* remote_desc,
6000 bool* valid) {
6001 *valid = true;
6002
6003 const SessionDescriptionInterface* current_remote_desc =
6004 remote_desc ? remote_desc : remote_description();
6005
6006 if (!current_remote_desc) {
6007 return false;
6008 }
6009
6010 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6011 size_t remote_content_size =
6012 current_remote_desc->description()->contents().size();
6013 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006014 RTC_LOG(LS_ERROR)
6015 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6016 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006017
6018 *valid = false;
6019 return false;
6020 }
6021
6022 cricket::ContentInfo content =
6023 current_remote_desc->description()->contents()[mediacontent_index];
6024
6025 const std::string transport_name = GetTransportName(content.name);
6026 if (transport_name.empty()) {
6027 return false;
6028 }
Zhi Huange830e682018-03-30 10:48:35 -07006029 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006030}
6031
6032bool PeerConnection::SrtpRequired() const {
6033 return dtls_enabled_ ||
6034 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6035}
6036
6037void PeerConnection::OnTransportControllerGatheringState(
6038 cricket::IceGatheringState state) {
6039 RTC_DCHECK(signaling_thread()->IsCurrent());
6040 if (state == cricket::kIceGatheringGathering) {
6041 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6042 } else if (state == cricket::kIceGatheringComplete) {
6043 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6044 }
6045}
6046
6047void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006048 std::map<std::string, std::set<cricket::MediaType>>
6049 media_types_by_transport_name;
6050 for (auto transceiver : transceivers_) {
6051 if (transceiver->internal()->channel()) {
6052 const std::string& transport_name =
6053 transceiver->internal()->channel()->transport_name();
6054 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006055 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006056 }
Steve Anton75737c02017-11-06 10:37:17 -08006057 }
6058 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006059 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6060 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006061 }
Zhi Huange830e682018-03-30 10:48:35 -07006062
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006063 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006064 if (transport_name) {
6065 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006066 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006067 }
Zhi Huange830e682018-03-30 10:48:35 -07006068
Steve Antonc7b964c2018-02-01 14:39:45 -08006069 for (const auto& entry : media_types_by_transport_name) {
6070 const std::string& transport_name = entry.first;
6071 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006072 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006073 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006074 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006075 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006076 }
6077 }
6078}
6079// Walk through the ConnectionInfos to gather best connection usage
6080// for IPv4 and IPv6.
6081void PeerConnection::ReportBestConnectionState(
6082 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006083 for (const cricket::TransportChannelStats& channel_stats :
6084 stats.channel_stats) {
6085 for (const cricket::ConnectionInfo& connection_info :
6086 channel_stats.connection_infos) {
6087 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006088 continue;
6089 }
6090
Steve Antonc7b964c2018-02-01 14:39:45 -08006091 const cricket::Candidate& local = connection_info.local_candidate;
6092 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006093
6094 // Increment the counter for IceCandidatePairType.
6095 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6096 (local.type() == RELAY_PORT_TYPE &&
6097 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006098 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6099 GetIceCandidatePairCounter(local, remote),
6100 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006101 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006102 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6103 GetIceCandidatePairCounter(local, remote),
6104 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006105 } else {
6106 RTC_CHECK(0);
6107 }
Steve Anton75737c02017-11-06 10:37:17 -08006108
6109 // Increment the counter for IP type.
6110 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006111 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6112 kBestConnections_IPv4,
6113 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006114 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006115 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6116 kBestConnections_IPv6,
6117 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006118 } else {
6119 RTC_CHECK(0);
6120 }
6121
6122 return;
6123 }
6124 }
6125}
6126
6127void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006128 const cricket::TransportStats& stats,
6129 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006130 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6131 return;
6132 }
6133
6134 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6135 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6136 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6137 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6138 return;
6139 }
6140
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006141 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6142 for (cricket::MediaType media_type : media_types) {
6143 switch (media_type) {
6144 case cricket::MEDIA_TYPE_AUDIO:
6145 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6146 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6147 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6148 break;
6149 case cricket::MEDIA_TYPE_VIDEO:
6150 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6151 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6152 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6153 break;
6154 case cricket::MEDIA_TYPE_DATA:
6155 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6156 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6157 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6158 break;
6159 default:
6160 RTC_NOTREACHED();
6161 continue;
6162 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006163 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006164 }
6165
6166 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6167 for (cricket::MediaType media_type : media_types) {
6168 switch (media_type) {
6169 case cricket::MEDIA_TYPE_AUDIO:
6170 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6171 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6172 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6173 break;
6174 case cricket::MEDIA_TYPE_VIDEO:
6175 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6176 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6177 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6178 break;
6179 case cricket::MEDIA_TYPE_DATA:
6180 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6181 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6182 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6183 break;
6184 default:
6185 RTC_NOTREACHED();
6186 continue;
6187 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006188 }
Steve Anton75737c02017-11-06 10:37:17 -08006189 }
6190}
6191
6192void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6193 RTC_DCHECK(worker_thread()->IsCurrent());
6194 RTC_DCHECK(call_);
6195 call_->OnSentPacket(sent_packet);
6196}
6197
6198const std::string PeerConnection::GetTransportName(
6199 const std::string& content_name) {
6200 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006201 if (channel) {
6202 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006203 }
Steve Anton6fec8802017-12-04 10:37:29 -08006204 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006205 RTC_DCHECK(sctp_mid_);
6206 if (content_name == *sctp_mid_) {
6207 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006208 }
6209 }
6210 // Return an empty string if failed to retrieve the transport name.
6211 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006212}
6213
Steve Anton6fec8802017-12-04 10:37:29 -08006214void PeerConnection::DestroyTransceiverChannel(
6215 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6216 transceiver) {
6217 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006218
Steve Anton6fec8802017-12-04 10:37:29 -08006219 cricket::BaseChannel* channel = transceiver->internal()->channel();
6220 if (channel) {
6221 transceiver->internal()->SetChannel(nullptr);
6222 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006223 }
6224}
6225
6226void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006227 if (rtp_data_channel_) {
6228 OnDataChannelDestroyed();
6229 DestroyBaseChannel(rtp_data_channel_);
6230 rtp_data_channel_ = nullptr;
6231 }
6232
6233 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6234 // grab a reference to this PeerConnection. If this is called from the
6235 // PeerConnection destructor, the RefCountedObject vtable will have already
6236 // been destroyed (since it is a subclass of PeerConnection) and using
6237 // rtc::Bind will cause "Pure virtual function called" error to appear.
6238
6239 if (sctp_transport_) {
6240 OnDataChannelDestroyed();
6241 network_thread()->Invoke<void>(RTC_FROM_HERE,
6242 [this] { DestroySctpTransport_n(); });
6243 }
6244}
6245
6246void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6247 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006248 switch (channel->media_type()) {
6249 case cricket::MEDIA_TYPE_AUDIO:
6250 channel_manager()->DestroyVoiceChannel(
6251 static_cast<cricket::VoiceChannel*>(channel));
6252 break;
6253 case cricket::MEDIA_TYPE_VIDEO:
6254 channel_manager()->DestroyVideoChannel(
6255 static_cast<cricket::VideoChannel*>(channel));
6256 break;
6257 case cricket::MEDIA_TYPE_DATA:
6258 channel_manager()->DestroyRtpDataChannel(
6259 static_cast<cricket::RtpDataChannel*>(channel));
6260 break;
6261 default:
6262 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6263 break;
6264 }
Zhi Huange830e682018-03-30 10:48:35 -07006265}
Steve Anton6fec8802017-12-04 10:37:29 -08006266
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006267bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006268 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006269 RtpTransportInternal* rtp_transport,
6270 cricket::DtlsTransportInternal* dtls_transport) {
6271 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006272 auto base_channel = GetChannel(mid);
6273 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006274 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006275 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006276 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006277 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006278 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006279 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006280}
6281
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006282PeerConnectionObserver* PeerConnection::Observer() const {
6283 // In earlier production code, the pointer was not cleared on close,
6284 // which might have led to undefined behavior if the observer was not
6285 // deallocated, or strange crashes if it was.
6286 // We use CHECK in order to catch such behavior if it exists.
6287 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6288 RTC_CHECK(observer_);
6289 return observer_;
6290}
6291
Harald Alvestrand89061872018-01-02 14:08:34 +01006292void PeerConnection::ClearStatsCache() {
6293 if (stats_collector_) {
6294 stats_collector_->ClearCachedStatsReport();
6295 }
6296}
6297
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006298void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006299 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6300 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006301}
6302
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006303} // namespace webrtc