blob: 9dc5e663dc5a7c2b64384e0217685dd9827b4394 [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;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700942
943 if (configuration.use_media_transport) {
944 if (!factory_->media_transport_factory()) {
945 RTC_DCHECK(false)
946 << "PeerConnecton is initialized with use_media_transport = true, "
947 << "but media transport factory is not set in PeerConnectioFactory";
948 return false;
949 }
950
951 config.media_transport_factory = factory_->media_transport_factory();
952 }
953
Zhi Huange830e682018-03-30 10:48:35 -0700954 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700955 signaling_thread(), network_thread(), port_allocator_.get(),
956 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700957 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800958 this, &PeerConnection::OnTransportControllerConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +0200959 transport_controller_->SignalStandardizedIceConnectionState.connect(
960 this, &PeerConnection::SetStandardizedIceConnectionState);
961 transport_controller_->SignalConnectionState.connect(
962 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700963 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800964 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700965 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800966 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700967 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800968 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
969 transport_controller_->SignalDtlsHandshakeError.connect(
970 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
971
972 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700973
deadbeefab9b2d12015-10-14 11:33:11 -0700974 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700975 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000976
Steve Antonba818672017-11-06 10:21:57 -0800977 configuration_ = configuration;
978
Steve Anton75737c02017-11-06 10:37:17 -0800979 // Obtain a certificate from RTCConfiguration if any were provided (optional).
980 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
981 if (!configuration.certificates.empty()) {
982 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
983 // just picking the first one. The decision should be made based on the DTLS
984 // handshake. The DTLS negotiations need to know about all certificates.
985 certificate = configuration.certificates[0];
986 }
987
Steve Antond25da372017-11-06 14:50:29 -0800988 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800989
990 if (options.disable_encryption) {
991 dtls_enabled_ = false;
992 } else {
993 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700994 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800995 // |configuration| can override the default |dtls_enabled_| value.
996 if (configuration.enable_dtls_srtp) {
997 dtls_enabled_ = *(configuration.enable_dtls_srtp);
998 }
999 }
1000
1001 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
1002 // It takes precendence over the disable_sctp_data_channels
1003 // PeerConnectionFactoryInterface::Options.
1004 if (configuration.enable_rtp_data_channel) {
1005 data_channel_type_ = cricket::DCT_RTP;
1006 } else {
1007 // DTLS has to be enabled to use SCTP.
1008 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1009 data_channel_type_ = cricket::DCT_SCTP;
1010 }
1011 }
1012
1013 video_options_.screencast_min_bitrate_kbps =
1014 configuration.screencast_min_bitrate;
1015 audio_options_.combined_audio_video_bwe =
1016 configuration.combined_audio_video_bwe;
1017
1018 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001019 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001020
1021 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001022 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001023
1024 // Whether the certificate generator/certificate is null or not determines
1025 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1026 // the right instructions by clearing the variables if needed.
1027 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001028 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001029 certificate = nullptr;
1030 } else if (certificate) {
1031 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001032 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001033 }
1034
1035 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1036 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001037 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001038 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1039 this, &PeerConnection::OnCertificateReady);
1040
1041 if (options.disable_encryption) {
1042 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1043 }
1044
1045 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001046 options.crypto_options.srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001047
Steve Anton4171afb2017-11-20 10:20:22 -08001048 // Add default audio/video transceivers for Plan B SDP.
1049 if (!IsUnifiedPlan()) {
1050 transceivers_.push_back(
1051 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1052 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1053 transceivers_.push_back(
1054 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1055 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1056 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001057 int delay_ms =
1058 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001059 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1060 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001061 return true;
1062}
1063
Steve Anton038834f2017-07-14 15:59:59 -07001064RTCError PeerConnection::ValidateConfiguration(
1065 const RTCConfiguration& config) const {
1066 if (config.ice_regather_interval_range &&
1067 config.continual_gathering_policy == GATHER_ONCE) {
1068 return RTCError(RTCErrorType::INVALID_PARAMETER,
1069 "ice_regather_interval_range specified but continual "
1070 "gathering policy is GATHER_ONCE");
1071 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001072 auto result =
1073 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1074 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001075}
1076
Yves Gerey665174f2018-06-19 15:03:05 +02001077rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001078 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1079 "Plan SdpSemantics. Please use GetSenders "
1080 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001081 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001082}
1083
Yves Gerey665174f2018-06-19 15:03:05 +02001084rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001085 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1086 "Plan SdpSemantics. Please use GetReceivers "
1087 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001088 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001089}
1090
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001091bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001092 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1093 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001094 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 if (IsClosed()) {
1096 return false;
1097 }
deadbeefab9b2d12015-10-14 11:33:11 -07001098 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001099 return false;
1100 }
deadbeefab9b2d12015-10-14 11:33:11 -07001101
1102 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001103 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1104 observer->SignalAudioTrackAdded.connect(this,
1105 &PeerConnection::OnAudioTrackAdded);
1106 observer->SignalAudioTrackRemoved.connect(
1107 this, &PeerConnection::OnAudioTrackRemoved);
1108 observer->SignalVideoTrackAdded.connect(this,
1109 &PeerConnection::OnVideoTrackAdded);
1110 observer->SignalVideoTrackRemoved.connect(
1111 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001112 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001113
deadbeefab9b2d12015-10-14 11:33:11 -07001114 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001115 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001116 }
1117 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001118 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001119 }
1120
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001121 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001122 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001123 return true;
1124}
1125
1126void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001127 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1128 "Plan SdpSemantics. Please use RemoveTrack "
1129 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001130 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001131 if (!IsClosed()) {
1132 for (const auto& track : local_stream->GetAudioTracks()) {
1133 RemoveAudioTrack(track.get(), local_stream);
1134 }
1135 for (const auto& track : local_stream->GetVideoTracks()) {
1136 RemoveVideoTrack(track.get(), local_stream);
1137 }
deadbeefab9b2d12015-10-14 11:33:11 -07001138 }
deadbeefab9b2d12015-10-14 11:33:11 -07001139 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001140 stream_observers_.erase(
1141 std::remove_if(
1142 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001143 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001144 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001145 }),
1146 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001147
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148 if (IsClosed()) {
1149 return;
1150 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001151 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152}
1153
Steve Anton2d6c76a2018-01-05 17:10:52 -08001154RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001155 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001156 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001157 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001158 if (!track) {
1159 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1160 }
1161 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1162 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1163 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1164 "Track has invalid kind: " + track->kind());
1165 }
Steve Antonf9381f02017-12-14 10:23:57 -08001166 if (IsClosed()) {
1167 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1168 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001169 }
Steve Anton4171afb2017-11-20 10:20:22 -08001170 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001171 LOG_AND_RETURN_ERROR(
1172 RTCErrorType::INVALID_PARAMETER,
1173 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001174 }
Steve Antonf9381f02017-12-14 10:23:57 -08001175 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001176 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1177 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001178 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001179 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001180 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001181 }
1182 return sender_or_error;
1183}
deadbeefe1f9d832016-01-14 15:35:42 -08001184
Steve Antonf9381f02017-12-14 10:23:57 -08001185RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1186PeerConnection::AddTrackPlanB(
1187 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001188 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001189 if (stream_ids.size() > 1u) {
1190 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1191 "AddTrack with more than one stream is not "
1192 "supported with Plan B semantics.");
1193 }
1194 std::vector<std::string> adjusted_stream_ids = stream_ids;
1195 if (adjusted_stream_ids.empty()) {
1196 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1197 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001198 cricket::MediaType media_type =
1199 (track->kind() == MediaStreamTrackInterface::kAudioKind
1200 ? cricket::MEDIA_TYPE_AUDIO
1201 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001202 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001203 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001204 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001205 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001206 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001207 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001208 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001209 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001210 if (sender_info) {
1211 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001212 }
Steve Antonf9381f02017-12-14 10:23:57 -08001213 } else {
1214 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001215 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001216 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001217 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001218 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001219 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001220 if (sender_info) {
1221 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001222 }
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001224 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001225}
deadbeefe1f9d832016-01-14 15:35:42 -08001226
Steve Antonf9381f02017-12-14 10:23:57 -08001227RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1228PeerConnection::AddTrackUnifiedPlan(
1229 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001230 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001231 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1232 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001233 RTC_LOG(LS_INFO) << "Reusing an existing "
1234 << cricket::MediaTypeToString(transceiver->media_type())
1235 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001236 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001237 transceiver->internal()->set_direction(
1238 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001239 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001240 transceiver->internal()->set_direction(
1241 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001242 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001243 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001244 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001245 } else {
1246 cricket::MediaType media_type =
1247 (track->kind() == MediaStreamTrackInterface::kAudioKind
1248 ? cricket::MEDIA_TYPE_AUDIO
1249 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001250 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1251 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001252 std::string sender_id = track->id();
1253 // Avoid creating a sender with an existing ID by generating a random ID.
1254 // This can happen if this is the second time AddTrack has created a sender
1255 // for this track.
1256 if (FindSenderById(sender_id)) {
1257 sender_id = rtc::CreateRandomUuid();
1258 }
Florent Castelli892acf02018-10-01 22:47:20 +02001259 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001260 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1261 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001262 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001263 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001264 }
Steve Antonf9381f02017-12-14 10:23:57 -08001265 return transceiver->sender();
1266}
1267
1268rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1269PeerConnection::FindFirstTransceiverForAddedTrack(
1270 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1271 RTC_DCHECK(track);
1272 for (auto transceiver : transceivers_) {
1273 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001274 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001275 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001276 !transceiver->internal()->has_ever_been_used_to_send() &&
1277 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001278 return transceiver;
1279 }
1280 }
1281 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001282}
1283
1284bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1285 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001286 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001287}
1288
Steve Anton24db5732018-07-23 10:27:33 -07001289RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001290 rtc::scoped_refptr<RtpSenderInterface> sender) {
1291 if (!sender) {
1292 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1293 }
deadbeefe1f9d832016-01-14 15:35:42 -08001294 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001295 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1296 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001297 }
Steve Antonf9381f02017-12-14 10:23:57 -08001298 if (IsUnifiedPlan()) {
1299 auto transceiver = FindTransceiverBySender(sender);
1300 if (!transceiver || !sender->track()) {
1301 return RTCError::OK();
1302 }
1303 sender->SetTrack(nullptr);
1304 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001305 transceiver->internal()->set_direction(
1306 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001307 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001308 transceiver->internal()->set_direction(
1309 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001310 }
Steve Anton4171afb2017-11-20 10:20:22 -08001311 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001312 bool removed;
1313 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1314 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1315 } else {
1316 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1317 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1318 }
1319 if (!removed) {
1320 LOG_AND_RETURN_ERROR(
1321 RTCErrorType::INVALID_PARAMETER,
1322 "Couldn't find sender " + sender->id() + " to remove.");
1323 }
Steve Anton4171afb2017-11-20 10:20:22 -08001324 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001325 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001326 return RTCError::OK();
1327}
1328
1329rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1330PeerConnection::FindTransceiverBySender(
1331 rtc::scoped_refptr<RtpSenderInterface> sender) {
1332 for (auto transceiver : transceivers_) {
1333 if (transceiver->sender() == sender) {
1334 return transceiver;
1335 }
1336 }
1337 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001338}
1339
Steve Anton9158ef62017-11-27 13:01:52 -08001340RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1341PeerConnection::AddTransceiver(
1342 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1343 return AddTransceiver(track, RtpTransceiverInit());
1344}
1345
1346RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1347PeerConnection::AddTransceiver(
1348 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1349 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001350 RTC_CHECK(IsUnifiedPlan())
1351 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001352 if (!track) {
1353 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1354 }
1355 cricket::MediaType media_type;
1356 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1357 media_type = cricket::MEDIA_TYPE_AUDIO;
1358 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1359 media_type = cricket::MEDIA_TYPE_VIDEO;
1360 } else {
1361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1362 "Track kind is not audio or video");
1363 }
1364 return AddTransceiver(media_type, track, init);
1365}
1366
1367RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1368PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1369 return AddTransceiver(media_type, RtpTransceiverInit());
1370}
1371
1372RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1373PeerConnection::AddTransceiver(cricket::MediaType media_type,
1374 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001375 RTC_CHECK(IsUnifiedPlan())
1376 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001377 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1378 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1379 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1380 "media type is not audio or video");
1381 }
1382 return AddTransceiver(media_type, nullptr, init);
1383}
1384
1385RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1386PeerConnection::AddTransceiver(
1387 cricket::MediaType media_type,
1388 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001389 const RtpTransceiverInit& init,
1390 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001391 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1392 media_type == cricket::MEDIA_TYPE_VIDEO));
1393 if (track) {
1394 RTC_DCHECK_EQ(media_type,
1395 (track->kind() == MediaStreamTrackInterface::kAudioKind
1396 ? cricket::MEDIA_TYPE_AUDIO
1397 : cricket::MEDIA_TYPE_VIDEO));
1398 }
1399
1400 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001401 if (init.send_encodings.size() > 1) {
1402 LOG_AND_RETURN_ERROR(
1403 RTCErrorType::UNSUPPORTED_PARAMETER,
1404 "Attempted to create an encoder with more than 1 encoding parameter.");
1405 }
1406
1407 for (const auto& encoding : init.send_encodings) {
1408 if (encoding.ssrc.has_value()) {
1409 LOG_AND_RETURN_ERROR(
1410 RTCErrorType::UNSUPPORTED_PARAMETER,
1411 "Attempted to set an unimplemented parameter of RtpParameters.");
1412 }
1413 }
1414
1415 RtpParameters parameters;
1416 parameters.encodings = init.send_encodings;
1417 if (UnimplementedRtpParameterHasValue(parameters)) {
1418 LOG_AND_RETURN_ERROR(
1419 RTCErrorType::UNSUPPORTED_PARAMETER,
1420 "Attempted to set an unimplemented parameter of RtpParameters.");
1421 }
Steve Anton9158ef62017-11-27 13:01:52 -08001422
Steve Anton3d954a62018-04-02 11:27:23 -07001423 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1424 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001425 // Set the sender ID equal to the track ID if the track is specified unless
1426 // that sender ID is already in use.
1427 std::string sender_id =
1428 (track && !FindSenderById(track->id()) ? track->id()
1429 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001430 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1431 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001432 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1433 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1434 transceiver->internal()->set_direction(init.direction);
1435
Steve Anton22da89f2018-01-25 13:58:07 -08001436 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001437 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001438 }
Steve Antonf9381f02017-12-14 10:23:57 -08001439
1440 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1441}
1442
Steve Anton02ee47c2018-01-10 16:26:06 -08001443rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1444PeerConnection::CreateSender(
1445 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001446 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001448 const std::vector<std::string>& stream_ids,
1449 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001450 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001451 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1452 RTC_DCHECK(!track ||
1453 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1454 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1455 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001456 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001457 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001458 } else {
1459 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1460 RTC_DCHECK(!track ||
1461 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1462 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001463 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001464 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001465 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001466 bool set_track_succeeded = sender->SetTrack(track);
1467 RTC_DCHECK(set_track_succeeded);
1468 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001469 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001470 return sender;
1471}
1472
1473rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1474PeerConnection::CreateReceiver(cricket::MediaType media_type,
1475 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001476 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1477 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001478 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001479 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001480 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1481 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001482 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001483 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001484 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001485 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001486 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1487 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001488 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001489 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001490 return receiver;
1491}
1492
1493rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1494PeerConnection::CreateAndAddTransceiver(
1495 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1496 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1497 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001498 // Ensure that the new sender does not have an ID that is already in use by
1499 // another sender.
1500 // Allow receiver IDs to conflict since those come from remote SDP (which
1501 // could be invalid, but should not cause a crash).
1502 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001503 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1504 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001505 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001506 transceiver->internal()->SignalNegotiationNeeded.connect(
1507 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001508 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001509}
1510
Steve Anton52d86772018-02-20 15:48:12 -08001511void PeerConnection::OnNegotiationNeeded() {
1512 RTC_DCHECK_RUN_ON(signaling_thread());
1513 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001514 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001515}
1516
deadbeeffac06552015-11-25 11:26:01 -08001517rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001518 const std::string& kind,
1519 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001520 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1521 "Plan SdpSemantics. Please use AddTransceiver "
1522 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001523 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001524 if (IsClosed()) {
1525 return nullptr;
1526 }
Steve Anton4171afb2017-11-20 10:20:22 -08001527
Seth Hampson5b4f0752018-04-02 16:31:36 -07001528 // Internally we need to have one stream with Plan B semantics, so we
1529 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001530 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001531 if (stream_id.empty()) {
1532 stream_ids.push_back(rtc::CreateRandomUuid());
1533 RTC_LOG(LS_INFO)
1534 << "No stream_id specified for sender. Generated stream ID: "
1535 << stream_ids[0];
1536 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001537 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001538 }
1539
Steve Anton4171afb2017-11-20 10:20:22 -08001540 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001541 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001542 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001543 auto* audio_sender = new AudioRtpSender(
1544 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001545 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001546 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001547 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001548 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001549 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001550 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001551 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001552 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001553 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001554 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001555 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001556 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001557 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001558 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001559 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001560 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001561
deadbeefe1f9d832016-01-14 15:35:42 -08001562 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001563}
1564
deadbeef70ab1a12015-09-28 16:53:55 -07001565std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1566 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001567 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001568 for (auto sender : GetSendersInternal()) {
1569 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001570 }
1571 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001572}
1573
Steve Anton4171afb2017-11-20 10:20:22 -08001574std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1575PeerConnection::GetSendersInternal() const {
1576 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1577 all_senders;
1578 for (auto transceiver : transceivers_) {
1579 auto senders = transceiver->internal()->senders();
1580 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1581 }
1582 return all_senders;
1583}
1584
deadbeef70ab1a12015-09-28 16:53:55 -07001585std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1586PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001587 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001588 for (const auto& receiver : GetReceiversInternal()) {
1589 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001590 }
1591 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001592}
1593
Steve Anton4171afb2017-11-20 10:20:22 -08001594std::vector<
1595 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1596PeerConnection::GetReceiversInternal() const {
1597 std::vector<
1598 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1599 all_receivers;
1600 for (auto transceiver : transceivers_) {
1601 auto receivers = transceiver->internal()->receivers();
1602 all_receivers.insert(all_receivers.end(), receivers.begin(),
1603 receivers.end());
1604 }
1605 return all_receivers;
1606}
1607
Steve Anton9158ef62017-11-27 13:01:52 -08001608std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1609PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001610 RTC_CHECK(IsUnifiedPlan())
1611 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001612 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1613 for (auto transceiver : transceivers_) {
1614 all_transceivers.push_back(transceiver);
1615 }
1616 return all_transceivers;
1617}
1618
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001619bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001620 MediaStreamTrackInterface* track,
1621 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001622 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001623 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001624 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001625 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001626 return false;
1627 }
1628
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001629 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001630 // The StatsCollector is used to tell if a track is valid because it may
1631 // remember tracks that the PeerConnection previously removed.
1632 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001633 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1634 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001635 return false;
1636 }
Steve Antonad182762018-09-05 20:22:40 +00001637 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1638 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001639 return true;
1640}
1641
hbos74e1a4f2016-09-15 23:33:01 -07001642void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001643 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001644 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001645 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001646 stats_collector_->GetStatsReport(callback);
1647}
1648
Henrik Boström1df1bf82018-03-20 13:24:20 +01001649void PeerConnection::GetStats(
1650 rtc::scoped_refptr<RtpSenderInterface> selector,
1651 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1652 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1653 RTC_DCHECK(callback);
1654 RTC_DCHECK(stats_collector_);
1655 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1656 if (selector) {
1657 for (const auto& proxy_transceiver : transceivers_) {
1658 for (const auto& proxy_sender :
1659 proxy_transceiver->internal()->senders()) {
1660 if (proxy_sender == selector) {
1661 internal_sender = proxy_sender->internal();
1662 break;
1663 }
1664 }
1665 if (internal_sender)
1666 break;
1667 }
1668 }
1669 // If there is no |internal_sender| then |selector| is either null or does not
1670 // belong to the PeerConnection (in Plan B, senders can be removed from the
1671 // PeerConnection). This means that "all the stats objects representing the
1672 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1673 // produces an empty stats report.
1674 stats_collector_->GetStatsReport(internal_sender, callback);
1675}
1676
1677void PeerConnection::GetStats(
1678 rtc::scoped_refptr<RtpReceiverInterface> selector,
1679 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1680 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1681 RTC_DCHECK(callback);
1682 RTC_DCHECK(stats_collector_);
1683 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1684 if (selector) {
1685 for (const auto& proxy_transceiver : transceivers_) {
1686 for (const auto& proxy_receiver :
1687 proxy_transceiver->internal()->receivers()) {
1688 if (proxy_receiver == selector) {
1689 internal_receiver = proxy_receiver->internal();
1690 break;
1691 }
1692 }
1693 if (internal_receiver)
1694 break;
1695 }
1696 }
1697 // If there is no |internal_receiver| then |selector| is either null or does
1698 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1699 // the PeerConnection). This means that "all the stats objects representing
1700 // the selector" is an empty set. Invoking GetStatsReport() with a null
1701 // selector produces an empty stats report.
1702 stats_collector_->GetStatsReport(internal_receiver, callback);
1703}
1704
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1706 return signaling_state_;
1707}
1708
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001709PeerConnectionInterface::IceConnectionState
1710PeerConnection::ice_connection_state() {
1711 return ice_connection_state_;
1712}
1713
Jonas Olsson635474e2018-10-18 15:58:17 +02001714PeerConnectionInterface::IceConnectionState
1715PeerConnection::standardized_ice_connection_state() {
1716 return standardized_ice_connection_state_;
1717}
1718
1719PeerConnectionInterface::PeerConnectionState
1720PeerConnection::peer_connection_state() {
1721 return connection_state_;
1722}
1723
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001724PeerConnectionInterface::IceGatheringState
1725PeerConnection::ice_gathering_state() {
1726 return ice_gathering_state_;
1727}
1728
Yves Gerey665174f2018-06-19 15:03:05 +02001729rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001730 const std::string& label,
1731 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001732 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001733
deadbeefab9b2d12015-10-14 11:33:11 -07001734 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001735
kwibergd1fe2812016-04-27 06:47:29 -07001736 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001737 if (config) {
1738 internal_config.reset(new InternalDataChannelInit(*config));
1739 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001740 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001741 InternalCreateDataChannel(label, internal_config.get()));
1742 if (!channel.get()) {
1743 return nullptr;
1744 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001745
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001746 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1747 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001748 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001749 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001750 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001751 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001752 return DataChannelProxy::Create(signaling_thread(), channel.get());
1753}
1754
1755void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001756 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001757 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001758
nisse7ce109a2017-01-31 00:57:56 -08001759 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001761 return;
1762 }
deadbeefab9b2d12015-10-14 11:33:11 -07001763
Steve Anton8d3444d2017-10-20 15:30:51 -07001764 if (IsClosed()) {
1765 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001766 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001767 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001768 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001769 return;
1770 }
1771
zhihuang1c378ed2017-08-17 14:10:50 -07001772 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001773 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001774 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001775 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001776 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001777 return;
1778 }
1779
Steve Anton22da89f2018-01-25 13:58:07 -08001780 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1781 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1782 if (IsUnifiedPlan()) {
1783 RTCError error = HandleLegacyOfferOptions(options);
1784 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001785 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001786 return;
1787 }
1788 }
1789
zhihuang1c378ed2017-08-17 14:10:50 -07001790 cricket::MediaSessionOptions session_options;
1791 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001792 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001793}
1794
Steve Anton22da89f2018-01-25 13:58:07 -08001795RTCError PeerConnection::HandleLegacyOfferOptions(
1796 const RTCOfferAnswerOptions& options) {
1797 RTC_DCHECK(IsUnifiedPlan());
1798
1799 if (options.offer_to_receive_audio == 0) {
1800 RemoveRecvDirectionFromReceivingTransceiversOfType(
1801 cricket::MEDIA_TYPE_AUDIO);
1802 } else if (options.offer_to_receive_audio == 1) {
1803 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1804 } else if (options.offer_to_receive_audio > 1) {
1805 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1806 "offer_to_receive_audio > 1 is not supported.");
1807 }
1808
1809 if (options.offer_to_receive_video == 0) {
1810 RemoveRecvDirectionFromReceivingTransceiversOfType(
1811 cricket::MEDIA_TYPE_VIDEO);
1812 } else if (options.offer_to_receive_video == 1) {
1813 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1814 } else if (options.offer_to_receive_video > 1) {
1815 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1816 "offer_to_receive_video > 1 is not supported.");
1817 }
1818
1819 return RTCError::OK();
1820}
1821
1822void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1823 cricket::MediaType media_type) {
1824 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001825 RtpTransceiverDirection new_direction =
1826 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1827 if (new_direction != transceiver->direction()) {
1828 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1829 << " transceiver (MID="
1830 << transceiver->mid().value_or("<not set>") << ") from "
1831 << RtpTransceiverDirectionToString(
1832 transceiver->direction())
1833 << " to "
1834 << RtpTransceiverDirectionToString(new_direction)
1835 << " since CreateOffer specified offer_to_receive=0";
1836 transceiver->internal()->set_direction(new_direction);
1837 }
Steve Anton22da89f2018-01-25 13:58:07 -08001838 }
1839}
1840
1841void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1842 cricket::MediaType media_type) {
1843 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001844 RTC_LOG(LS_INFO)
1845 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1846 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001847 RtpTransceiverInit init;
1848 init.direction = RtpTransceiverDirection::kRecvOnly;
1849 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1850 }
1851}
1852
1853std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1854PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1855 std::vector<
1856 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1857 receiving_transceivers;
1858 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001859 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001860 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1861 receiving_transceivers.push_back(transceiver);
1862 }
1863 }
1864 return receiving_transceivers;
1865}
1866
htaa2a49d92016-03-04 02:51:39 -08001867void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1868 const RTCOfferAnswerOptions& options) {
1869 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001870 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001871 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001872 return;
1873 }
1874
Steve Antondffead82018-02-06 10:31:29 -08001875 if (!(signaling_state_ == kHaveRemoteOffer ||
1876 signaling_state_ == kHaveLocalPrAnswer)) {
1877 std::string error =
1878 "PeerConnection cannot create an answer in a state other than "
1879 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001880 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001881 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001882 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001883 return;
1884 }
1885
Steve Antondffead82018-02-06 10:31:29 -08001886 // The remote description should be set if we're in the right state.
1887 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001888
Steve Anton22da89f2018-01-25 13:58:07 -08001889 if (IsUnifiedPlan()) {
1890 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1891 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1892 "supported with Unified Plan semantics. Use the "
1893 "RtpTransceiver API instead.";
1894 }
1895 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1896 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1897 "supported with Unified Plan semantics. Use the "
1898 "RtpTransceiver API instead.";
1899 }
1900 }
1901
htaa2a49d92016-03-04 02:51:39 -08001902 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001903 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001904
Steve Antond25da372017-11-06 14:50:29 -08001905 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001906}
1907
1908void PeerConnection::SetLocalDescription(
1909 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001910 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001911 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001912
Steve Anton80dd7b52018-02-16 17:08:42 -08001913 // The SetLocalDescription contract is that we take ownership of the session
1914 // description regardless of the outcome, so wrap it in a unique_ptr right
1915 // away. Ideally, SetLocalDescription's signature will be changed to take the
1916 // description as a unique_ptr argument to formalize this agreement.
1917 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1918
nisse7ce109a2017-01-31 00:57:56 -08001919 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001920 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001921 return;
1922 }
Steve Anton8a006912017-12-04 15:25:56 -08001923
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001924 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001925 PostSetSessionDescriptionFailure(
1926 observer,
1927 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001928 return;
1929 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001930
Steve Anton80dd7b52018-02-16 17:08:42 -08001931 // If a session error has occurred the PeerConnection is in a possibly
1932 // inconsistent state so fail right away.
1933 if (session_error() != SessionError::kNone) {
1934 std::string error_message = GetSessionErrorMsg();
1935 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001936 PostSetSessionDescriptionFailure(
1937 observer,
1938 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001939 return;
1940 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001941
Steve Anton80dd7b52018-02-16 17:08:42 -08001942 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1943 if (!error.ok()) {
1944 std::string error_message = GetSetDescriptionErrorMessage(
1945 cricket::CS_LOCAL, desc->GetType(), error);
1946 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001947 PostSetSessionDescriptionFailure(
1948 observer,
1949 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001950 return;
1951 }
1952
1953 // Grab the description type before moving ownership to ApplyLocalDescription,
1954 // which may destroy it before returning.
1955 const SdpType type = desc->GetType();
1956
1957 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001958 // |desc| may be destroyed at this point.
1959
1960 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001961 // If ApplyLocalDescription fails, the PeerConnection could be in an
1962 // inconsistent state, so act conservatively here and set the session error
1963 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1964 SetSessionError(SessionError::kContent, error.message());
1965 std::string error_message =
1966 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1967 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001968 PostSetSessionDescriptionFailure(
1969 observer,
1970 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001971 return;
1972 }
Steve Anton8a006912017-12-04 15:25:56 -08001973 RTC_DCHECK(local_description());
1974
1975 PostSetSessionDescriptionSuccess(observer);
1976
Steve Antonad182762018-09-05 20:22:40 +00001977 // MaybeStartGathering needs to be called after posting
1978 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1979 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001980 transport_controller_->MaybeStartGathering();
1981
Steve Antona3a92c22017-12-07 10:27:41 -08001982 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001983 // TODO(deadbeef): We already had to hop to the network thread for
1984 // MaybeStartGathering...
1985 network_thread()->Invoke<void>(
1986 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1987 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001988 // Make UMA notes about what was agreed to.
1989 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001990 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001991 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001992}
1993
1994RTCError PeerConnection::ApplyLocalDescription(
1995 std::unique_ptr<SessionDescriptionInterface> desc) {
1996 RTC_DCHECK_RUN_ON(signaling_thread());
1997 RTC_DCHECK(desc);
1998
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001999 // Update stats here so that we have the most recent stats for tracks and
2000 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002001 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002002
Steve Antondcc3c022017-12-22 16:02:54 -08002003 // Take a reference to the old local description since it's used below to
2004 // compare against the new local description. When setting the new local
2005 // description, grab ownership of the replaced session description in case it
2006 // is the same as |old_local_description|, to keep it alive for the duration
2007 // of the method.
2008 const SessionDescriptionInterface* old_local_description =
2009 local_description();
2010 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002011 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002012 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002013 replaced_local_description = pending_local_description_
2014 ? std::move(pending_local_description_)
2015 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002016 current_local_description_ = std::move(desc);
2017 pending_local_description_ = nullptr;
2018 current_remote_description_ = std::move(pending_remote_description_);
2019 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002020 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002021 pending_local_description_ = std::move(desc);
2022 }
2023 // The session description to apply now must be accessed by
2024 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002025 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002026
Zhi Huange830e682018-03-30 10:48:35 -07002027 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2028 if (!error.ok()) {
2029 return error;
2030 }
2031
Steve Antondcc3c022017-12-22 16:02:54 -08002032 if (IsUnifiedPlan()) {
2033 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002034 cricket::CS_LOCAL, *local_description(), old_local_description,
2035 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002036 if (!error.ok()) {
2037 return error;
2038 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002039 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2040 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002041 for (auto transceiver : transceivers_) {
2042 const ContentInfo* content =
2043 FindMediaSectionForTransceiver(transceiver, local_description());
2044 if (!content) {
2045 continue;
2046 }
2047 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002048 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2049 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002050 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002051 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2052 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2053 // "recvonly", process the removal of a remote track for the media
2054 // description, given transceiver, removeList, and muteTracks.
2055 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2056 (transceiver->internal()->fired_direction() &&
2057 RtpTransceiverDirectionHasRecv(
2058 *transceiver->internal()->fired_direction()))) {
2059 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2060 &removed_streams);
2061 }
2062 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2063 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002064 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002065 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002066 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002067 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002068 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002069 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002070 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002071 }
2072 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002073 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002074 }
2075 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002076 // Media channels will be created only when offer is set. These may use new
2077 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002078 if (type == SdpType::kOffer) {
2079 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2080 // description is applied. Restore back to old description.
2081 RTCError error = CreateChannels(*local_description()->description());
2082 if (!error.ok()) {
2083 return error;
2084 }
2085 }
Steve Antondcc3c022017-12-22 16:02:54 -08002086 // Remove unused channels if MediaContentDescription is rejected.
2087 RemoveUnusedChannels(local_description()->description());
2088 }
Steve Anton8a006912017-12-04 15:25:56 -08002089
Zhi Huange830e682018-03-30 10:48:35 -07002090 error = UpdateSessionState(type, cricket::CS_LOCAL,
2091 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002092 if (!error.ok()) {
2093 return error;
2094 }
Steve Antondcc3c022017-12-22 16:02:54 -08002095
Steve Anton8a006912017-12-04 15:25:56 -08002096 if (remote_description()) {
2097 // Now that we have a local description, we can push down remote candidates.
2098 UseCandidatesInSessionDescription(remote_description());
2099 }
2100
2101 pending_ice_restarts_.clear();
2102 if (session_error() != SessionError::kNone) {
2103 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2104 }
2105
deadbeefab9b2d12015-10-14 11:33:11 -07002106 // If setting the description decided our SSL role, allocate any necessary
2107 // SCTP sids.
2108 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002109 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002110 AllocateSctpSids(role);
2111 }
2112
Steve Antond3679212018-01-17 17:41:02 -08002113 if (IsUnifiedPlan()) {
2114 for (auto transceiver : transceivers_) {
2115 const ContentInfo* content =
2116 FindMediaSectionForTransceiver(transceiver, local_description());
2117 if (!content) {
2118 continue;
2119 }
Steve Anton74255ff2018-01-24 18:32:57 -08002120 const auto& streams = content->media_description()->streams();
2121 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002122 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002123 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002124 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002125 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002126 } else {
2127 // 0 is a special value meaning "this sender has no associated send
2128 // stream". Need to call this so the sender won't attempt to configure
2129 // a no longer existing stream and run into DCHECKs in the lower
2130 // layers.
2131 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002132 }
2133 }
2134 } else {
2135 // Plan B semantics.
2136
Steve Antondcc3c022017-12-22 16:02:54 -08002137 // Update state and SSRC of local MediaStreams and DataChannels based on the
2138 // local session description.
2139 const cricket::ContentInfo* audio_content =
2140 GetFirstAudioContent(local_description()->description());
2141 if (audio_content) {
2142 if (audio_content->rejected) {
2143 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2144 } else {
2145 const cricket::AudioContentDescription* audio_desc =
2146 audio_content->media_description()->as_audio();
2147 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2148 }
deadbeeffaac4972015-11-12 15:33:07 -08002149 }
deadbeefab9b2d12015-10-14 11:33:11 -07002150
Steve Antondcc3c022017-12-22 16:02:54 -08002151 const cricket::ContentInfo* video_content =
2152 GetFirstVideoContent(local_description()->description());
2153 if (video_content) {
2154 if (video_content->rejected) {
2155 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2156 } else {
2157 const cricket::VideoContentDescription* video_desc =
2158 video_content->media_description()->as_video();
2159 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2160 }
deadbeeffaac4972015-11-12 15:33:07 -08002161 }
deadbeefab9b2d12015-10-14 11:33:11 -07002162 }
2163
2164 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002165 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002166 if (data_content) {
2167 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002168 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002169 if (rtc::starts_with(data_desc->protocol().data(),
2170 cricket::kMediaProtocolRtpPrefix)) {
2171 UpdateLocalRtpDataChannels(data_desc->streams());
2172 }
2173 }
2174
Steve Anton8a006912017-12-04 15:25:56 -08002175 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002176}
2177
2178void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002179 SetSessionDescriptionObserver* observer,
2180 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002181 SetRemoteDescription(
2182 std::unique_ptr<SessionDescriptionInterface>(desc),
2183 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2184 new SetRemoteDescriptionObserverAdapter(this, observer)));
2185}
2186
2187void PeerConnection::SetRemoteDescription(
2188 std::unique_ptr<SessionDescriptionInterface> desc,
2189 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002190 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002191
nisse7ce109a2017-01-31 00:57:56 -08002192 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002193 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002194 return;
2195 }
Steve Anton8a006912017-12-04 15:25:56 -08002196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002198 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002199 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002200 return;
2201 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002202
Steve Anton80dd7b52018-02-16 17:08:42 -08002203 // If a session error has occurred the PeerConnection is in a possibly
2204 // inconsistent state so fail right away.
2205 if (session_error() != SessionError::kNone) {
2206 std::string error_message = GetSessionErrorMsg();
2207 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2208 observer->OnSetRemoteDescriptionComplete(
2209 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2210 return;
2211 }
Steve Anton71439a62018-02-15 11:53:06 -08002212
Steve Antonba42e992018-04-09 14:10:01 -07002213 if (desc->GetType() == SdpType::kOffer) {
2214 // Report to UMA the format of the received offer.
2215 ReportSdpFormatReceived(*desc);
2216 }
2217
Steve Anton80dd7b52018-02-16 17:08:42 -08002218 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002219 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002220 std::string error_message = GetSetDescriptionErrorMessage(
2221 cricket::CS_REMOTE, desc->GetType(), error);
2222 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002223 observer->OnSetRemoteDescriptionComplete(
2224 RTCError(error.type(), std::move(error_message)));
2225 return;
2226 }
Steve Anton71439a62018-02-15 11:53:06 -08002227
Steve Anton80dd7b52018-02-16 17:08:42 -08002228 // Grab the description type before moving ownership to
2229 // ApplyRemoteDescription, which may destroy it before returning.
2230 const SdpType type = desc->GetType();
2231
2232 error = ApplyRemoteDescription(std::move(desc));
2233 // |desc| may be destroyed at this point.
2234
2235 if (!error.ok()) {
2236 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2237 // inconsistent state, so act conservatively here and set the session error
2238 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2239 SetSessionError(SessionError::kContent, error.message());
2240 std::string error_message =
2241 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2242 RTC_LOG(LS_ERROR) << error_message;
2243 observer->OnSetRemoteDescriptionComplete(
2244 RTCError(error.type(), std::move(error_message)));
2245 return;
2246 }
2247 RTC_DCHECK(remote_description());
2248
2249 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002250 // TODO(deadbeef): We already had to hop to the network thread for
2251 // MaybeStartGathering...
2252 network_thread()->Invoke<void>(
2253 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2254 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002255 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002256 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002257 }
2258
2259 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002260 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002261}
2262
2263RTCError PeerConnection::ApplyRemoteDescription(
2264 std::unique_ptr<SessionDescriptionInterface> desc) {
2265 RTC_DCHECK_RUN_ON(signaling_thread());
2266 RTC_DCHECK(desc);
2267
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002268 // Update stats here so that we have the most recent stats for tracks and
2269 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002270 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002271
Steve Antondcc3c022017-12-22 16:02:54 -08002272 // Take a reference to the old remote description since it's used below to
2273 // compare against the new remote description. When setting the new remote
2274 // description, grab ownership of the replaced session description in case it
2275 // is the same as |old_remote_description|, to keep it alive for the duration
2276 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002277 const SessionDescriptionInterface* old_remote_description =
2278 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002279 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002280 SdpType type = desc->GetType();
2281 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002282 replaced_remote_description = pending_remote_description_
2283 ? std::move(pending_remote_description_)
2284 : std::move(current_remote_description_);
2285 current_remote_description_ = std::move(desc);
2286 pending_remote_description_ = nullptr;
2287 current_local_description_ = std::move(pending_local_description_);
2288 } else {
2289 replaced_remote_description = std::move(pending_remote_description_);
2290 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002291 }
Steve Anton8a006912017-12-04 15:25:56 -08002292 // The session description to apply now must be accessed by
2293 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002294 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002295
Zhi Huange830e682018-03-30 10:48:35 -07002296 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2297 if (!error.ok()) {
2298 return error;
2299 }
Steve Anton8a006912017-12-04 15:25:56 -08002300 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002301 if (IsUnifiedPlan()) {
2302 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002303 cricket::CS_REMOTE, *remote_description(), local_description(),
2304 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002305 if (!error.ok()) {
2306 return error;
2307 }
Steve Antondcc3c022017-12-22 16:02:54 -08002308 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002309 // Media channels will be created only when offer is set. These may use new
2310 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002311 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002312 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002313 // description is applied. Restore back to old description.
2314 RTCError error = CreateChannels(*remote_description()->description());
2315 if (!error.ok()) {
2316 return error;
2317 }
2318 }
Steve Antondcc3c022017-12-22 16:02:54 -08002319 // Remove unused channels if MediaContentDescription is rejected.
2320 RemoveUnusedChannels(remote_description()->description());
2321 }
Steve Anton8a006912017-12-04 15:25:56 -08002322
Zhi Huange830e682018-03-30 10:48:35 -07002323 // NOTE: Candidates allocation will be initiated only when
2324 // SetLocalDescription is called.
2325 error = UpdateSessionState(type, cricket::CS_REMOTE,
2326 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002327 if (!error.ok()) {
2328 return error;
2329 }
2330
2331 if (local_description() &&
2332 !UseCandidatesInSessionDescription(remote_description())) {
2333 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2334 }
2335
2336 if (old_remote_description) {
2337 for (const cricket::ContentInfo& content :
2338 old_remote_description->description()->contents()) {
2339 // Check if this new SessionDescription contains new ICE ufrag and
2340 // password that indicates the remote peer requests an ICE restart.
2341 // TODO(deadbeef): When we start storing both the current and pending
2342 // remote description, this should reset pending_ice_restarts and compare
2343 // against the current description.
2344 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2345 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002346 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002347 pending_ice_restarts_.insert(content.name);
2348 }
2349 } else {
2350 // We retain all received candidates only if ICE is not restarted.
2351 // When ICE is restarted, all previous candidates belong to an old
2352 // generation and should not be kept.
2353 // TODO(deadbeef): This goes against the W3C spec which says the remote
2354 // description should only contain candidates from the last set remote
2355 // description plus any candidates added since then. We should remove
2356 // this once we're sure it won't break anything.
2357 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2358 old_remote_description, content.name, mutable_remote_description());
2359 }
2360 }
2361 }
2362
2363 if (session_error() != SessionError::kNone) {
2364 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2365 }
2366
2367 // Set the the ICE connection state to connecting since the connection may
2368 // become writable with peer reflexive candidates before any remote candidate
2369 // is signaled.
2370 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2371 // is to have a new signal the indicates a change in checking state from the
2372 // transport and expose a new checking() member from transport that can be
2373 // read to determine the current checking state. The existing SignalConnecting
2374 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002375 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002376 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002377 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2378 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2379 }
2380
deadbeefab9b2d12015-10-14 11:33:11 -07002381 // If setting the description decided our SSL role, allocate any necessary
2382 // SCTP sids.
2383 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002384 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002385 AllocateSctpSids(role);
2386 }
2387
Steve Antondcc3c022017-12-22 16:02:54 -08002388 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002389 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002390 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002391 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002392 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002393 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002394 for (auto transceiver : transceivers_) {
2395 const ContentInfo* content =
2396 FindMediaSectionForTransceiver(transceiver, remote_description());
2397 if (!content) {
2398 continue;
2399 }
2400 const MediaContentDescription* media_desc = content->media_description();
2401 RtpTransceiverDirection local_direction =
2402 RtpTransceiverDirectionReversed(media_desc->direction());
2403 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2404 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2405 // transceiver's current direction is neither sendrecv nor recvonly,
2406 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002407 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002408 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002409 // The remote description has signaled the stream IDs.
2410 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002411 }
Steve Antondcc3c022017-12-22 16:02:54 -08002412 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002413 (!transceiver->fired_direction() ||
2414 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002415 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002416 << content->name << " (added to "
2417 << GetStreamIdsString(stream_ids) << ").";
2418
2419 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2420 for (const std::string& stream_id : stream_ids) {
2421 rtc::scoped_refptr<MediaStreamInterface> stream =
2422 remote_streams_->find(stream_id);
2423 if (!stream) {
2424 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2425 MediaStream::Create(stream_id));
2426 remote_streams_->AddStream(stream);
2427 added_streams.push_back(stream);
2428 }
2429 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002430 }
Steve Anton3172c032018-05-03 15:30:18 -07002431 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002432 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2433 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002434 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002435 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002436 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002437 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2438 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2439 // removal of a remote track for the media description, given transceiver,
2440 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002441 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002442 (transceiver->fired_direction() &&
2443 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2444 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2445 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002446 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002447 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2448 transceiver->internal()->set_fired_direction(local_direction);
2449 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2450 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002451 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002452 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2453 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002454 transceiver->internal()->set_current_direction(local_direction);
2455 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002456 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2457 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002458 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002459 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2460 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002461 transceiver->Stop();
2462 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002463 if (!content->rejected &&
2464 RtpTransceiverDirectionHasRecv(local_direction)) {
2465 // Set ssrc to 0 in the case of an unsignalled ssrc.
2466 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002467 if (!media_desc->streams().empty() &&
2468 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002469 ssrc = media_desc->streams()[0].first_ssrc();
2470 }
2471 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002472 }
Steve Antondcc3c022017-12-22 16:02:54 -08002473 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002474 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002475 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002476 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002477 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002478 observer->OnTrack(transceiver);
2479 observer->OnAddTrack(transceiver->receiver(),
2480 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002481 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002482 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002483 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002484 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002485 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002486 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002487 }
2488 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002489 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002490 }
Steve Antondcc3c022017-12-22 16:02:54 -08002491 }
2492
Henrik Boströmfdb92012017-11-09 19:55:44 +01002493 const cricket::ContentInfo* audio_content =
2494 GetFirstAudioContent(remote_description()->description());
2495 const cricket::ContentInfo* video_content =
2496 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002497 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002498 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002499 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002500 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002501 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002502 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002503
2504 // Check if the descriptions include streams, just in case the peer supports
2505 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002506 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002507 (audio_desc && !audio_desc->streams().empty()) ||
2508 (video_desc && !video_desc->streams().empty())) {
2509 remote_peer_supports_msid_ = true;
2510 }
deadbeefab9b2d12015-10-14 11:33:11 -07002511
2512 // We wait to signal new streams until we finish processing the description,
2513 // since only at that point will new streams have all their tracks.
2514 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2515
Steve Antondcc3c022017-12-22 16:02:54 -08002516 if (!IsUnifiedPlan()) {
2517 // TODO(steveanton): When removing RTP senders/receivers in response to a
2518 // rejected media section, there is some cleanup logic that expects the
2519 // voice/ video channel to still be set. But in this method the voice/video
2520 // channel would have been destroyed by the SetRemoteDescription caller
2521 // above so the cleanup that relies on them fails to run. The RemoveSenders
2522 // calls should be moved to right before the DestroyChannel calls to fix
2523 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002524
Steve Antondcc3c022017-12-22 16:02:54 -08002525 // Find all audio rtp streams and create corresponding remote AudioTracks
2526 // and MediaStreams.
2527 if (audio_content) {
2528 if (audio_content->rejected) {
2529 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2530 } else {
2531 bool default_audio_track_needed =
2532 !remote_peer_supports_msid_ &&
2533 RtpTransceiverDirectionHasSend(audio_desc->direction());
2534 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2535 default_audio_track_needed, audio_desc->type(),
2536 new_streams);
2537 }
deadbeeffaac4972015-11-12 15:33:07 -08002538 }
deadbeefab9b2d12015-10-14 11:33:11 -07002539
Steve Antondcc3c022017-12-22 16:02:54 -08002540 // Find all video rtp streams and create corresponding remote VideoTracks
2541 // and MediaStreams.
2542 if (video_content) {
2543 if (video_content->rejected) {
2544 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2545 } else {
2546 bool default_video_track_needed =
2547 !remote_peer_supports_msid_ &&
2548 RtpTransceiverDirectionHasSend(video_desc->direction());
2549 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2550 default_video_track_needed, video_desc->type(),
2551 new_streams);
2552 }
deadbeeffaac4972015-11-12 15:33:07 -08002553 }
deadbeefab9b2d12015-10-14 11:33:11 -07002554
Steve Antondcc3c022017-12-22 16:02:54 -08002555 // Update the DataChannels with the information from the remote peer.
2556 if (data_desc) {
2557 if (rtc::starts_with(data_desc->protocol().data(),
2558 cricket::kMediaProtocolRtpPrefix)) {
2559 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2560 }
deadbeefab9b2d12015-10-14 11:33:11 -07002561 }
deadbeefab9b2d12015-10-14 11:33:11 -07002562
Steve Antondcc3c022017-12-22 16:02:54 -08002563 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002564 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002565 for (size_t i = 0; i < new_streams->count(); ++i) {
2566 MediaStreamInterface* new_stream = new_streams->at(i);
2567 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002568 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002569 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2570 }
deadbeefab9b2d12015-10-14 11:33:11 -07002571
Steve Antondcc3c022017-12-22 16:02:54 -08002572 UpdateEndedRemoteMediaStreams();
2573 }
deadbeefab9b2d12015-10-14 11:33:11 -07002574
Steve Anton8a006912017-12-04 15:25:56 -08002575 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002576}
2577
Steve Anton0f5400a2018-07-17 14:25:36 -07002578void PeerConnection::ProcessRemovalOfRemoteTrack(
2579 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2580 transceiver,
2581 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2582 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2583 RTC_DCHECK(transceiver->mid());
2584 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2585 << *transceiver->mid();
2586 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2587 transceiver->internal()->receiver_internal()->streams();
2588 // This will remove the remote track from the streams.
2589 transceiver->internal()->receiver_internal()->set_stream_ids({});
2590 remove_list->push_back(transceiver);
2591 // Remove any streams that no longer have tracks.
2592 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2593 // of streams, see if the stream was removed by checking if this was the
2594 // last receiver with that stream ID.
2595 for (auto stream : media_streams) {
2596 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2597 remote_streams_->RemoveStream(stream);
2598 removed_streams->push_back(stream);
2599 }
2600 }
2601}
2602
Steve Antondcc3c022017-12-22 16:02:54 -08002603RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2604 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002605 const SessionDescriptionInterface& new_session,
2606 const SessionDescriptionInterface* old_local_description,
2607 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002608 RTC_DCHECK(IsUnifiedPlan());
2609
Steve Anton7464fca2018-01-19 11:10:37 -08002610 const cricket::ContentGroup* bundle_group = nullptr;
2611 if (new_session.GetType() == SdpType::kOffer) {
2612 auto bundle_group_or_error =
2613 GetEarlyBundleGroup(*new_session.description());
2614 if (!bundle_group_or_error.ok()) {
2615 return bundle_group_or_error.MoveError();
2616 }
2617 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002618 }
Steve Antondcc3c022017-12-22 16:02:54 -08002619
Steve Antondcc3c022017-12-22 16:02:54 -08002620 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002621 for (size_t i = 0; i < new_contents.size(); ++i) {
2622 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002623 cricket::MediaType media_type = new_content.media_description()->type();
2624 seen_mids_.insert(new_content.name);
2625 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2626 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002627 const cricket::ContentInfo* old_local_content = nullptr;
2628 if (old_local_description &&
2629 i < old_local_description->description()->contents().size()) {
2630 old_local_content =
2631 &old_local_description->description()->contents()[i];
2632 }
2633 const cricket::ContentInfo* old_remote_content = nullptr;
2634 if (old_remote_description &&
2635 i < old_remote_description->description()->contents().size()) {
2636 old_remote_content =
2637 &old_remote_description->description()->contents()[i];
2638 }
Steve Antondcc3c022017-12-22 16:02:54 -08002639 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002640 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2641 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002642 if (!transceiver_or_error.ok()) {
2643 return transceiver_or_error.MoveError();
2644 }
2645 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002646 RTCError error =
2647 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2648 if (!error.ok()) {
2649 return error;
2650 }
2651 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002652 if (GetDataMid() && new_content.name != *GetDataMid()) {
2653 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002654 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2655 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002656 continue;
2657 }
2658 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2659 if (!error.ok()) {
2660 return error;
2661 }
Steve Antondcc3c022017-12-22 16:02:54 -08002662 } else {
2663 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2664 "Unknown section type.");
2665 }
2666 }
2667
2668 return RTCError::OK();
2669}
2670
2671RTCError PeerConnection::UpdateTransceiverChannel(
2672 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2673 transceiver,
2674 const cricket::ContentInfo& content,
2675 const cricket::ContentGroup* bundle_group) {
2676 RTC_DCHECK(IsUnifiedPlan());
2677 RTC_DCHECK(transceiver);
2678 cricket::BaseChannel* channel = transceiver->internal()->channel();
2679 if (content.rejected) {
2680 if (channel) {
2681 transceiver->internal()->SetChannel(nullptr);
2682 DestroyBaseChannel(channel);
2683 }
2684 } else {
2685 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002686 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002687 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002688 } else {
Steve Anton69470252018-02-09 11:43:08 -08002689 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002690 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002691 }
2692 if (!channel) {
2693 LOG_AND_RETURN_ERROR(
2694 RTCErrorType::INTERNAL_ERROR,
2695 "Failed to create channel for mid=" + content.name);
2696 }
2697 transceiver->internal()->SetChannel(channel);
2698 }
2699 }
2700 return RTCError::OK();
2701}
2702
Steve Antonfa2260d2017-12-28 16:38:23 -08002703RTCError PeerConnection::UpdateDataChannel(
2704 cricket::ContentSource source,
2705 const cricket::ContentInfo& content,
2706 const cricket::ContentGroup* bundle_group) {
2707 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002708 // If data channels are disabled, ignore this media section. CreateAnswer
2709 // will take care of rejecting it.
2710 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002711 }
2712 if (content.rejected) {
2713 DestroyDataChannel();
2714 } else {
2715 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002716 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002717 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2718 "Failed to create data channel.");
2719 }
2720 }
2721 if (source == cricket::CS_REMOTE) {
2722 const MediaContentDescription* data_desc = content.media_description();
2723 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2724 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2725 }
2726 }
2727 }
2728 return RTCError::OK();
2729}
2730
Steve Antondcc3c022017-12-22 16:02:54 -08002731RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2732PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002733 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002734 size_t mline_index,
2735 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002736 const ContentInfo* old_local_content,
2737 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002738 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002739 // If this is an offer then the m= section might be recycled. If the m=
2740 // section is being recycled (defined as: rejected in the current local or
2741 // remote description and not rejected in new description), dissociate the
2742 // currently associated RtpTransceiver by setting its mid property to null,
2743 // and discard the mapping between the transceiver and its m= section index.
2744 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2745 old_remote_content)) {
2746 // We want to dissociate the transceiver that has the rejected mid.
2747 const std::string& old_mid =
2748 (old_local_content && old_local_content->rejected)
2749 ? old_local_content->name
2750 : old_remote_content->name;
2751 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002752 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002753 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2754 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002755 old_transceiver->internal()->set_mid(absl::nullopt);
2756 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002757 }
2758 }
2759 const MediaContentDescription* media_desc = content.media_description();
2760 auto transceiver = GetAssociatedTransceiver(content.name);
2761 if (source == cricket::CS_LOCAL) {
2762 // Find the RtpTransceiver that corresponds to this m= section, using the
2763 // mapping between transceivers and m= section indices established when
2764 // creating the offer.
2765 if (!transceiver) {
2766 transceiver = GetTransceiverByMLineIndex(mline_index);
2767 }
2768 if (!transceiver) {
2769 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2770 "Unknown transceiver");
2771 }
2772 } else {
2773 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2774 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2775 // of the same type...
2776 if (!transceiver &&
2777 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2778 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2779 }
2780 // If no RtpTransceiver was found in the previous step, create one with a
2781 // recvonly direction.
2782 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002783 RTC_LOG(LS_INFO) << "Adding "
2784 << cricket::MediaTypeToString(media_desc->type())
2785 << " transceiver for MID=" << content.name
2786 << " at i=" << mline_index
2787 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002788 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002789 auto sender =
2790 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002791 std::string receiver_id;
2792 if (!media_desc->streams().empty()) {
2793 receiver_id = media_desc->streams()[0].id;
2794 } else {
2795 receiver_id = rtc::CreateRandomUuid();
2796 }
2797 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002798 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002799 transceiver->internal()->set_direction(
2800 RtpTransceiverDirection::kRecvOnly);
2801 }
2802 }
2803 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002804 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002805 LOG_AND_RETURN_ERROR(
2806 RTCErrorType::INVALID_PARAMETER,
2807 "Transceiver type does not match media description type.");
2808 }
2809 // Associate the found or created RtpTransceiver with the m= section by
2810 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2811 // section, and establish a mapping between the transceiver and the index of
2812 // the m= section.
2813 transceiver->internal()->set_mid(content.name);
2814 transceiver->internal()->set_mline_index(mline_index);
2815 return std::move(transceiver);
2816}
2817
2818rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2819PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2820 RTC_DCHECK(IsUnifiedPlan());
2821 for (auto transceiver : transceivers_) {
2822 if (transceiver->mid() == mid) {
2823 return transceiver;
2824 }
2825 }
2826 return nullptr;
2827}
2828
2829rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2830PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2831 RTC_DCHECK(IsUnifiedPlan());
2832 for (auto transceiver : transceivers_) {
2833 if (transceiver->internal()->mline_index() == mline_index) {
2834 return transceiver;
2835 }
2836 }
2837 return nullptr;
2838}
2839
2840rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2841PeerConnection::FindAvailableTransceiverToReceive(
2842 cricket::MediaType media_type) const {
2843 RTC_DCHECK(IsUnifiedPlan());
2844 // From JSEP section 5.10 (Applying a Remote Description):
2845 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2846 // the same type that were added to the PeerConnection by addTrack and are not
2847 // associated with any m= section and are not stopped, find the first such
2848 // RtpTransceiver.
2849 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002850 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002851 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2852 !transceiver->stopped()) {
2853 return transceiver;
2854 }
2855 }
2856 return nullptr;
2857}
2858
Steve Antoned10bd92017-12-05 10:52:59 -08002859const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2860 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2861 transceiver,
2862 const SessionDescriptionInterface* sdesc) const {
2863 RTC_DCHECK(transceiver);
2864 RTC_DCHECK(sdesc);
2865 if (IsUnifiedPlan()) {
2866 if (!transceiver->internal()->mid()) {
2867 // This transceiver is not associated with a media section yet.
2868 return nullptr;
2869 }
2870 return sdesc->description()->GetContentByName(
2871 *transceiver->internal()->mid());
2872 } else {
2873 // Plan B only allows at most one audio and one video section, so use the
2874 // first media section of that type.
2875 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002876 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002877 }
2878}
2879
deadbeef46c73892016-11-16 19:42:04 -08002880PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2881 return configuration_;
2882}
2883
deadbeef293e9262017-01-11 12:28:30 -08002884bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2885 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002886 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002887 if (IsClosed()) {
2888 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2889 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2890 }
2891
Qingsi Wanga2d60672018-04-11 16:57:45 -07002892 // According to JSEP, after setLocalDescription, changing the candidate pool
2893 // size is not allowed, and changing the set of ICE servers will not result
2894 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002895 if (local_description() && configuration.ice_candidate_pool_size !=
2896 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002897 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2898 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002899 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002900 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002901
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002902 if (local_description() &&
2903 configuration.use_media_transport != configuration_.use_media_transport) {
2904 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2905 "SetLocalDescription.";
2906 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2907 }
2908
2909 if (remote_description() &&
2910 configuration.use_media_transport != configuration_.use_media_transport) {
2911 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2912 "SetRemoteDescription.";
2913 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2914 }
2915
deadbeef293e9262017-01-11 12:28:30 -08002916 // The simplest (and most future-compatible) way to tell if the config was
2917 // modified in an invalid way is to copy each property we do support
2918 // modifying, then use operator==. There are far more properties we don't
2919 // support modifying than those we do, and more could be added.
2920 RTCConfiguration modified_config = configuration_;
2921 modified_config.servers = configuration.servers;
2922 modified_config.type = configuration.type;
2923 modified_config.ice_candidate_pool_size =
2924 configuration.ice_candidate_pool_size;
2925 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002926 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002927 modified_config.ice_check_interval_strong_connectivity =
2928 configuration.ice_check_interval_strong_connectivity;
2929 modified_config.ice_check_interval_weak_connectivity =
2930 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002931 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2932 modified_config.ice_unwritable_min_checks =
2933 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002934 modified_config.stun_candidate_keepalive_interval =
2935 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002936 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002937 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002938 modified_config.active_reset_srtp_params =
2939 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002940 modified_config.use_media_transport = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08002941 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002942 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002943 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2944 }
2945
Steve Anton038834f2017-07-14 15:59:59 -07002946 // Validate the modified configuration.
2947 RTCError validate_error = ValidateConfiguration(modified_config);
2948 if (!validate_error.ok()) {
2949 return SafeSetError(std::move(validate_error), error);
2950 }
2951
deadbeef293e9262017-01-11 12:28:30 -08002952 // Note that this isn't possible through chromium, since it's an unsigned
2953 // short in WebIDL.
2954 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002955 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002956 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2957 }
2958
2959 // Parse ICE servers before hopping to network thread.
2960 cricket::ServerAddresses stun_servers;
2961 std::vector<cricket::RelayServerConfig> turn_servers;
2962 RTCErrorType parse_error =
2963 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2964 if (parse_error != RTCErrorType::NONE) {
2965 return SafeSetError(parse_error, error);
2966 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002967 // Note if STUN or TURN servers were supplied.
2968 if (!stun_servers.empty()) {
2969 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2970 }
2971 if (!turn_servers.empty()) {
2972 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2973 }
deadbeef293e9262017-01-11 12:28:30 -08002974
2975 // In theory this shouldn't fail.
2976 if (!network_thread()->Invoke<bool>(
2977 RTC_FROM_HERE,
2978 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2979 stun_servers, turn_servers, modified_config.type,
2980 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002981 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002982 modified_config.turn_customizer,
2983 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002984 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002985 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2986 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002987
deadbeefd1a38b52016-12-10 13:15:33 -08002988 // As described in JSEP, calling setConfiguration with new ICE servers or
2989 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2990 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002991 if (modified_config.servers != configuration_.servers ||
2992 modified_config.type != configuration_.type ||
2993 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002994 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002995 }
skvladd1f5fda2017-02-03 16:54:05 -08002996
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002997 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07002998 transport_controller_->SetMediaTransportFactory(
2999 modified_config.use_media_transport ? factory_->media_transport_factory()
3000 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003001
Zhi Huangb57e1692018-06-12 11:41:11 -07003002 if (configuration_.active_reset_srtp_params !=
3003 modified_config.active_reset_srtp_params) {
3004 transport_controller_->SetActiveResetSrtpParams(
3005 modified_config.active_reset_srtp_params);
3006 }
3007
deadbeef293e9262017-01-11 12:28:30 -08003008 configuration_ = modified_config;
3009 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003010}
3011
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003012bool PeerConnection::AddIceCandidate(
3013 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003014 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003015 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003016 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003017 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003018 return false;
3019 }
Steve Antond25da372017-11-06 14:50:29 -08003020
3021 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003022 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003023 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003024 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003025 return false;
3026 }
3027
3028 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003029 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003030 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003031 return false;
3032 }
3033
3034 bool valid = false;
3035 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3036 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003037 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003038 return false;
3039 }
3040
3041 // Add this candidate to the remote session description.
3042 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003043 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003044 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003045 return false;
3046 }
3047
3048 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003049 bool result = UseCandidate(ice_candidate);
3050 if (result) {
3051 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3052 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3053 } else {
3054 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3055 }
3056 return result;
Steve Antond25da372017-11-06 14:50:29 -08003057 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003058 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003059 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003060 return true;
3061 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003062}
3063
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003064bool PeerConnection::RemoveIceCandidates(
3065 const std::vector<cricket::Candidate>& candidates) {
3066 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003067 if (IsClosed()) {
3068 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3069 return false;
3070 }
3071
Steve Antond25da372017-11-06 14:50:29 -08003072 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003073 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3074 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003075 return false;
3076 }
3077
3078 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003079 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003080 return false;
3081 }
3082
3083 size_t number_removed =
3084 mutable_remote_description()->RemoveCandidates(candidates);
3085 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003086 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003087 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003088 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003089 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003090 }
3091
3092 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003093 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3094 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003095 RTC_LOG(LS_ERROR)
3096 << "RemoveIceCandidates: Error when removing remote candidates: "
3097 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003098 }
3099 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003100}
3101
Niels Möller0c4f7be2018-05-07 14:01:37 +02003102RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003103 if (!worker_thread()->IsCurrent()) {
3104 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003105 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003106 }
3107
Niels Möller0c4f7be2018-05-07 14:01:37 +02003108 const bool has_min = bitrate.min_bitrate_bps.has_value();
3109 const bool has_start = bitrate.start_bitrate_bps.has_value();
3110 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003111 if (has_min && *bitrate.min_bitrate_bps < 0) {
3112 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3113 "min_bitrate_bps <= 0");
3114 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003115 if (has_start) {
3116 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003117 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003118 "start_bitrate_bps < min_bitrate_bps");
3119 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003120 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3121 "curent_bitrate_bps < 0");
3122 }
3123 }
3124 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003125 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003126 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003127 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003128 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3129 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3130 "max_bitrate_bps < min_bitrate_bps");
3131 } else if (*bitrate.max_bitrate_bps < 0) {
3132 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3133 "max_bitrate_bps < 0");
3134 }
3135 }
3136
zstein4b979802017-06-02 14:37:37 -07003137 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003138 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003139
3140 return RTCError::OK();
3141}
3142
Alex Narest78609d52017-10-20 10:37:47 +02003143void PeerConnection::SetBitrateAllocationStrategy(
3144 std::unique_ptr<rtc::BitrateAllocationStrategy>
3145 bitrate_allocation_strategy) {
3146 rtc::Thread* worker_thread = factory_->worker_thread();
3147 if (!worker_thread->IsCurrent()) {
3148 rtc::BitrateAllocationStrategy* strategy_raw =
3149 bitrate_allocation_strategy.release();
3150 auto functor = [this, strategy_raw]() {
3151 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003152 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003153 };
3154 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3155 return;
3156 }
3157 RTC_DCHECK(call_.get());
3158 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3159}
3160
henrika5f6bf242017-11-01 11:06:56 +01003161void PeerConnection::SetAudioPlayout(bool playout) {
3162 if (!worker_thread()->IsCurrent()) {
3163 worker_thread()->Invoke<void>(
3164 RTC_FROM_HERE,
3165 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3166 return;
3167 }
3168 auto audio_state =
3169 factory_->channel_manager()->media_engine()->GetAudioState();
3170 audio_state->SetPlayout(playout);
3171}
3172
3173void PeerConnection::SetAudioRecording(bool recording) {
3174 if (!worker_thread()->IsCurrent()) {
3175 worker_thread()->Invoke<void>(
3176 RTC_FROM_HERE,
3177 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3178 return;
3179 }
3180 auto audio_state =
3181 factory_->channel_manager()->media_engine()->GetAudioState();
3182 audio_state->SetRecording(recording);
3183}
3184
Steve Anton8c0f7a72017-10-03 10:03:10 -07003185std::unique_ptr<rtc::SSLCertificate>
3186PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003187 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3188 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003189 return nullptr;
3190 }
Steve Antonf25303e2018-10-16 15:23:31 -07003191 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003192}
3193
Zhi Huang70b820f2018-01-27 14:16:15 -08003194std::unique_ptr<rtc::SSLCertChain>
3195PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003196 auto audio_transceiver = GetFirstAudioTransceiver();
3197 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003198 return nullptr;
3199 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003200 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003201 audio_transceiver->internal()->channel()->transport_name());
3202}
3203
3204rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3205PeerConnection::GetFirstAudioTransceiver() const {
3206 for (auto transceiver : transceivers_) {
3207 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3208 return transceiver;
3209 }
3210 }
3211 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003212}
3213
ivoc14d5dbe2016-07-04 07:06:55 -07003214bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3215 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003216 // TODO(eladalon): It would be better to not allow negative values into PC.
3217 const size_t max_size = (max_size_bytes < 0)
3218 ? RtcEventLog::kUnlimitedOutput
3219 : rtc::saturated_cast<size_t>(max_size_bytes);
3220 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003221 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003222 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003223}
3224
Bjorn Tereliusde939432017-11-20 17:38:14 +01003225bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3226 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003227 // TODO(eladalon): In C++14, this can be done with a lambda.
3228 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003229 bool operator()() {
3230 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3231 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003232 PeerConnection* const pc;
3233 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003234 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003235 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003236 return worker_thread()->Invoke<bool>(
3237 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003238}
3239
3240void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003241 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003242 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3243}
3244
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003245const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003246 return pending_local_description_ ? pending_local_description_.get()
3247 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003248}
3249
3250const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003251 return pending_remote_description_ ? pending_remote_description_.get()
3252 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003253}
3254
deadbeeffe4a8a42016-12-20 17:56:17 -08003255const SessionDescriptionInterface* PeerConnection::current_local_description()
3256 const {
Steve Anton75737c02017-11-06 10:37:17 -08003257 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003258}
3259
3260const SessionDescriptionInterface* PeerConnection::current_remote_description()
3261 const {
Steve Anton75737c02017-11-06 10:37:17 -08003262 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003263}
3264
3265const SessionDescriptionInterface* PeerConnection::pending_local_description()
3266 const {
Steve Anton75737c02017-11-06 10:37:17 -08003267 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003268}
3269
3270const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3271 const {
Steve Anton75737c02017-11-06 10:37:17 -08003272 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003273}
3274
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003275void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003276 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003277 // Update stats here so that we have the most recent stats for tracks and
3278 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003279 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003280
Steve Anton75737c02017-11-06 10:37:17 -08003281 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003282 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003283
Steve Anton8af21862017-12-15 11:20:13 -08003284 for (auto transceiver : transceivers_) {
3285 transceiver->Stop();
3286 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003287
3288 // Ensure that all asynchronous stats requests are completed before destroying
3289 // the transport controller below.
3290 if (stats_collector_) {
3291 stats_collector_->WaitForPendingRequest();
3292 }
3293
3294 // Don't destroy BaseChannels until after stats has been cleaned up so that
3295 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003296 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003297
Qingsi Wang93a84392018-01-30 17:13:09 -08003298 // The event log is used in the transport controller, which must be outlived
3299 // by the former. CreateOffer by the peer connection is implemented
3300 // asynchronously and if the peer connection is closed without resetting the
3301 // WebRTC session description factory, the session description factory would
3302 // call the transport controller.
3303 webrtc_session_desc_factory_.reset();
3304 transport_controller_.reset();
3305
deadbeef42a42632017-03-10 15:18:00 -08003306 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003307 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3308 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003309
Steve Anton978b8762017-09-29 12:15:02 -07003310 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003311 call_.reset();
3312 // The event log must outlive call (and any other object that uses it).
3313 event_log_.reset();
3314 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003315 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003316 // The .h file says that observer can be discarded after close() returns.
3317 // Make sure this is true.
3318 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003319}
3320
Steve Antonad182762018-09-05 20:22:40 +00003321void PeerConnection::OnMessage(rtc::Message* msg) {
3322 switch (msg->message_id) {
3323 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3324 SetSessionDescriptionMsg* param =
3325 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3326 param->observer->OnSuccess();
3327 delete param;
3328 break;
3329 }
3330 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3331 SetSessionDescriptionMsg* param =
3332 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3333 param->observer->OnFailure(std::move(param->error));
3334 delete param;
3335 break;
3336 }
3337 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3338 CreateSessionDescriptionMsg* param =
3339 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3340 param->observer->OnFailure(std::move(param->error));
3341 delete param;
3342 break;
3343 }
3344 case MSG_GETSTATS: {
3345 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3346 StatsReports reports;
3347 stats_->GetStats(param->track, &reports);
3348 param->observer->OnComplete(reports);
3349 delete param;
3350 break;
3351 }
3352 case MSG_FREE_DATACHANNELS: {
3353 sctp_data_channels_to_free_.clear();
3354 break;
3355 }
3356 case MSG_REPORT_USAGE_PATTERN: {
3357 ReportUsagePattern();
3358 break;
3359 }
3360 default:
3361 RTC_NOTREACHED() << "Not implemented";
3362 break;
3363 }
3364}
3365
Steve Antonafb0bb72018-02-20 11:35:37 -08003366cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3367 RTC_DCHECK(!IsUnifiedPlan());
3368 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3369 GetAudioTransceiver()->internal()->channel());
3370 if (voice_channel) {
3371 return voice_channel->media_channel();
3372 } else {
3373 return nullptr;
3374 }
3375}
3376
3377cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3378 RTC_DCHECK(!IsUnifiedPlan());
3379 auto* video_channel = static_cast<cricket::VideoChannel*>(
3380 GetVideoTransceiver()->internal()->channel());
3381 if (video_channel) {
3382 return video_channel->media_channel();
3383 } else {
3384 return nullptr;
3385 }
3386}
3387
Steve Anton4171afb2017-11-20 10:20:22 -08003388void PeerConnection::CreateAudioReceiver(
3389 MediaStreamInterface* stream,
3390 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003391 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3392 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003393 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3394 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003395 auto* audio_receiver = new AudioRtpReceiver(
3396 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003397 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003398 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3399 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3400 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003401 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003402 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003403 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003404}
3405
Steve Anton4171afb2017-11-20 10:20:22 -08003406void PeerConnection::CreateVideoReceiver(
3407 MediaStreamInterface* stream,
3408 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003409 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3410 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003411 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3412 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003413 auto* video_receiver = new VideoRtpReceiver(
3414 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003415 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003416 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3417 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3418 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003419 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003420 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003421 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003422}
3423
deadbeef70ab1a12015-09-28 16:53:55 -07003424// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3425// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003426rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003427 const RtpSenderInfo& remote_sender_info) {
3428 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3429 if (!receiver) {
3430 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3431 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003432 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003433 }
Steve Anton4171afb2017-11-20 10:20:22 -08003434 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3435 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3436 } else {
3437 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3438 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003439 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003440}
3441
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003442void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3443 MediaStreamInterface* stream) {
3444 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003445 RTC_DCHECK(track);
3446 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003447 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003448 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003449 // We already have a sender for this track, so just change the stream_id
3450 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003451 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003452 return;
3453 }
3454
3455 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003456 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003457 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003458 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003459 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003460 // If the sender has already been configured in SDP, we call SetSsrc,
3461 // which will connect the sender to the underlying transport. This can
3462 // occur if a local session description that contains the ID of the sender
3463 // is set before AddStream is called. It can also occur if the local
3464 // session description is not changed and RemoveStream is called, and
3465 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003466 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003467 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003468 if (sender_info) {
3469 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003470 }
3471}
3472
3473// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3474// indefinitely, when we have unified plan SDP.
3475void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3476 MediaStreamInterface* stream) {
3477 RTC_DCHECK(!IsClosed());
3478 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003479 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003480 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3481 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003482 return;
3483 }
Steve Anton4171afb2017-11-20 10:20:22 -08003484 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003485}
3486
3487void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3488 MediaStreamInterface* stream) {
3489 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003490 RTC_DCHECK(track);
3491 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003492 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003493 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003494 // We already have a sender for this track, so just change the stream_id
3495 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003496 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003497 return;
3498 }
3499
3500 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003501 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003502 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003503 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003504 GetVideoTransceiver()->internal()->AddSender(new_sender);
3505 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003506 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003507 if (sender_info) {
3508 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003509 }
3510}
3511
3512void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3513 MediaStreamInterface* stream) {
3514 RTC_DCHECK(!IsClosed());
3515 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003516 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003517 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3518 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003519 return;
3520 }
Steve Anton4171afb2017-11-20 10:20:22 -08003521 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003522}
3523
Steve Antonba818672017-11-06 10:21:57 -08003524void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003525 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003526 if (ice_connection_state_ == new_state) {
3527 return;
3528 }
3529
deadbeefcbecd352015-09-23 11:50:27 -07003530 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003531 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003532 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003533 return;
3534 }
Steve Antonba818672017-11-06 10:21:57 -08003535
Mirko Bonadei675513b2017-11-09 11:09:25 +01003536 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3537 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003538 RTC_DCHECK(ice_connection_state_ !=
3539 PeerConnectionInterface::kIceConnectionClosed);
3540
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003541 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003542 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003543}
3544
Jonas Olsson635474e2018-10-18 15:58:17 +02003545void PeerConnection::SetStandardizedIceConnectionState(
3546 PeerConnectionInterface::IceConnectionState new_state) {
3547 RTC_DCHECK(signaling_thread()->IsCurrent());
3548 if (standardized_ice_connection_state_ == new_state)
3549 return;
3550 if (IsClosed())
3551 return;
3552 standardized_ice_connection_state_ = new_state;
3553 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3554 // the old one once disconnects are handled properly.
3555}
3556
3557void PeerConnection::SetConnectionState(
3558 PeerConnectionInterface::PeerConnectionState new_state) {
3559 RTC_DCHECK(signaling_thread()->IsCurrent());
3560 if (connection_state_ == new_state)
3561 return;
3562 if (IsClosed())
3563 return;
3564 connection_state_ = new_state;
3565 Observer()->OnConnectionChange(new_state);
3566}
3567
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003568void PeerConnection::OnIceGatheringChange(
3569 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003570 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003571 if (IsClosed()) {
3572 return;
3573 }
3574 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003575 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003576}
3577
jbauch81bf7b02017-03-25 08:31:12 -07003578void PeerConnection::OnIceCandidate(
3579 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003580 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003581 if (IsClosed()) {
3582 return;
3583 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003584 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003585 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3586 candidate->candidate().address().IsPrivateIP()) {
3587 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3588 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003589 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003590}
3591
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003592void PeerConnection::OnIceCandidatesRemoved(
3593 const std::vector<cricket::Candidate>& candidates) {
3594 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003595 if (IsClosed()) {
3596 return;
3597 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003598 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003599}
3600
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003601void PeerConnection::ChangeSignalingState(
3602 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003603 RTC_DCHECK(signaling_thread()->IsCurrent());
3604 if (signaling_state_ == signaling_state) {
3605 return;
3606 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003607 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3608 << GetSignalingStateString(signaling_state_)
3609 << " New state: "
3610 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003611 signaling_state_ = signaling_state;
3612 if (signaling_state == kClosed) {
3613 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003614 Observer()->OnIceConnectionChange(ice_connection_state_);
Jonas Olsson635474e2018-10-18 15:58:17 +02003615 standardized_ice_connection_state_ =
3616 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
3617 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3618 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003619 if (ice_gathering_state_ != kIceGatheringComplete) {
3620 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003621 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003622 }
3623 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003624 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003625}
3626
deadbeefeb459812015-12-15 19:24:43 -08003627void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3628 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003629 if (IsClosed()) {
3630 return;
3631 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003632 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003633 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003634}
3635
deadbeefeb459812015-12-15 19:24:43 -08003636void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3637 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003638 if (IsClosed()) {
3639 return;
3640 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003641 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003642 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003643}
3644
3645void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3646 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003647 if (IsClosed()) {
3648 return;
3649 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003650 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003651 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003652}
3653
3654void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3655 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003656 if (IsClosed()) {
3657 return;
3658 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003659 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003660 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003661}
3662
Henrik Boström31638672017-11-23 17:48:32 +01003663void PeerConnection::PostSetSessionDescriptionSuccess(
3664 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003665 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3666 signaling_thread()->Post(RTC_FROM_HERE, this,
3667 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003668}
3669
deadbeefab9b2d12015-10-14 11:33:11 -07003670void PeerConnection::PostSetSessionDescriptionFailure(
3671 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003672 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003673 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003674 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3675 msg->error = std::move(error);
3676 signaling_thread()->Post(RTC_FROM_HERE, this,
3677 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003678}
3679
3680void PeerConnection::PostCreateSessionDescriptionFailure(
3681 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003682 RTCError error) {
3683 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003684 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3685 msg->error = std::move(error);
3686 signaling_thread()->Post(RTC_FROM_HERE, this,
3687 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003688}
3689
zhihuang1c378ed2017-08-17 14:10:50 -07003690void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003691 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003692 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003693 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003694
Steve Antondcc3c022017-12-22 16:02:54 -08003695 if (IsUnifiedPlan()) {
3696 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3697 } else {
3698 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3699 }
3700
Steve Antonfa2260d2017-12-28 16:38:23 -08003701 // Intentionally unset the data channel type for RTP data channel with the
3702 // second condition. Otherwise the RTP data channels would be successfully
3703 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3704 // when building with chromium. We want to leave RTP data channels broken, so
3705 // people won't try to use them.
3706 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3707 session_options->data_channel_type = data_channel_type();
3708 }
3709
Steve Antondcc3c022017-12-22 16:02:54 -08003710 // Apply ICE restart flag and renomination flag.
3711 for (auto& options : session_options->media_description_options) {
3712 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3713 options.transport_options.enable_ice_renomination =
3714 configuration_.enable_ice_renomination;
3715 }
3716
3717 session_options->rtcp_cname = rtcp_cname_;
3718 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003719 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003720 session_options->pooled_ice_credentials =
3721 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3722 RTC_FROM_HERE,
3723 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3724 port_allocator_.get()));
Steve Antondcc3c022017-12-22 16:02:54 -08003725}
3726
3727void PeerConnection::GetOptionsForPlanBOffer(
3728 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3729 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003730 // Figure out transceiver directional preferences.
3731 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3732 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3733
3734 // By default, generate sendrecv/recvonly m= sections.
3735 bool recv_audio = true;
3736 bool recv_video = true;
3737
3738 // By default, only offer a new m= section if we have media to send with it.
3739 bool offer_new_audio_description = send_audio;
3740 bool offer_new_video_description = send_video;
3741 bool offer_new_data_description = HasDataChannels();
3742
3743 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003744 if (offer_answer_options.offer_to_receive_audio !=
3745 RTCOfferAnswerOptions::kUndefined) {
3746 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003747 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003748 offer_new_audio_description ||
3749 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003750 }
Steve Antondcc3c022017-12-22 16:02:54 -08003751 if (offer_answer_options.offer_to_receive_video !=
3752 RTCOfferAnswerOptions::kUndefined) {
3753 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003754 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003755 offer_new_video_description ||
3756 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003757 }
3758
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003759 absl::optional<size_t> audio_index;
3760 absl::optional<size_t> video_index;
3761 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003762 // If a current description exists, generate m= sections in the same order,
3763 // using the first audio/video/data section that appears and rejecting
3764 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003765 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003766 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003767 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003768 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3769 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3770 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003771 }
3772
zhihuang1c378ed2017-08-17 14:10:50 -07003773 // Add audio/video/data m= sections to the end if needed.
3774 if (!audio_index && offer_new_audio_description) {
3775 session_options->media_description_options.push_back(
3776 cricket::MediaDescriptionOptions(
3777 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003778 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3779 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003780 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003781 }
zhihuang1c378ed2017-08-17 14:10:50 -07003782 if (!video_index && offer_new_video_description) {
3783 session_options->media_description_options.push_back(
3784 cricket::MediaDescriptionOptions(
3785 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003786 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3787 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003788 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003789 }
zhihuang1c378ed2017-08-17 14:10:50 -07003790 if (!data_index && offer_new_data_description) {
3791 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003792 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003793 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003794 }
3795
3796 cricket::MediaDescriptionOptions* audio_media_description_options =
3797 !audio_index ? nullptr
3798 : &session_options->media_description_options[*audio_index];
3799 cricket::MediaDescriptionOptions* video_media_description_options =
3800 !video_index ? nullptr
3801 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003802
Steve Anton4171afb2017-11-20 10:20:22 -08003803 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003804 video_media_description_options,
3805 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003806}
3807
3808// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3809// and return a reference to it.
3810// Generated MIDs should be no more than 3 bytes long to take up less space in
3811// the RTP packet.
3812static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3813 RTC_DCHECK(used_mids);
3814 // We're boring: just generate MIDs 0, 1, 2, ...
3815 size_t i = 0;
3816 std::set<std::string>::iterator it;
3817 bool inserted;
3818 do {
3819 std::string mid = rtc::ToString(i++);
3820 auto insert_result = used_mids->insert(mid);
3821 it = insert_result.first;
3822 inserted = insert_result.second;
3823 } while (!inserted);
3824 return *it;
3825}
3826
3827static cricket::MediaDescriptionOptions
3828GetMediaDescriptionOptionsForTransceiver(
3829 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3830 transceiver,
3831 const std::string& mid) {
3832 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003833 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003834 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003835 // This behavior is specified in JSEP. The gist is that:
3836 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3837 // sendrecv.
3838 // 2. If the MSID is included, then it must be included in any subsequent
3839 // offer/answer exactly the same until the RtpTransceiver is stopped.
3840 if (!transceiver->stopped() &&
3841 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3842 transceiver->internal()->has_ever_been_used_to_send())) {
3843 cricket::SenderOptions sender_options;
3844 sender_options.track_id = transceiver->sender()->id();
3845 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003846 int num_send_encoding_layers =
3847 transceiver->sender()->init_send_encodings().size();
3848 sender_options.num_sim_layers =
3849 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003850 media_description_options.sender_options.push_back(sender_options);
3851 }
Steve Antondcc3c022017-12-22 16:02:54 -08003852 return media_description_options;
3853}
3854
3855void PeerConnection::GetOptionsForUnifiedPlanOffer(
3856 const RTCOfferAnswerOptions& offer_answer_options,
3857 cricket::MediaSessionOptions* session_options) {
3858 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3859 // Offers) and 5.2.2 (Subsequent Offers).
3860 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3861 const ContentInfos& local_contents =
3862 (local_description() ? local_description()->description()->contents()
3863 : ContentInfos());
3864 const ContentInfos& remote_contents =
3865 (remote_description() ? remote_description()->description()->contents()
3866 : ContentInfos());
3867 // The mline indices that can be recycled. New transceivers should reuse these
3868 // slots first.
3869 std::queue<size_t> recycleable_mline_indices;
3870 // Track the MIDs used in previous offer/answer exchanges and the current
3871 // offer so that new, unique MIDs are generated.
3872 std::set<std::string> used_mids = seen_mids_;
3873 // First, go through each media section that exists in either the local or
3874 // remote description and generate a media section in this offer for the
3875 // associated transceiver. If a media section can be recycled, generate a
3876 // default, rejected media section here that can be later overwritten.
3877 for (size_t i = 0;
3878 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3879 // Either |local_content| or |remote_content| is non-null.
3880 const ContentInfo* local_content =
3881 (i < local_contents.size() ? &local_contents[i] : nullptr);
3882 const ContentInfo* remote_content =
3883 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3884 bool had_been_rejected = (local_content && local_content->rejected) ||
3885 (remote_content && remote_content->rejected);
3886 const std::string& mid =
3887 (local_content ? local_content->name : remote_content->name);
3888 cricket::MediaType media_type =
3889 (local_content ? local_content->media_description()->type()
3890 : remote_content->media_description()->type());
3891 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3892 media_type == cricket::MEDIA_TYPE_VIDEO) {
3893 auto transceiver = GetAssociatedTransceiver(mid);
3894 RTC_CHECK(transceiver);
3895 // A media section is considered eligible for recycling if it is marked as
3896 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003897 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003898 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003899 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3900 RtpTransceiverDirection::kInactive,
3901 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003902 recycleable_mline_indices.push(i);
3903 } else {
3904 session_options->media_description_options.push_back(
3905 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3906 // CreateOffer shouldn't really cause any state changes in
3907 // PeerConnection, but we need a way to match new transceivers to new
3908 // media sections in SetLocalDescription and JSEP specifies this is done
3909 // by recording the index of the media section generated for the
3910 // transceiver in the offer.
3911 transceiver->internal()->set_mline_index(i);
3912 }
3913 } else {
3914 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003915 RTC_CHECK(GetDataMid());
3916 if (had_been_rejected || mid != *GetDataMid()) {
3917 session_options->media_description_options.push_back(
3918 GetMediaDescriptionOptionsForRejectedData(mid));
3919 } else {
3920 session_options->media_description_options.push_back(
3921 GetMediaDescriptionOptionsForActiveData(mid));
3922 }
Steve Antondcc3c022017-12-22 16:02:54 -08003923 }
3924 }
3925 // Next, look for transceivers that are newly added (that is, are not stopped
3926 // and not associated). Reuse media sections marked as recyclable first,
3927 // otherwise append to the end of the offer. New media sections should be
3928 // added in the order they were added to the PeerConnection.
3929 for (auto transceiver : transceivers_) {
3930 if (transceiver->mid() || transceiver->stopped()) {
3931 continue;
3932 }
3933 size_t mline_index;
3934 if (!recycleable_mline_indices.empty()) {
3935 mline_index = recycleable_mline_indices.front();
3936 recycleable_mline_indices.pop();
3937 session_options->media_description_options[mline_index] =
3938 GetMediaDescriptionOptionsForTransceiver(transceiver,
3939 AllocateMid(&used_mids));
3940 } else {
3941 mline_index = session_options->media_description_options.size();
3942 session_options->media_description_options.push_back(
3943 GetMediaDescriptionOptionsForTransceiver(transceiver,
3944 AllocateMid(&used_mids)));
3945 }
3946 // See comment above for why CreateOffer changes the transceiver's state.
3947 transceiver->internal()->set_mline_index(mline_index);
3948 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003949 // Lastly, add a m-section if we have local data channels and an m section
3950 // does not already exist.
3951 if (!GetDataMid() && HasDataChannels()) {
3952 session_options->media_description_options.push_back(
3953 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3954 }
Steve Antondcc3c022017-12-22 16:02:54 -08003955}
3956
3957void PeerConnection::GetOptionsForAnswer(
3958 const RTCOfferAnswerOptions& offer_answer_options,
3959 cricket::MediaSessionOptions* session_options) {
3960 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3961
3962 if (IsUnifiedPlan()) {
3963 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3964 } else {
3965 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3966 }
3967
Steve Antonfa2260d2017-12-28 16:38:23 -08003968 // Intentionally unset the data channel type for RTP data channel. Otherwise
3969 // the RTP data channels would be successfully negotiated by default and the
3970 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3971 // We want to leave RTP data channels broken, so people won't try to use them.
3972 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3973 session_options->data_channel_type = data_channel_type();
3974 }
3975
Steve Antondcc3c022017-12-22 16:02:54 -08003976 // Apply ICE renomination flag.
3977 for (auto& options : session_options->media_description_options) {
3978 options.transport_options.enable_ice_renomination =
3979 configuration_.enable_ice_renomination;
3980 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003981
3982 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003983 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003984 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003985 session_options->pooled_ice_credentials =
3986 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3987 RTC_FROM_HERE,
3988 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3989 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07003990}
3991
Steve Antondcc3c022017-12-22 16:02:54 -08003992void PeerConnection::GetOptionsForPlanBAnswer(
3993 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003994 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003995 // Figure out transceiver directional preferences.
3996 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3997 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3998
3999 // By default, generate sendrecv/recvonly m= sections. The direction is also
4000 // restricted by the direction in the offer.
4001 bool recv_audio = true;
4002 bool recv_video = true;
4003
4004 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004005 if (offer_answer_options.offer_to_receive_audio !=
4006 RTCOfferAnswerOptions::kUndefined) {
4007 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004008 }
Steve Antondcc3c022017-12-22 16:02:54 -08004009 if (offer_answer_options.offer_to_receive_video !=
4010 RTCOfferAnswerOptions::kUndefined) {
4011 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004012 }
4013
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004014 absl::optional<size_t> audio_index;
4015 absl::optional<size_t> video_index;
4016 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004017
4018 // Generate m= sections that match those in the offer.
4019 // Note that mediasession.cc will handle intersection our preferred
4020 // direction with the offered direction.
4021 GenerateMediaDescriptionOptions(
4022 remote_description(),
4023 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4024 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4025 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004026
4027 cricket::MediaDescriptionOptions* audio_media_description_options =
4028 !audio_index ? nullptr
4029 : &session_options->media_description_options[*audio_index];
4030 cricket::MediaDescriptionOptions* video_media_description_options =
4031 !video_index ? nullptr
4032 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004033
Steve Anton4171afb2017-11-20 10:20:22 -08004034 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004035 video_media_description_options,
4036 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004037}
zhihuangaf388472016-11-02 16:49:48 -07004038
Steve Antondcc3c022017-12-22 16:02:54 -08004039void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4040 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4041 cricket::MediaSessionOptions* session_options) {
4042 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4043 // Answers) and 5.3.2 (Subsequent Answers).
4044 RTC_DCHECK(remote_description());
4045 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4046 for (const ContentInfo& content :
4047 remote_description()->description()->contents()) {
4048 cricket::MediaType media_type = content.media_description()->type();
4049 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4050 media_type == cricket::MEDIA_TYPE_VIDEO) {
4051 auto transceiver = GetAssociatedTransceiver(content.name);
4052 RTC_CHECK(transceiver);
4053 session_options->media_description_options.push_back(
4054 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4055 } else {
4056 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004057 // Reject all data sections if data channels are disabled.
4058 // Reject a data section if it has already been rejected.
4059 // Reject all data sections except for the first one.
4060 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4061 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004062 session_options->media_description_options.push_back(
4063 GetMediaDescriptionOptionsForRejectedData(content.name));
4064 } else {
4065 session_options->media_description_options.push_back(
4066 GetMediaDescriptionOptionsForActiveData(content.name));
4067 }
Steve Antondcc3c022017-12-22 16:02:54 -08004068 }
4069 }
htaa2a49d92016-03-04 02:51:39 -08004070}
4071
zhihuang1c378ed2017-08-17 14:10:50 -07004072void PeerConnection::GenerateMediaDescriptionOptions(
4073 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004074 RtpTransceiverDirection audio_direction,
4075 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004076 absl::optional<size_t>* audio_index,
4077 absl::optional<size_t>* video_index,
4078 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004079 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004080 for (const cricket::ContentInfo& content :
4081 session_desc->description()->contents()) {
4082 if (IsAudioContent(&content)) {
4083 // If we already have an audio m= section, reject this extra one.
4084 if (*audio_index) {
4085 session_options->media_description_options.push_back(
4086 cricket::MediaDescriptionOptions(
4087 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004088 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004089 } else {
4090 session_options->media_description_options.push_back(
4091 cricket::MediaDescriptionOptions(
4092 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004093 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004094 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004095 }
4096 } else if (IsVideoContent(&content)) {
4097 // If we already have an video m= section, reject this extra one.
4098 if (*video_index) {
4099 session_options->media_description_options.push_back(
4100 cricket::MediaDescriptionOptions(
4101 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004102 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004103 } else {
4104 session_options->media_description_options.push_back(
4105 cricket::MediaDescriptionOptions(
4106 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004107 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004108 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004109 }
4110 } else {
4111 RTC_DCHECK(IsDataContent(&content));
4112 // If we already have an data m= section, reject this extra one.
4113 if (*data_index) {
4114 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004115 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004116 } else {
4117 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004118 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004119 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004120 }
4121 }
htaa2a49d92016-03-04 02:51:39 -08004122 }
deadbeefab9b2d12015-10-14 11:33:11 -07004123}
4124
Steve Antonfa2260d2017-12-28 16:38:23 -08004125cricket::MediaDescriptionOptions
4126PeerConnection::GetMediaDescriptionOptionsForActiveData(
4127 const std::string& mid) const {
4128 // Direction for data sections is meaningless, but legacy endpoints might
4129 // expect sendrecv.
4130 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4131 RtpTransceiverDirection::kSendRecv,
4132 /*stopped=*/false);
4133 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4134 return options;
4135}
4136
4137cricket::MediaDescriptionOptions
4138PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4139 const std::string& mid) const {
4140 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4141 RtpTransceiverDirection::kInactive,
4142 /*stopped=*/true);
4143 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4144 return options;
4145}
4146
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004147absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004148 switch (data_channel_type_) {
4149 case cricket::DCT_RTP:
4150 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004151 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004152 }
4153 return rtp_data_channel_->content_name();
4154 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004155 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004156 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004157 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004158 }
4159}
4160
Steve Anton4171afb2017-11-20 10:20:22 -08004161void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4162 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4163 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004164 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004165}
4166
Steve Anton4171afb2017-11-20 10:20:22 -08004167void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004168 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004169 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004170 cricket::MediaType media_type,
4171 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004172 RTC_DCHECK(!IsUnifiedPlan());
4173
Steve Anton4171afb2017-11-20 10:20:22 -08004174 std::vector<RtpSenderInfo>* current_senders =
4175 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004176
Steve Anton4171afb2017-11-20 10:20:22 -08004177 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004178 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004179 for (auto sender_it = current_senders->begin();
4180 sender_it != current_senders->end();
4181 /* incremented manually */) {
4182 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004183 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004184 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004185 std::string params_stream_id;
4186 if (params) {
4187 params_stream_id =
4188 (!params->first_stream_id().empty() ? params->first_stream_id()
4189 : kDefaultStreamId);
4190 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004191 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004192 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004193 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004194 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004195 sender_exists) {
4196 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004197 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004198 OnRemoteSenderRemoved(info, media_type);
4199 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004200 }
4201 }
4202
Steve Anton4171afb2017-11-20 10:20:22 -08004203 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004204 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004205 if (!params.has_ssrcs()) {
4206 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4207 // sender, this means it is coming from a Unified Plan endpoint,so we just
4208 // create a default.
4209 default_sender_needed = true;
4210 break;
4211 }
4212
Seth Hampson845e8782018-03-02 11:34:10 -08004213 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004214 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004215 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4216 // not supported in Plan B, we just take the first here and create the
4217 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004218 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004219 (!params.first_stream_id().empty() ? params.first_stream_id()
4220 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004221 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004222 uint32_t ssrc = params.first_ssrc();
4223
4224 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004225 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004226 if (!stream) {
4227 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004228 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004229 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004230 remote_streams_->AddStream(stream);
4231 new_streams->AddStream(stream);
4232 }
4233
Steve Anton4171afb2017-11-20 10:20:22 -08004234 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004235 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004236 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004237 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004238 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004239 }
4240 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004241
Steve Anton4171afb2017-11-20 10:20:22 -08004242 // Add default sender if necessary.
4243 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004244 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004245 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004246 if (!default_stream) {
4247 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004248 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004249 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004250 remote_streams_->AddStream(default_stream);
4251 new_streams->AddStream(default_stream);
4252 }
Steve Anton4171afb2017-11-20 10:20:22 -08004253 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4254 ? kDefaultAudioSenderId
4255 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004256 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004257 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004258 if (!default_sender_info) {
4259 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004260 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004261 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004262 }
4263 }
deadbeefab9b2d12015-10-14 11:33:11 -07004264}
4265
Steve Anton4171afb2017-11-20 10:20:22 -08004266void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4267 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004268 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4269 << " receiver for track_id=" << sender_info.sender_id
4270 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004271
Steve Anton3d954a62018-04-02 11:27:23 -07004272 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004273 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004274 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004275 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004276 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004277 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004278 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004279 }
4280}
4281
Steve Anton4171afb2017-11-20 10:20:22 -08004282void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4283 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004284 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4285 << " receiver for track_id=" << sender_info.sender_id
4286 << " and stream_id=" << sender_info.stream_id;
4287
Seth Hampson845e8782018-03-02 11:34:10 -08004288 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004289
Henrik Boström933d8b02017-10-10 10:05:16 -07004290 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004291 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004292 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4293 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004294 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004295 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004296 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004297 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004298 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004299 }
4300 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004301 // Stopping or destroying a VideoRtpReceiver will end the
4302 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004303 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004304 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004305 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004306 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004307 // There's no guarantee the track is still available, e.g. the track may
4308 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004309 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004310 }
4311 } else {
nisseede5da42017-01-12 05:15:36 -08004312 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004313 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004314 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004315 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004316 }
deadbeefab9b2d12015-10-14 11:33:11 -07004317}
4318
4319void PeerConnection::UpdateEndedRemoteMediaStreams() {
4320 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4321 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4322 MediaStreamInterface* stream = remote_streams_->at(i);
4323 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4324 streams_to_remove.push_back(stream);
4325 }
4326 }
4327
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004328 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004329 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004330 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004331 }
4332}
4333
Steve Anton4171afb2017-11-20 10:20:22 -08004334void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004335 const std::vector<cricket::StreamParams>& streams,
4336 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004337 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004338
Seth Hampson845e8782018-03-02 11:34:10 -08004339 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004340 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004341 for (auto sender_it = current_senders->begin();
4342 sender_it != current_senders->end();
4343 /* incremented manually */) {
4344 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004345 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004346 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4347 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004348 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004349 OnLocalSenderRemoved(info, media_type);
4350 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004351 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004352 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004353 }
4354 }
4355
Steve Anton4171afb2017-11-20 10:20:22 -08004356 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004357 for (const cricket::StreamParams& params : streams) {
4358 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004359 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004360 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004361 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004362 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004363 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004364 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004365 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004366 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004367 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004368 }
4369 }
4370}
4371
Steve Anton4171afb2017-11-20 10:20:22 -08004372void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4373 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004374 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004375 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004376 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004377 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4378 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004379 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004380 return;
4381 }
4382
deadbeeffac06552015-11-25 11:26:01 -08004383 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004384 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004385 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004386 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004387 }
deadbeeffac06552015-11-25 11:26:01 -08004388
Seth Hampson5b4f0752018-04-02 16:31:36 -07004389 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004390 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004391}
4392
Steve Anton4171afb2017-11-20 10:20:22 -08004393void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4394 cricket::MediaType media_type) {
4395 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004396 if (!sender) {
4397 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004398 // SessionDescriptions has been renegotiated.
4399 return;
4400 }
deadbeeffac06552015-11-25 11:26:01 -08004401
4402 // A sender has been removed from the SessionDescription but it's still
4403 // associated with the PeerConnection. This only occurs if the SDP doesn't
4404 // match with the calls to CreateSender, AddStream and RemoveStream.
4405 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004406 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004407 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004408 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004409 }
deadbeeffac06552015-11-25 11:26:01 -08004410
Steve Anton4171afb2017-11-20 10:20:22 -08004411 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004412}
4413
4414void PeerConnection::UpdateLocalRtpDataChannels(
4415 const cricket::StreamParamsVec& streams) {
4416 std::vector<std::string> existing_channels;
4417
4418 // Find new and active data channels.
4419 for (const cricket::StreamParams& params : streams) {
4420 // |it->sync_label| is actually the data channel label. The reason is that
4421 // we use the same naming of data channels as we do for
4422 // MediaStreams and Tracks.
4423 // For MediaStreams, the sync_label is the MediaStream label and the
4424 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004425 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004426 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004427 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004428 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004429 continue;
4430 }
4431 // Set the SSRC the data channel should use for sending.
4432 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4433 existing_channels.push_back(data_channel_it->first);
4434 }
4435
4436 UpdateClosingRtpDataChannels(existing_channels, true);
4437}
4438
4439void PeerConnection::UpdateRemoteRtpDataChannels(
4440 const cricket::StreamParamsVec& streams) {
4441 std::vector<std::string> existing_channels;
4442
4443 // Find new and active data channels.
4444 for (const cricket::StreamParams& params : streams) {
4445 // The data channel label is either the mslabel or the SSRC if the mslabel
4446 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004447 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004448 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004449 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004450 auto data_channel_it = rtp_data_channels_.find(label);
4451 if (data_channel_it == rtp_data_channels_.end()) {
4452 // This is a new data channel.
4453 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4454 } else {
4455 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4456 }
4457 existing_channels.push_back(label);
4458 }
4459
4460 UpdateClosingRtpDataChannels(existing_channels, false);
4461}
4462
4463void PeerConnection::UpdateClosingRtpDataChannels(
4464 const std::vector<std::string>& active_channels,
4465 bool is_local_update) {
4466 auto it = rtp_data_channels_.begin();
4467 while (it != rtp_data_channels_.end()) {
4468 DataChannel* data_channel = it->second;
4469 if (std::find(active_channels.begin(), active_channels.end(),
4470 data_channel->label()) != active_channels.end()) {
4471 ++it;
4472 continue;
4473 }
4474
4475 if (is_local_update) {
4476 data_channel->SetSendSsrc(0);
4477 } else {
4478 data_channel->RemotePeerRequestClose();
4479 }
4480
4481 if (data_channel->state() == DataChannel::kClosed) {
4482 rtp_data_channels_.erase(it);
4483 it = rtp_data_channels_.begin();
4484 } else {
4485 ++it;
4486 }
4487 }
4488}
4489
4490void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4491 uint32_t remote_ssrc) {
4492 rtc::scoped_refptr<DataChannel> channel(
4493 InternalCreateDataChannel(label, nullptr));
4494 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004495 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004496 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004497 return;
4498 }
4499 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004500 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4501 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004502 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004503}
4504
4505rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4506 const std::string& label,
4507 const InternalDataChannelInit* config) {
4508 if (IsClosed()) {
4509 return nullptr;
4510 }
Steve Anton75737c02017-11-06 10:37:17 -08004511 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004512 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004513 << "InternalCreateDataChannel: Data is not supported in this call.";
4514 return nullptr;
4515 }
4516 InternalDataChannelInit new_config =
4517 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004518 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004519 if (new_config.id < 0) {
4520 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004521 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004522 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004523 RTC_LOG(LS_ERROR)
4524 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004525 return nullptr;
4526 }
4527 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004528 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004529 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004530 return nullptr;
4531 }
4532 }
4533
Steve Anton75737c02017-11-06 10:37:17 -08004534 rtc::scoped_refptr<DataChannel> channel(
4535 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004536 if (!channel) {
4537 sid_allocator_.ReleaseSid(new_config.id);
4538 return nullptr;
4539 }
4540
4541 if (channel->data_channel_type() == cricket::DCT_RTP) {
4542 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004543 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4544 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004545 return nullptr;
4546 }
4547 rtp_data_channels_[channel->label()] = channel;
4548 } else {
4549 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4550 sctp_data_channels_.push_back(channel);
4551 channel->SignalClosed.connect(this,
4552 &PeerConnection::OnSctpDataChannelClosed);
4553 }
4554
Steve Anton2d8609c2018-01-23 16:38:46 -08004555 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004556 return channel;
4557}
4558
4559bool PeerConnection::HasDataChannels() const {
4560 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4561}
4562
4563void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4564 for (const auto& channel : sctp_data_channels_) {
4565 if (channel->id() < 0) {
4566 int sid;
4567 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004568 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004569 continue;
4570 }
4571 channel->SetSctpSid(sid);
4572 }
4573 }
4574}
4575
4576void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004577 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004578 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4579 ++it) {
4580 if (it->get() == channel) {
4581 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004582 // After the closing procedure is done, it's safe to use this ID for
4583 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004584 sid_allocator_.ReleaseSid(channel->id());
4585 }
deadbeefbd292462015-12-14 18:15:29 -08004586 // Since this method is triggered by a signal from the DataChannel,
4587 // we can't free it directly here; we need to free it asynchronously.
4588 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004589 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004590 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4591 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004592 return;
4593 }
4594 }
4595}
4596
deadbeefab9b2d12015-10-14 11:33:11 -07004597void PeerConnection::OnDataChannelDestroyed() {
4598 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4599 // DataChannel may callback to us and try to modify the list.
4600 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4601 temp_rtp_dcs.swap(rtp_data_channels_);
4602 for (const auto& kv : temp_rtp_dcs) {
4603 kv.second->OnTransportChannelDestroyed();
4604 }
4605
4606 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4607 temp_sctp_dcs.swap(sctp_data_channels_);
4608 for (const auto& channel : temp_sctp_dcs) {
4609 channel->OnTransportChannelDestroyed();
4610 }
4611}
4612
4613void PeerConnection::OnDataChannelOpenMessage(
4614 const std::string& label,
4615 const InternalDataChannelInit& config) {
4616 rtc::scoped_refptr<DataChannel> channel(
4617 InternalCreateDataChannel(label, &config));
4618 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004619 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004620 return;
4621 }
4622
deadbeefa601f5c2016-06-06 14:27:39 -07004623 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4624 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004625 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004626 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004627}
4628
Steve Anton4171afb2017-11-20 10:20:22 -08004629rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4630PeerConnection::GetAudioTransceiver() const {
4631 // This method only works with Plan B SDP, where there is a single
4632 // audio/video transceiver.
4633 RTC_DCHECK(!IsUnifiedPlan());
4634 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004635 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004636 return transceiver;
4637 }
4638 }
4639 RTC_NOTREACHED();
4640 return nullptr;
4641}
4642
4643rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4644PeerConnection::GetVideoTransceiver() const {
4645 // This method only works with Plan B SDP, where there is a single
4646 // audio/video transceiver.
4647 RTC_DCHECK(!IsUnifiedPlan());
4648 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004649 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004650 return transceiver;
4651 }
4652 }
4653 RTC_NOTREACHED();
4654 return nullptr;
4655}
4656
4657// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4658// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004659bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004660 switch (type) {
4661 case cricket::MEDIA_TYPE_AUDIO:
4662 return !GetAudioTransceiver()->internal()->senders().empty();
4663 case cricket::MEDIA_TYPE_VIDEO:
4664 return !GetVideoTransceiver()->internal()->senders().empty();
4665 case cricket::MEDIA_TYPE_DATA:
4666 return false;
4667 }
4668 RTC_NOTREACHED();
4669 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004670}
4671
Steve Anton4171afb2017-11-20 10:20:22 -08004672rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4673PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4674 for (auto transceiver : transceivers_) {
4675 for (auto sender : transceiver->internal()->senders()) {
4676 if (sender->track() == track) {
4677 return sender;
4678 }
4679 }
4680 }
4681 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004682}
4683
Steve Anton4171afb2017-11-20 10:20:22 -08004684rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4685PeerConnection::FindSenderById(const std::string& sender_id) const {
4686 for (auto transceiver : transceivers_) {
4687 for (auto sender : transceiver->internal()->senders()) {
4688 if (sender->id() == sender_id) {
4689 return sender;
4690 }
4691 }
4692 }
4693 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004694}
4695
Steve Anton4171afb2017-11-20 10:20:22 -08004696rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4697PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4698 for (auto transceiver : transceivers_) {
4699 for (auto receiver : transceiver->internal()->receivers()) {
4700 if (receiver->id() == receiver_id) {
4701 return receiver;
4702 }
4703 }
4704 }
4705 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004706}
4707
Steve Anton4171afb2017-11-20 10:20:22 -08004708std::vector<PeerConnection::RtpSenderInfo>*
4709PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4710 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4711 media_type == cricket::MEDIA_TYPE_VIDEO);
4712 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4713 ? &remote_audio_sender_infos_
4714 : &remote_video_sender_infos_;
4715}
4716
4717std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004718 cricket::MediaType media_type) {
4719 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4720 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004721 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4722 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004723}
4724
Steve Anton4171afb2017-11-20 10:20:22 -08004725const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4726 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004727 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004728 const std::string sender_id) const {
4729 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004730 if (sender_info.stream_id == stream_id &&
4731 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004732 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004733 }
4734 }
4735 return nullptr;
4736}
4737
4738DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4739 for (const auto& channel : sctp_data_channels_) {
4740 if (channel->id() == sid) {
4741 return channel;
4742 }
4743 }
4744 return nullptr;
4745}
4746
deadbeef91dd5672016-05-18 16:55:30 -07004747bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004748 const cricket::ServerAddresses& stun_servers,
4749 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004750 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004751 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004752 // To handle both internal and externally created port allocator, we will
4753 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004754 port_allocator_flags_ = port_allocator_->flags();
4755 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4756 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4757 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004758 // If the disable-IPv6 flag was specified, we'll not override it
4759 // by experiment.
4760 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004761 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004762 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4763 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004764 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004765 }
4766
zhihuangb09b3f92017-03-07 14:40:51 -08004767 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004768 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004769 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004770 }
4771
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004772 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004773 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004774 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004775 }
4776
honghaiz60347052016-05-31 18:29:12 -07004777 if (configuration.candidate_network_policy ==
4778 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004779 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004780 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004781 }
4782
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004783 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004784 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004785 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4786 }
4787
Qingsi Wanga2d60672018-04-11 16:57:45 -07004788 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004789 // No step delay is used while allocating ports.
4790 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4791 port_allocator_->set_candidate_filter(
4792 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004793 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004794
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004795 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004796 for (auto& turn_server : turn_servers_copy) {
4797 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004798 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004799 // Call this last since it may create pooled allocator sessions using the
4800 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004801 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004802 stun_servers, std::move(turn_servers_copy),
4803 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4804 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004805 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004806 return true;
4807}
4808
deadbeef91dd5672016-05-18 16:55:30 -07004809bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004810 const cricket::ServerAddresses& stun_servers,
4811 const std::vector<cricket::RelayServerConfig>& turn_servers,
4812 IceTransportsType type,
4813 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004814 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004815 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004816 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004817 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004818 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004819 // According to JSEP, after setLocalDescription, changing the candidate pool
4820 // size is not allowed, and changing the set of ICE servers will not result
4821 // in new candidates being gathered.
4822 if (local_description()) {
4823 port_allocator_->FreezeCandidatePool();
4824 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004825 // Add the custom tls turn servers if they exist.
4826 auto turn_servers_copy = turn_servers;
4827 for (auto& turn_server : turn_servers_copy) {
4828 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4829 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004830 // Call this last since it may create pooled allocator sessions using the
4831 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004832 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004833 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4834 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004835}
4836
Steve Antonba818672017-11-06 10:21:57 -08004837cricket::ChannelManager* PeerConnection::channel_manager() const {
4838 return factory_->channel_manager();
4839}
4840
Elad Alon99c3fe52017-10-13 16:29:40 +02004841bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004842 std::unique_ptr<RtcEventLogOutput> output,
4843 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004844 if (!event_log_) {
4845 return false;
4846 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004847 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004848}
4849
4850void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004851 if (event_log_) {
4852 event_log_->StopLogging();
4853 }
ivoc14d5dbe2016-07-04 07:06:55 -07004854}
nisseeaabdf62017-05-05 02:23:02 -07004855
Steve Anton75737c02017-11-06 10:37:17 -08004856cricket::BaseChannel* PeerConnection::GetChannel(
4857 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004858 for (auto transceiver : transceivers_) {
4859 cricket::BaseChannel* channel = transceiver->internal()->channel();
4860 if (channel && channel->content_name() == content_name) {
4861 return channel;
4862 }
Steve Anton75737c02017-11-06 10:37:17 -08004863 }
4864 if (rtp_data_channel() &&
4865 rtp_data_channel()->content_name() == content_name) {
4866 return rtp_data_channel();
4867 }
4868 return nullptr;
4869}
4870
4871bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4872 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004873 RTC_LOG(LS_INFO)
4874 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004875 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004876 return false;
4877 }
4878 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004879 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004880 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004881 return false;
4882 }
4883
Zhi Huange830e682018-03-30 10:48:35 -07004884 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4885 if (dtls_role) {
4886 *role = *dtls_role;
4887 return true;
4888 }
4889 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004890}
4891
4892bool PeerConnection::GetSslRole(const std::string& content_name,
4893 rtc::SSLRole* role) {
4894 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004895 RTC_LOG(LS_INFO)
4896 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004897 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004898 return false;
4899 }
4900
Zhi Huange830e682018-03-30 10:48:35 -07004901 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4902 if (dtls_role) {
4903 *role = *dtls_role;
4904 return true;
4905 }
4906 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004907}
4908
Steve Antonf8470812017-12-04 10:46:21 -08004909void PeerConnection::SetSessionError(SessionError error,
4910 const std::string& error_desc) {
4911 RTC_DCHECK_RUN_ON(signaling_thread());
4912 if (error != session_error_) {
4913 session_error_ = error;
4914 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004915 }
4916}
4917
Zhi Huange830e682018-03-30 10:48:35 -07004918RTCError PeerConnection::UpdateSessionState(
4919 SdpType type,
4920 cricket::ContentSource source,
4921 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004922 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004923
4924 // If there's already a pending error then no state transition should happen.
4925 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004926 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004927
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004928 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004929 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004930 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004931 }
4932
4933 // Update the signaling state according to the specified state machine (see
4934 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004935 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004936 ChangeSignalingState(source == cricket::CS_LOCAL
4937 ? PeerConnectionInterface::kHaveLocalOffer
4938 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004939 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004940 ChangeSignalingState(source == cricket::CS_LOCAL
4941 ? PeerConnectionInterface::kHaveLocalPrAnswer
4942 : PeerConnectionInterface::kHaveRemotePrAnswer);
4943 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004944 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004945 ChangeSignalingState(PeerConnectionInterface::kStable);
4946 }
4947
4948 // Update internal objects according to the session description's media
4949 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004950 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004951 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004952 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004953 }
4954
Steve Anton8a006912017-12-04 15:25:56 -08004955 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004956}
4957
Steve Anton8a006912017-12-04 15:25:56 -08004958RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004959 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004960 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004961 const SessionDescriptionInterface* sdesc =
4962 (source == cricket::CS_LOCAL ? local_description()
4963 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004964 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004965
4966 // Push down the new SDP media section for each audio/video transceiver.
4967 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004968 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004969 FindMediaSectionForTransceiver(transceiver, sdesc);
4970 cricket::BaseChannel* channel = transceiver->internal()->channel();
4971 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004972 continue;
4973 }
4974 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004975 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004976 if (!content_desc) {
4977 continue;
4978 }
4979 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004980 bool success = (source == cricket::CS_LOCAL)
4981 ? channel->SetLocalContent(content_desc, type, &error)
4982 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004983 if (!success) {
4984 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4985 }
4986 }
4987
4988 // If using the RtpDataChannel, push down the new SDP section for it too.
4989 if (rtp_data_channel_) {
4990 const ContentInfo* data_content =
4991 cricket::GetFirstDataContent(sdesc->description());
4992 if (data_content && !data_content->rejected) {
4993 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004994 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004995 if (data_desc) {
4996 std::string error;
4997 bool success =
4998 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004999 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005000 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005001 if (!success) {
5002 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5003 std::move(error));
5004 }
Steve Anton75737c02017-11-06 10:37:17 -08005005 }
5006 }
5007 }
Steve Antoned10bd92017-12-05 10:52:59 -08005008
Steve Anton75737c02017-11-06 10:37:17 -08005009 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5010 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5011 if (sctp_transport_ && local_description() && remote_description() &&
5012 cricket::GetFirstDataContent(local_description()->description()) &&
5013 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005014 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005015 RTC_FROM_HERE,
5016 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005017 if (!success) {
5018 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5019 "Failed to push down SCTP parameters.");
5020 }
Steve Anton75737c02017-11-06 10:37:17 -08005021 }
Steve Antoned10bd92017-12-05 10:52:59 -08005022
Steve Anton8a006912017-12-04 15:25:56 -08005023 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005024}
5025
5026bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5027 RTC_DCHECK(network_thread()->IsCurrent());
5028 RTC_DCHECK(local_description());
5029 RTC_DCHECK(remote_description());
5030 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5031 // When we support "max-message-size", that would also be pushed down here.
5032 return sctp_transport_->Start(
5033 GetSctpPort(local_description()->description()),
5034 GetSctpPort(remote_description()->description()));
5035}
5036
Steve Anton8a006912017-12-04 15:25:56 -08005037RTCError PeerConnection::PushdownTransportDescription(
5038 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005039 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005040 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005041
Zhi Huange830e682018-03-30 10:48:35 -07005042 if (source == cricket::CS_LOCAL) {
5043 const SessionDescriptionInterface* sdesc = local_description();
5044 RTC_DCHECK(sdesc);
5045 return transport_controller_->SetLocalDescription(type,
5046 sdesc->description());
5047 } else {
5048 const SessionDescriptionInterface* sdesc = remote_description();
5049 RTC_DCHECK(sdesc);
5050 return transport_controller_->SetRemoteDescription(type,
5051 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005052 }
Steve Anton75737c02017-11-06 10:37:17 -08005053}
5054
5055bool PeerConnection::GetTransportDescription(
5056 const SessionDescription* description,
5057 const std::string& content_name,
5058 cricket::TransportDescription* tdesc) {
5059 if (!description || !tdesc) {
5060 return false;
5061 }
5062 const TransportInfo* transport_info =
5063 description->GetTransportInfoByName(content_name);
5064 if (!transport_info) {
5065 return false;
5066 }
5067 *tdesc = transport_info->description;
5068 return true;
5069}
5070
Steve Anton75737c02017-11-06 10:37:17 -08005071cricket::IceConfig PeerConnection::ParseIceConfig(
5072 const PeerConnectionInterface::RTCConfiguration& config) const {
5073 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005074 switch (config.continual_gathering_policy) {
5075 case PeerConnectionInterface::GATHER_ONCE:
5076 gathering_policy = cricket::GATHER_ONCE;
5077 break;
5078 case PeerConnectionInterface::GATHER_CONTINUALLY:
5079 gathering_policy = cricket::GATHER_CONTINUALLY;
5080 break;
5081 default:
5082 RTC_NOTREACHED();
5083 gathering_policy = cricket::GATHER_ONCE;
5084 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005085
Steve Anton75737c02017-11-06 10:37:17 -08005086 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005087 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5088 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005089 ice_config.prioritize_most_likely_candidate_pairs =
5090 config.prioritize_most_likely_ice_candidate_pairs;
5091 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005092 RTCConfigurationToIceConfigOptionalInt(
5093 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005094 ice_config.continual_gathering_policy = gathering_policy;
5095 ice_config.presume_writable_when_fully_relayed =
5096 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005097 ice_config.ice_check_interval_strong_connectivity =
5098 config.ice_check_interval_strong_connectivity;
5099 ice_config.ice_check_interval_weak_connectivity =
5100 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005101 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005102 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005103 ice_config.regather_all_networks_interval_range =
5104 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005105 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005106 return ice_config;
5107}
5108
Steve Anton75737c02017-11-06 10:37:17 -08005109bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5110 std::string* track_id) {
5111 if (!local_description()) {
5112 return false;
5113 }
5114 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5115 track_id);
5116}
5117
5118bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5119 std::string* track_id) {
5120 if (!remote_description()) {
5121 return false;
5122 }
5123 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5124 track_id);
5125}
5126
5127bool PeerConnection::SendData(const cricket::SendDataParams& params,
5128 const rtc::CopyOnWriteBuffer& payload,
5129 cricket::SendDataResult* result) {
5130 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005131 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005132 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005133 return false;
5134 }
5135 return rtp_data_channel_
5136 ? rtp_data_channel_->SendData(params, payload, result)
5137 : network_thread()->Invoke<bool>(
5138 RTC_FROM_HERE,
5139 Bind(&cricket::SctpTransportInternal::SendData,
5140 sctp_transport_.get(), params, payload, result));
5141}
5142
5143bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5144 if (!rtp_data_channel_ && !sctp_transport_) {
5145 // Don't log an error here, because DataChannels are expected to call
5146 // ConnectDataChannel in this state. It's the only way to initially tell
5147 // whether or not the underlying transport is ready.
5148 return false;
5149 }
5150 if (rtp_data_channel_) {
5151 rtp_data_channel_->SignalReadyToSendData.connect(
5152 webrtc_data_channel, &DataChannel::OnChannelReady);
5153 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5154 &DataChannel::OnDataReceived);
5155 } else {
5156 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5157 &DataChannel::OnChannelReady);
5158 SignalSctpDataReceived.connect(webrtc_data_channel,
5159 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005160 SignalSctpClosingProcedureStartedRemotely.connect(
5161 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5162 SignalSctpClosingProcedureComplete.connect(
5163 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005164 }
5165 return true;
5166}
5167
5168void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5169 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005170 RTC_LOG(LS_ERROR)
5171 << "DisconnectDataChannel called when rtp_data_channel_ and "
5172 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005173 return;
5174 }
5175 if (rtp_data_channel_) {
5176 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5177 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5178 } else {
5179 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5180 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005181 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5182 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005183 }
5184}
5185
5186void PeerConnection::AddSctpDataStream(int sid) {
5187 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005188 RTC_LOG(LS_ERROR)
5189 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005190 return;
5191 }
5192 network_thread()->Invoke<void>(
5193 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5194 sctp_transport_.get(), sid));
5195}
5196
5197void PeerConnection::RemoveSctpDataStream(int sid) {
5198 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005199 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005200 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005201 return;
5202 }
5203 network_thread()->Invoke<void>(
5204 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5205 sctp_transport_.get(), sid));
5206}
5207
5208bool PeerConnection::ReadyToSendData() const {
5209 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5210 sctp_ready_to_send_data_;
5211}
5212
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005213absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005214 if (sctp_mid_ && transport_controller_) {
5215 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5216 if (dtls_transport) {
5217 return dtls_transport->transport_name();
5218 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005219 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005220 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005221 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005222}
5223
Qingsi Wang72a43a12018-02-20 16:03:18 -08005224cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5225 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005226 network_thread()->Invoke<void>(
5227 RTC_FROM_HERE,
5228 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5229 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005230 return candidate_states_list;
5231}
5232
Steve Anton5dfde182018-02-06 10:34:40 -08005233std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5234 const {
5235 std::map<std::string, std::string> transport_names_by_mid;
5236 for (auto transceiver : transceivers_) {
5237 cricket::BaseChannel* channel = transceiver->internal()->channel();
5238 if (channel) {
5239 transport_names_by_mid[channel->content_name()] =
5240 channel->transport_name();
5241 }
Steve Anton75737c02017-11-06 10:37:17 -08005242 }
Steve Anton5dfde182018-02-06 10:34:40 -08005243 if (rtp_data_channel_) {
5244 transport_names_by_mid[rtp_data_channel_->content_name()] =
5245 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005246 }
5247 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005248 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005249 RTC_DCHECK(transport_name);
5250 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005251 }
Steve Anton5dfde182018-02-06 10:34:40 -08005252 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005253}
5254
Steve Anton5dfde182018-02-06 10:34:40 -08005255std::map<std::string, cricket::TransportStats>
5256PeerConnection::GetTransportStatsByNames(
5257 const std::set<std::string>& transport_names) {
5258 if (!network_thread()->IsCurrent()) {
5259 return network_thread()
5260 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5261 RTC_FROM_HERE,
5262 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005263 }
Steve Anton5dfde182018-02-06 10:34:40 -08005264 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5265 for (const std::string& transport_name : transport_names) {
5266 cricket::TransportStats transport_stats;
5267 bool success =
5268 transport_controller_->GetStats(transport_name, &transport_stats);
5269 if (success) {
5270 transport_stats_by_name[transport_name] = std::move(transport_stats);
5271 } else {
5272 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5273 << transport_name;
5274 }
5275 }
5276 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005277}
5278
5279bool PeerConnection::GetLocalCertificate(
5280 const std::string& transport_name,
5281 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005282 if (!certificate) {
5283 return false;
5284 }
5285 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5286 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005287}
5288
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005289std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005290 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005291 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005292}
5293
5294cricket::DataChannelType PeerConnection::data_channel_type() const {
5295 return data_channel_type_;
5296}
5297
5298bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5299 return pending_ice_restarts_.find(content_name) !=
5300 pending_ice_restarts_.end();
5301}
5302
Steve Anton75737c02017-11-06 10:37:17 -08005303bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5304 return transport_controller_->NeedsIceRestart(content_name);
5305}
5306
5307void PeerConnection::OnCertificateReady(
5308 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5309 transport_controller_->SetLocalCertificate(certificate);
5310}
5311
5312void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005313 SetSessionError(SessionError::kTransport,
5314 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005315}
5316
5317void PeerConnection::OnTransportControllerConnectionState(
5318 cricket::IceConnectionState state) {
5319 switch (state) {
5320 case cricket::kIceConnectionConnecting:
5321 // If the current state is Connected or Completed, then there were
5322 // writable channels but now there are not, so the next state must
5323 // be Disconnected.
5324 // kIceConnectionConnecting is currently used as the default,
5325 // un-connected state by the TransportController, so its only use is
5326 // detecting disconnections.
5327 if (ice_connection_state_ ==
5328 PeerConnectionInterface::kIceConnectionConnected ||
5329 ice_connection_state_ ==
5330 PeerConnectionInterface::kIceConnectionCompleted) {
5331 SetIceConnectionState(
5332 PeerConnectionInterface::kIceConnectionDisconnected);
5333 }
5334 break;
5335 case cricket::kIceConnectionFailed:
5336 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5337 break;
5338 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005339 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005340 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005341 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005342 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005343 break;
5344 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005345 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005346 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005347 if (ice_connection_state_ !=
5348 PeerConnectionInterface::kIceConnectionConnected) {
5349 // If jumping directly from "checking" to "connected",
5350 // signal "connected" first.
5351 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5352 }
5353 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005354 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005355 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005356 break;
5357 default:
5358 RTC_NOTREACHED();
5359 }
5360}
5361
5362void PeerConnection::OnTransportControllerCandidatesGathered(
5363 const std::string& transport_name,
5364 const cricket::Candidates& candidates) {
5365 RTC_DCHECK(signaling_thread()->IsCurrent());
5366 int sdp_mline_index;
5367 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005368 RTC_LOG(LS_ERROR)
5369 << "OnTransportControllerCandidatesGathered: content name "
5370 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005371 return;
5372 }
5373
5374 for (cricket::Candidates::const_iterator citer = candidates.begin();
5375 citer != candidates.end(); ++citer) {
5376 // Use transport_name as the candidate media id.
5377 std::unique_ptr<JsepIceCandidate> candidate(
5378 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5379 if (local_description()) {
5380 mutable_local_description()->AddCandidate(candidate.get());
5381 }
5382 OnIceCandidate(std::move(candidate));
5383 }
5384}
5385
5386void PeerConnection::OnTransportControllerCandidatesRemoved(
5387 const std::vector<cricket::Candidate>& candidates) {
5388 RTC_DCHECK(signaling_thread()->IsCurrent());
5389 // Sanity check.
5390 for (const cricket::Candidate& candidate : candidates) {
5391 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005392 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005393 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005394 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005395 return;
5396 }
5397 }
5398
5399 if (local_description()) {
5400 mutable_local_description()->RemoveCandidates(candidates);
5401 }
5402 OnIceCandidatesRemoved(candidates);
5403}
5404
5405void PeerConnection::OnTransportControllerDtlsHandshakeError(
5406 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005407 RTC_HISTOGRAM_ENUMERATION(
5408 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5409 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005410}
5411
Steve Antoned10bd92017-12-05 10:52:59 -08005412void PeerConnection::EnableSending() {
5413 for (auto transceiver : transceivers_) {
5414 cricket::BaseChannel* channel = transceiver->internal()->channel();
5415 if (channel && !channel->enabled()) {
5416 channel->Enable(true);
5417 }
Steve Anton75737c02017-11-06 10:37:17 -08005418 }
5419
Steve Anton4171afb2017-11-20 10:20:22 -08005420 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005421 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005422 }
Steve Anton75737c02017-11-06 10:37:17 -08005423}
5424
5425// Returns the media index for a local ice candidate given the content name.
5426bool PeerConnection::GetLocalCandidateMediaIndex(
5427 const std::string& content_name,
5428 int* sdp_mline_index) {
5429 if (!local_description() || !sdp_mline_index) {
5430 return false;
5431 }
5432
5433 bool content_found = false;
5434 const ContentInfos& contents = local_description()->description()->contents();
5435 for (size_t index = 0; index < contents.size(); ++index) {
5436 if (contents[index].name == content_name) {
5437 *sdp_mline_index = static_cast<int>(index);
5438 content_found = true;
5439 break;
5440 }
5441 }
5442 return content_found;
5443}
5444
5445bool PeerConnection::UseCandidatesInSessionDescription(
5446 const SessionDescriptionInterface* remote_desc) {
5447 if (!remote_desc) {
5448 return true;
5449 }
5450 bool ret = true;
5451
5452 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5453 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5454 for (size_t n = 0; n < candidates->count(); ++n) {
5455 const IceCandidateInterface* candidate = candidates->at(n);
5456 bool valid = false;
5457 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5458 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005459 RTC_LOG(LS_INFO)
5460 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005461 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005462 }
5463 continue;
5464 }
5465 ret = UseCandidate(candidate);
5466 if (!ret) {
5467 break;
5468 }
5469 }
5470 }
5471 return ret;
5472}
5473
5474bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5475 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5476 size_t remote_content_size =
5477 remote_description()->description()->contents().size();
5478 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005479 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005480 return false;
5481 }
5482
5483 cricket::ContentInfo content =
5484 remote_description()->description()->contents()[mediacontent_index];
5485 std::vector<cricket::Candidate> candidates;
5486 candidates.push_back(candidate->candidate());
5487 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005488 RTCError error =
5489 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005490 if (error.ok()) {
5491 // Candidates successfully submitted for checking.
5492 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5493 ice_connection_state_ ==
5494 PeerConnectionInterface::kIceConnectionDisconnected) {
5495 // If state is New, then the session has just gotten its first remote ICE
5496 // candidates, so go to Checking.
5497 // If state is Disconnected, the session is re-using old candidates or
5498 // receiving additional ones, so go to Checking.
5499 // If state is Connected, stay Connected.
5500 // TODO(bemasc): If state is Connected, and the new candidates are for a
5501 // newly added transport, then the state actually _should_ move to
5502 // checking. Add a way to distinguish that case.
5503 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5504 }
5505 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005506 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005507 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005508 }
5509 return true;
5510}
5511
5512void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005513 // Destroy video channel first since it may have a pointer to the
5514 // voice channel.
5515 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005516 if (!video_info || video_info->rejected) {
5517 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005518 }
5519
Steve Anton6fec8802017-12-04 10:37:29 -08005520 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5521 if (!audio_info || audio_info->rejected) {
5522 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005523 }
5524
5525 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5526 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005527 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005528 }
5529}
5530
Steve Antondcc3c022017-12-22 16:02:54 -08005531RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5532 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005533 const cricket::ContentGroup* bundle_group = nullptr;
5534 if (configuration_.bundle_policy ==
5535 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005536 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005537 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005538 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5539 "max-bundle configured but session description "
5540 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005541 }
5542 }
Steve Antondcc3c022017-12-22 16:02:54 -08005543 return std::move(bundle_group);
5544}
5545
5546RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005547 // Creating the media channels. Transports should already have been created
5548 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005549 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005550 if (voice && !voice->rejected &&
5551 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005552 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005553 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005554 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5555 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005556 }
5557 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5558 }
5559
Steve Antondcc3c022017-12-22 16:02:54 -08005560 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005561 if (video && !video->rejected &&
5562 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005563 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005564 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005565 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5566 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005567 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005568 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005569 }
5570
Steve Antondcc3c022017-12-22 16:02:54 -08005571 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005572 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5573 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005574 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005575 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5576 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005577 }
5578 }
5579
Steve Anton8a006912017-12-04 15:25:56 -08005580 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005581}
5582
Steve Anton4171afb2017-11-20 10:20:22 -08005583// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005584cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005585 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005586 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5587 MediaTransportInterface* media_transport = GetMediaTransport(mid);
5588
Steve Anton75737c02017-11-06 10:37:17 -08005589 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005590 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Zhi Huange830e682018-03-30 10:48:35 -07005591 signaling_thread(), mid, SrtpRequired(),
5592 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005593 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005594 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005595 }
Steve Anton75737c02017-11-06 10:37:17 -08005596 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5597 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005598 voice_channel->SignalSentPacket.connect(this,
5599 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005600 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005601
Steve Antoneda6ccd2017-12-04 10:21:55 -08005602 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005603}
5604
Steve Anton4171afb2017-11-20 10:20:22 -08005605// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005606cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005607 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005608 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5609
5610 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005611 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005612 call_.get(), configuration_.media_config, rtp_transport,
5613 signaling_thread(), mid, SrtpRequired(),
5614 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005615 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005616 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005617 }
Steve Anton75737c02017-11-06 10:37:17 -08005618 video_channel->SignalDtlsSrtpSetupFailure.connect(
5619 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005620 video_channel->SignalSentPacket.connect(this,
5621 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005622 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005623
Steve Antoneda6ccd2017-12-04 10:21:55 -08005624 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005625}
5626
Zhi Huange830e682018-03-30 10:48:35 -07005627bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005628 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5629 if (sctp) {
5630 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005631 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005632 << "Trying to create SCTP transport, but didn't compile with "
5633 "SCTP support (HAVE_SCTP)";
5634 return false;
5635 }
5636 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005637 RTC_FROM_HERE,
5638 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005639 return false;
5640 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005641 for (const auto& channel : sctp_data_channels_) {
5642 channel->OnTransportChannelCreated();
5643 }
Steve Anton75737c02017-11-06 10:37:17 -08005644 } else {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005645 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Steve Anton75737c02017-11-06 10:37:17 -08005646 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005647 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5648 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005649 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005650 return false;
5651 }
Steve Anton75737c02017-11-06 10:37:17 -08005652 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5653 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5654 rtp_data_channel_->SignalSentPacket.connect(
5655 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005656 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005657 }
5658
Steve Anton75737c02017-11-06 10:37:17 -08005659 return true;
5660}
5661
5662Call::Stats PeerConnection::GetCallStats() {
5663 if (!worker_thread()->IsCurrent()) {
5664 return worker_thread()->Invoke<Call::Stats>(
5665 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5666 }
5667 if (call_) {
5668 return call_->GetStats();
5669 } else {
5670 return Call::Stats();
5671 }
5672}
5673
Zhi Huange830e682018-03-30 10:48:35 -07005674bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005675 RTC_DCHECK(network_thread()->IsCurrent());
5676 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005677 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005678 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005679 RTC_DCHECK(dtls_transport);
5680 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005681 RTC_DCHECK(sctp_transport_);
5682 sctp_invoker_.reset(new rtc::AsyncInvoker());
5683 sctp_transport_->SignalReadyToSendData.connect(
5684 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5685 sctp_transport_->SignalDataReceived.connect(
5686 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005687 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5688 // another thread. Would be nice if there was a helper class similar to
5689 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5690 // code.
5691 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5692 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5693 sctp_transport_->SignalClosingProcedureComplete.connect(
5694 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005695 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005696 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005697 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005698}
5699
5700void PeerConnection::DestroySctpTransport_n() {
5701 RTC_DCHECK(network_thread()->IsCurrent());
5702 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005703 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005704 sctp_invoker_.reset(nullptr);
5705 sctp_ready_to_send_data_ = false;
5706}
5707
5708void PeerConnection::OnSctpTransportReadyToSendData_n() {
5709 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5710 RTC_DCHECK(network_thread()->IsCurrent());
5711 // Note: Cannot use rtc::Bind here because it will grab a reference to
5712 // PeerConnection and potentially cause PeerConnection to live longer than
5713 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5714 // be destroyed before PeerConnection is destroyed, and at that point all
5715 // pending tasks will be cleared.
5716 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5717 OnSctpTransportReadyToSendData_s(true);
5718 });
5719}
5720
5721void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5722 RTC_DCHECK(signaling_thread()->IsCurrent());
5723 sctp_ready_to_send_data_ = ready;
5724 SignalSctpReadyToSendData(ready);
5725}
5726
5727void PeerConnection::OnSctpTransportDataReceived_n(
5728 const cricket::ReceiveDataParams& params,
5729 const rtc::CopyOnWriteBuffer& payload) {
5730 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5731 RTC_DCHECK(network_thread()->IsCurrent());
5732 // Note: Cannot use rtc::Bind here because it will grab a reference to
5733 // PeerConnection and potentially cause PeerConnection to live longer than
5734 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5735 // be destroyed before PeerConnection is destroyed, and at that point all
5736 // pending tasks will be cleared.
5737 sctp_invoker_->AsyncInvoke<void>(
5738 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5739 OnSctpTransportDataReceived_s(params, payload);
5740 });
5741}
5742
5743void PeerConnection::OnSctpTransportDataReceived_s(
5744 const cricket::ReceiveDataParams& params,
5745 const rtc::CopyOnWriteBuffer& payload) {
5746 RTC_DCHECK(signaling_thread()->IsCurrent());
5747 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5748 // Received OPEN message; parse and signal that a new data channel should
5749 // be created.
5750 std::string label;
5751 InternalDataChannelInit config;
5752 config.id = params.ssrc;
5753 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005754 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5755 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005756 return;
5757 }
5758 config.open_handshake_role = InternalDataChannelInit::kAcker;
5759 OnDataChannelOpenMessage(label, config);
5760 } else {
5761 // Otherwise just forward the signal.
5762 SignalSctpDataReceived(params, payload);
5763 }
5764}
5765
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005766void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005767 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5768 RTC_DCHECK(network_thread()->IsCurrent());
5769 sctp_invoker_->AsyncInvoke<void>(
5770 RTC_FROM_HERE, signaling_thread(),
5771 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005772 &SignalSctpClosingProcedureStartedRemotely, sid));
5773}
5774
5775void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5776 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5777 RTC_DCHECK(network_thread()->IsCurrent());
5778 sctp_invoker_->AsyncInvoke<void>(
5779 RTC_FROM_HERE, signaling_thread(),
5780 rtc::Bind(&sigslot::signal1<int>::operator(),
5781 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005782}
5783
5784// Returns false if bundle is enabled and rtcp_mux is disabled.
5785bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5786 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5787 if (!bundle_enabled)
5788 return true;
5789
5790 const cricket::ContentGroup* bundle_group =
5791 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5792 RTC_DCHECK(bundle_group != NULL);
5793
5794 const cricket::ContentInfos& contents = desc->contents();
5795 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5796 citer != contents.end(); ++citer) {
5797 const cricket::ContentInfo* content = (&*citer);
5798 RTC_DCHECK(content != NULL);
5799 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005800 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005801 if (!HasRtcpMuxEnabled(content))
5802 return false;
5803 }
5804 }
5805 // RTCP-MUX is enabled in all the contents.
5806 return true;
5807}
5808
5809bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005810 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005811}
5812
Steve Anton8a006912017-12-04 15:25:56 -08005813RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005814 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005815 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005816 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005817 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005818 }
5819
5820 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005821 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005822 }
5823
Steve Anton3828c062017-12-06 10:34:51 -08005824 SdpType type = sdesc->GetType();
5825 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5826 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005827 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005828 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005829 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005830 }
5831
5832 // Verify crypto settings.
5833 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005834 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5835 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005836 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005837 if (!crypto_error.ok()) {
5838 return crypto_error;
5839 }
Steve Anton75737c02017-11-06 10:37:17 -08005840 }
5841
5842 // Verify ice-ufrag and ice-pwd.
5843 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005844 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5845 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005846 }
5847
5848 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5850 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005851 }
5852
5853 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5854 // m-lines that do not rtcp-mux enabled.
5855
5856 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005857 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005858 // With an answer we want to compare the new answer session description with
5859 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005860 const cricket::SessionDescription* offer_desc =
5861 (source == cricket::CS_LOCAL) ? remote_description()->description()
5862 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005863 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5864 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5865 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005866 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5867 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005868 }
5869 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005870 // The re-offers should respect the order of m= sections in current
5871 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005872 // With a re-offer, either the current local or current remote descriptions
5873 // could be the most up to date, so we would like to check against both of
5874 // them if they exist. It could be the case that one of them has a 0 port
5875 // for a media section, but the other does not. This is important to check
5876 // against in the case that we are recycling an m= section.
5877 const cricket::SessionDescription* current_desc = nullptr;
5878 const cricket::SessionDescription* secondary_current_desc = nullptr;
5879 if (local_description()) {
5880 current_desc = local_description()->description();
5881 if (remote_description()) {
5882 secondary_current_desc = remote_description()->description();
5883 }
5884 } else if (remote_description()) {
5885 current_desc = remote_description()->description();
5886 }
Steve Anton75737c02017-11-06 10:37:17 -08005887 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005888 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5889 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005890 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5891 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005892 }
5893 }
5894
Steve Antonba42e992018-04-09 14:10:01 -07005895 if (IsUnifiedPlan()) {
5896 // Ensure that each audio and video media section has at most one
5897 // "StreamParams". This will return an error if receiving a session
5898 // description from a "Plan B" endpoint which adds multiple tracks of the
5899 // same type. With Unified Plan, there can only be at most one track per
5900 // media section.
5901 for (const ContentInfo& content : sdesc->description()->contents()) {
5902 const MediaContentDescription& desc = *content.description;
5903 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5904 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5905 desc.streams().size() > 1u) {
5906 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5907 "Media section has more than one track specified "
5908 "with a=ssrc lines which is not supported with "
5909 "Unified Plan.");
5910 }
5911 }
5912 }
5913
Steve Anton8a006912017-12-04 15:25:56 -08005914 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005915}
5916
Steve Anton3828c062017-12-06 10:34:51 -08005917bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005918 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005919 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005920 return (state == PeerConnectionInterface::kStable) ||
5921 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005922 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005923 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005924 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5925 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5926 }
5927}
5928
Steve Anton3828c062017-12-06 10:34:51 -08005929bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005930 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005931 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005932 return (state == PeerConnectionInterface::kStable) ||
5933 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005934 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005935 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005936 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5937 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5938 }
5939}
5940
Steve Antonf8470812017-12-04 10:46:21 -08005941const char* PeerConnection::SessionErrorToString(SessionError error) const {
5942 switch (error) {
5943 case SessionError::kNone:
5944 return "ERROR_NONE";
5945 case SessionError::kContent:
5946 return "ERROR_CONTENT";
5947 case SessionError::kTransport:
5948 return "ERROR_TRANSPORT";
5949 }
5950 RTC_NOTREACHED();
5951 return "";
5952}
5953
Steve Anton75737c02017-11-06 10:37:17 -08005954std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02005955 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08005956 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5957 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02005958 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08005959}
5960
Steve Anton8e20f172018-03-06 10:55:04 -08005961void PeerConnection::ReportSdpFormatReceived(
5962 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005963 int num_audio_mlines = 0;
5964 int num_video_mlines = 0;
5965 int num_audio_tracks = 0;
5966 int num_video_tracks = 0;
5967 for (const ContentInfo& content : remote_offer.description()->contents()) {
5968 cricket::MediaType media_type = content.media_description()->type();
5969 int num_tracks = std::max(
5970 1, static_cast<int>(content.media_description()->streams().size()));
5971 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5972 num_audio_mlines += 1;
5973 num_audio_tracks += num_tracks;
5974 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5975 num_video_mlines += 1;
5976 num_video_tracks += num_tracks;
5977 }
5978 }
5979 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5980 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5981 format = kSdpFormatReceivedComplexUnifiedPlan;
5982 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5983 format = kSdpFormatReceivedComplexPlanB;
5984 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5985 format = kSdpFormatReceivedSimple;
5986 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005987 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5988 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005989}
5990
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005991void PeerConnection::NoteUsageEvent(UsageEvent event) {
5992 RTC_DCHECK_RUN_ON(signaling_thread());
5993 usage_event_accumulator_ |= static_cast<int>(event);
5994}
5995
5996void PeerConnection::ReportUsagePattern() const {
5997 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005998 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5999 usage_event_accumulator_,
6000 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006001 const int bad_bits =
6002 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6003 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6004 const int good_bits =
6005 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6006 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6007 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6008 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6009 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006010 // If called after close(), we can't report, because observer may have
6011 // been deallocated, and therefore pointer is null. Write to log instead.
6012 if (observer_) {
6013 Observer()->OnInterestingUsage(usage_event_accumulator_);
6014 } else {
6015 RTC_LOG(LS_INFO) << "Interesting usage signature "
6016 << usage_event_accumulator_
6017 << " observed after observer shutdown";
6018 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006019 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006020}
6021
Steve Anton0ffaaa22018-02-23 10:31:30 -08006022void PeerConnection::ReportNegotiatedSdpSemantics(
6023 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006024 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006025 switch (answer.description()->msid_signaling()) {
6026 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006027 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006028 break;
6029 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006030 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006031 break;
6032 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006033 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006034 break;
6035 case cricket::kMsidSignalingMediaSection |
6036 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006037 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006038 break;
6039 default:
6040 RTC_NOTREACHED();
6041 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006042 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6043 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006044}
6045
Steve Anton75737c02017-11-06 10:37:17 -08006046// We need to check the local/remote description for the Transport instead of
6047// the session, because a new Transport added during renegotiation may have
6048// them unset while the session has them set from the previous negotiation.
6049// Not doing so may trigger the auto generation of transport description and
6050// mess up DTLS identity information, ICE credential, etc.
6051bool PeerConnection::ReadyToUseRemoteCandidate(
6052 const IceCandidateInterface* candidate,
6053 const SessionDescriptionInterface* remote_desc,
6054 bool* valid) {
6055 *valid = true;
6056
6057 const SessionDescriptionInterface* current_remote_desc =
6058 remote_desc ? remote_desc : remote_description();
6059
6060 if (!current_remote_desc) {
6061 return false;
6062 }
6063
6064 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6065 size_t remote_content_size =
6066 current_remote_desc->description()->contents().size();
6067 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006068 RTC_LOG(LS_ERROR)
6069 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6070 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006071
6072 *valid = false;
6073 return false;
6074 }
6075
6076 cricket::ContentInfo content =
6077 current_remote_desc->description()->contents()[mediacontent_index];
6078
6079 const std::string transport_name = GetTransportName(content.name);
6080 if (transport_name.empty()) {
6081 return false;
6082 }
Zhi Huange830e682018-03-30 10:48:35 -07006083 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006084}
6085
6086bool PeerConnection::SrtpRequired() const {
6087 return dtls_enabled_ ||
6088 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6089}
6090
6091void PeerConnection::OnTransportControllerGatheringState(
6092 cricket::IceGatheringState state) {
6093 RTC_DCHECK(signaling_thread()->IsCurrent());
6094 if (state == cricket::kIceGatheringGathering) {
6095 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6096 } else if (state == cricket::kIceGatheringComplete) {
6097 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6098 }
6099}
6100
6101void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006102 std::map<std::string, std::set<cricket::MediaType>>
6103 media_types_by_transport_name;
6104 for (auto transceiver : transceivers_) {
6105 if (transceiver->internal()->channel()) {
6106 const std::string& transport_name =
6107 transceiver->internal()->channel()->transport_name();
6108 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006109 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006110 }
Steve Anton75737c02017-11-06 10:37:17 -08006111 }
6112 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006113 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6114 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006115 }
Zhi Huange830e682018-03-30 10:48:35 -07006116
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006117 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006118 if (transport_name) {
6119 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006120 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006121 }
Zhi Huange830e682018-03-30 10:48:35 -07006122
Steve Antonc7b964c2018-02-01 14:39:45 -08006123 for (const auto& entry : media_types_by_transport_name) {
6124 const std::string& transport_name = entry.first;
6125 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006126 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006127 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006128 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006129 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006130 }
6131 }
6132}
6133// Walk through the ConnectionInfos to gather best connection usage
6134// for IPv4 and IPv6.
6135void PeerConnection::ReportBestConnectionState(
6136 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006137 for (const cricket::TransportChannelStats& channel_stats :
6138 stats.channel_stats) {
6139 for (const cricket::ConnectionInfo& connection_info :
6140 channel_stats.connection_infos) {
6141 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006142 continue;
6143 }
6144
Steve Antonc7b964c2018-02-01 14:39:45 -08006145 const cricket::Candidate& local = connection_info.local_candidate;
6146 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006147
6148 // Increment the counter for IceCandidatePairType.
6149 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6150 (local.type() == RELAY_PORT_TYPE &&
6151 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006152 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6153 GetIceCandidatePairCounter(local, remote),
6154 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006155 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006156 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6157 GetIceCandidatePairCounter(local, remote),
6158 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006159 } else {
6160 RTC_CHECK(0);
6161 }
Steve Anton75737c02017-11-06 10:37:17 -08006162
6163 // Increment the counter for IP type.
6164 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006165 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6166 kBestConnections_IPv4,
6167 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006168 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006169 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6170 kBestConnections_IPv6,
6171 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006172 } else {
6173 RTC_CHECK(0);
6174 }
6175
6176 return;
6177 }
6178 }
6179}
6180
6181void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006182 const cricket::TransportStats& stats,
6183 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006184 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6185 return;
6186 }
6187
6188 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6189 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6190 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6191 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6192 return;
6193 }
6194
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006195 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6196 for (cricket::MediaType media_type : media_types) {
6197 switch (media_type) {
6198 case cricket::MEDIA_TYPE_AUDIO:
6199 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6200 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6201 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6202 break;
6203 case cricket::MEDIA_TYPE_VIDEO:
6204 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6205 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6206 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6207 break;
6208 case cricket::MEDIA_TYPE_DATA:
6209 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6210 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6211 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6212 break;
6213 default:
6214 RTC_NOTREACHED();
6215 continue;
6216 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006217 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006218 }
6219
6220 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6221 for (cricket::MediaType media_type : media_types) {
6222 switch (media_type) {
6223 case cricket::MEDIA_TYPE_AUDIO:
6224 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6225 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6226 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6227 break;
6228 case cricket::MEDIA_TYPE_VIDEO:
6229 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6230 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6231 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6232 break;
6233 case cricket::MEDIA_TYPE_DATA:
6234 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6235 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6236 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6237 break;
6238 default:
6239 RTC_NOTREACHED();
6240 continue;
6241 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006242 }
Steve Anton75737c02017-11-06 10:37:17 -08006243 }
6244}
6245
6246void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6247 RTC_DCHECK(worker_thread()->IsCurrent());
6248 RTC_DCHECK(call_);
6249 call_->OnSentPacket(sent_packet);
6250}
6251
6252const std::string PeerConnection::GetTransportName(
6253 const std::string& content_name) {
6254 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006255 if (channel) {
6256 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006257 }
Steve Anton6fec8802017-12-04 10:37:29 -08006258 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006259 RTC_DCHECK(sctp_mid_);
6260 if (content_name == *sctp_mid_) {
6261 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006262 }
6263 }
6264 // Return an empty string if failed to retrieve the transport name.
6265 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006266}
6267
Steve Anton6fec8802017-12-04 10:37:29 -08006268void PeerConnection::DestroyTransceiverChannel(
6269 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6270 transceiver) {
6271 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006272
Steve Anton6fec8802017-12-04 10:37:29 -08006273 cricket::BaseChannel* channel = transceiver->internal()->channel();
6274 if (channel) {
6275 transceiver->internal()->SetChannel(nullptr);
6276 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006277 }
6278}
6279
6280void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006281 if (rtp_data_channel_) {
6282 OnDataChannelDestroyed();
6283 DestroyBaseChannel(rtp_data_channel_);
6284 rtp_data_channel_ = nullptr;
6285 }
6286
6287 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6288 // grab a reference to this PeerConnection. If this is called from the
6289 // PeerConnection destructor, the RefCountedObject vtable will have already
6290 // been destroyed (since it is a subclass of PeerConnection) and using
6291 // rtc::Bind will cause "Pure virtual function called" error to appear.
6292
6293 if (sctp_transport_) {
6294 OnDataChannelDestroyed();
6295 network_thread()->Invoke<void>(RTC_FROM_HERE,
6296 [this] { DestroySctpTransport_n(); });
6297 }
6298}
6299
6300void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6301 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006302 switch (channel->media_type()) {
6303 case cricket::MEDIA_TYPE_AUDIO:
6304 channel_manager()->DestroyVoiceChannel(
6305 static_cast<cricket::VoiceChannel*>(channel));
6306 break;
6307 case cricket::MEDIA_TYPE_VIDEO:
6308 channel_manager()->DestroyVideoChannel(
6309 static_cast<cricket::VideoChannel*>(channel));
6310 break;
6311 case cricket::MEDIA_TYPE_DATA:
6312 channel_manager()->DestroyRtpDataChannel(
6313 static_cast<cricket::RtpDataChannel*>(channel));
6314 break;
6315 default:
6316 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6317 break;
6318 }
Zhi Huange830e682018-03-30 10:48:35 -07006319}
Steve Anton6fec8802017-12-04 10:37:29 -08006320
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006321bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006322 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006323 RtpTransportInternal* rtp_transport,
6324 cricket::DtlsTransportInternal* dtls_transport) {
6325 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006326 auto base_channel = GetChannel(mid);
6327 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006328 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006329 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006330 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006331 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006332 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006333 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006334}
6335
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006336PeerConnectionObserver* PeerConnection::Observer() const {
6337 // In earlier production code, the pointer was not cleared on close,
6338 // which might have led to undefined behavior if the observer was not
6339 // deallocated, or strange crashes if it was.
6340 // We use CHECK in order to catch such behavior if it exists.
6341 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6342 RTC_CHECK(observer_);
6343 return observer_;
6344}
6345
Harald Alvestrand89061872018-01-02 14:08:34 +01006346void PeerConnection::ClearStatsCache() {
6347 if (stats_collector_) {
6348 stats_collector_->ClearCachedStatsReport();
6349 }
6350}
6351
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006352void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006353 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6354 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006355}
6356
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006357} // namespace webrtc