blob: ecdec61c4cac4507c05d350f4fcbd71b17856904 [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);
Zhi Huange830e682018-03-30 10:48:35 -0700959 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800960 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700961 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800962 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700963 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800964 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
965 transport_controller_->SignalDtlsHandshakeError.connect(
966 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
967
968 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700969
deadbeefab9b2d12015-10-14 11:33:11 -0700970 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700971 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000972
Steve Antonba818672017-11-06 10:21:57 -0800973 configuration_ = configuration;
974
Steve Anton75737c02017-11-06 10:37:17 -0800975 // Obtain a certificate from RTCConfiguration if any were provided (optional).
976 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
977 if (!configuration.certificates.empty()) {
978 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
979 // just picking the first one. The decision should be made based on the DTLS
980 // handshake. The DTLS negotiations need to know about all certificates.
981 certificate = configuration.certificates[0];
982 }
983
Steve Antond25da372017-11-06 14:50:29 -0800984 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800985
986 if (options.disable_encryption) {
987 dtls_enabled_ = false;
988 } else {
989 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700990 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800991 // |configuration| can override the default |dtls_enabled_| value.
992 if (configuration.enable_dtls_srtp) {
993 dtls_enabled_ = *(configuration.enable_dtls_srtp);
994 }
995 }
996
997 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
998 // It takes precendence over the disable_sctp_data_channels
999 // PeerConnectionFactoryInterface::Options.
1000 if (configuration.enable_rtp_data_channel) {
1001 data_channel_type_ = cricket::DCT_RTP;
1002 } else {
1003 // DTLS has to be enabled to use SCTP.
1004 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1005 data_channel_type_ = cricket::DCT_SCTP;
1006 }
1007 }
1008
1009 video_options_.screencast_min_bitrate_kbps =
1010 configuration.screencast_min_bitrate;
1011 audio_options_.combined_audio_video_bwe =
1012 configuration.combined_audio_video_bwe;
1013
1014 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001015 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001016
1017 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001018 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001019
1020 // Whether the certificate generator/certificate is null or not determines
1021 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1022 // the right instructions by clearing the variables if needed.
1023 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001024 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001025 certificate = nullptr;
1026 } else if (certificate) {
1027 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001028 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001029 }
1030
1031 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1032 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001033 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001034 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1035 this, &PeerConnection::OnCertificateReady);
1036
1037 if (options.disable_encryption) {
1038 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1039 }
1040
1041 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wrighta54daf12018-10-11 15:33:17 -07001042 options.crypto_options.srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001043
Steve Anton4171afb2017-11-20 10:20:22 -08001044 // Add default audio/video transceivers for Plan B SDP.
1045 if (!IsUnifiedPlan()) {
1046 transceivers_.push_back(
1047 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1048 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1049 transceivers_.push_back(
1050 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1051 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1052 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001053 int delay_ms =
1054 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001055 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1056 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001057 return true;
1058}
1059
Steve Anton038834f2017-07-14 15:59:59 -07001060RTCError PeerConnection::ValidateConfiguration(
1061 const RTCConfiguration& config) const {
1062 if (config.ice_regather_interval_range &&
1063 config.continual_gathering_policy == GATHER_ONCE) {
1064 return RTCError(RTCErrorType::INVALID_PARAMETER,
1065 "ice_regather_interval_range specified but continual "
1066 "gathering policy is GATHER_ONCE");
1067 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001068 auto result =
1069 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1070 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001071}
1072
Yves Gerey665174f2018-06-19 15:03:05 +02001073rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001074 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1075 "Plan SdpSemantics. Please use GetSenders "
1076 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001077 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078}
1079
Yves Gerey665174f2018-06-19 15:03:05 +02001080rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001081 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1082 "Plan SdpSemantics. Please use GetReceivers "
1083 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001084 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001085}
1086
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001087bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001088 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1089 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001090 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001091 if (IsClosed()) {
1092 return false;
1093 }
deadbeefab9b2d12015-10-14 11:33:11 -07001094 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001095 return false;
1096 }
deadbeefab9b2d12015-10-14 11:33:11 -07001097
1098 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001099 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1100 observer->SignalAudioTrackAdded.connect(this,
1101 &PeerConnection::OnAudioTrackAdded);
1102 observer->SignalAudioTrackRemoved.connect(
1103 this, &PeerConnection::OnAudioTrackRemoved);
1104 observer->SignalVideoTrackAdded.connect(this,
1105 &PeerConnection::OnVideoTrackAdded);
1106 observer->SignalVideoTrackRemoved.connect(
1107 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001108 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001109
deadbeefab9b2d12015-10-14 11:33:11 -07001110 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001111 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001112 }
1113 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001114 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001115 }
1116
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001117 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001118 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001119 return true;
1120}
1121
1122void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001123 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1124 "Plan SdpSemantics. Please use RemoveTrack "
1125 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001126 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001127 if (!IsClosed()) {
1128 for (const auto& track : local_stream->GetAudioTracks()) {
1129 RemoveAudioTrack(track.get(), local_stream);
1130 }
1131 for (const auto& track : local_stream->GetVideoTracks()) {
1132 RemoveVideoTrack(track.get(), local_stream);
1133 }
deadbeefab9b2d12015-10-14 11:33:11 -07001134 }
deadbeefab9b2d12015-10-14 11:33:11 -07001135 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001136 stream_observers_.erase(
1137 std::remove_if(
1138 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001139 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001140 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001141 }),
1142 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001143
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001144 if (IsClosed()) {
1145 return;
1146 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001147 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148}
1149
Steve Anton2d6c76a2018-01-05 17:10:52 -08001150RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001151 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001152 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001153 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001154 if (!track) {
1155 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1156 }
1157 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1158 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1159 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1160 "Track has invalid kind: " + track->kind());
1161 }
Steve Antonf9381f02017-12-14 10:23:57 -08001162 if (IsClosed()) {
1163 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1164 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001165 }
Steve Anton4171afb2017-11-20 10:20:22 -08001166 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001167 LOG_AND_RETURN_ERROR(
1168 RTCErrorType::INVALID_PARAMETER,
1169 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001170 }
Steve Antonf9381f02017-12-14 10:23:57 -08001171 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001172 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1173 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001174 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001175 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001176 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001177 }
1178 return sender_or_error;
1179}
deadbeefe1f9d832016-01-14 15:35:42 -08001180
Steve Antonf9381f02017-12-14 10:23:57 -08001181RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1182PeerConnection::AddTrackPlanB(
1183 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001184 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001185 if (stream_ids.size() > 1u) {
1186 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1187 "AddTrack with more than one stream is not "
1188 "supported with Plan B semantics.");
1189 }
1190 std::vector<std::string> adjusted_stream_ids = stream_ids;
1191 if (adjusted_stream_ids.empty()) {
1192 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1193 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001194 cricket::MediaType media_type =
1195 (track->kind() == MediaStreamTrackInterface::kAudioKind
1196 ? cricket::MEDIA_TYPE_AUDIO
1197 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001198 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001199 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001200 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001201 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001202 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001203 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001204 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001205 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001206 if (sender_info) {
1207 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001208 }
Steve Antonf9381f02017-12-14 10:23:57 -08001209 } else {
1210 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001211 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001212 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001213 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001214 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001215 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001216 if (sender_info) {
1217 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001218 }
deadbeefe1f9d832016-01-14 15:35:42 -08001219 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001220 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001221}
deadbeefe1f9d832016-01-14 15:35:42 -08001222
Steve Antonf9381f02017-12-14 10:23:57 -08001223RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1224PeerConnection::AddTrackUnifiedPlan(
1225 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001226 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001227 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1228 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001229 RTC_LOG(LS_INFO) << "Reusing an existing "
1230 << cricket::MediaTypeToString(transceiver->media_type())
1231 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001232 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001233 transceiver->internal()->set_direction(
1234 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001235 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001236 transceiver->internal()->set_direction(
1237 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001238 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001239 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001240 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001241 } else {
1242 cricket::MediaType media_type =
1243 (track->kind() == MediaStreamTrackInterface::kAudioKind
1244 ? cricket::MEDIA_TYPE_AUDIO
1245 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001246 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1247 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001248 std::string sender_id = track->id();
1249 // Avoid creating a sender with an existing ID by generating a random ID.
1250 // This can happen if this is the second time AddTrack has created a sender
1251 // for this track.
1252 if (FindSenderById(sender_id)) {
1253 sender_id = rtc::CreateRandomUuid();
1254 }
Florent Castelli892acf02018-10-01 22:47:20 +02001255 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001256 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1257 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001258 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001259 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001260 }
Steve Antonf9381f02017-12-14 10:23:57 -08001261 return transceiver->sender();
1262}
1263
1264rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1265PeerConnection::FindFirstTransceiverForAddedTrack(
1266 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1267 RTC_DCHECK(track);
1268 for (auto transceiver : transceivers_) {
1269 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001270 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001271 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001272 !transceiver->internal()->has_ever_been_used_to_send() &&
1273 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001274 return transceiver;
1275 }
1276 }
1277 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001278}
1279
1280bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1281 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001282 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001283}
1284
Steve Anton24db5732018-07-23 10:27:33 -07001285RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001286 rtc::scoped_refptr<RtpSenderInterface> sender) {
1287 if (!sender) {
1288 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1289 }
deadbeefe1f9d832016-01-14 15:35:42 -08001290 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001291 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1292 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001293 }
Steve Antonf9381f02017-12-14 10:23:57 -08001294 if (IsUnifiedPlan()) {
1295 auto transceiver = FindTransceiverBySender(sender);
1296 if (!transceiver || !sender->track()) {
1297 return RTCError::OK();
1298 }
1299 sender->SetTrack(nullptr);
1300 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001301 transceiver->internal()->set_direction(
1302 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001303 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001304 transceiver->internal()->set_direction(
1305 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001306 }
Steve Anton4171afb2017-11-20 10:20:22 -08001307 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001308 bool removed;
1309 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1310 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1311 } else {
1312 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1313 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1314 }
1315 if (!removed) {
1316 LOG_AND_RETURN_ERROR(
1317 RTCErrorType::INVALID_PARAMETER,
1318 "Couldn't find sender " + sender->id() + " to remove.");
1319 }
Steve Anton4171afb2017-11-20 10:20:22 -08001320 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001321 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001322 return RTCError::OK();
1323}
1324
1325rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1326PeerConnection::FindTransceiverBySender(
1327 rtc::scoped_refptr<RtpSenderInterface> sender) {
1328 for (auto transceiver : transceivers_) {
1329 if (transceiver->sender() == sender) {
1330 return transceiver;
1331 }
1332 }
1333 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001334}
1335
Steve Anton9158ef62017-11-27 13:01:52 -08001336RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1337PeerConnection::AddTransceiver(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1339 return AddTransceiver(track, RtpTransceiverInit());
1340}
1341
1342RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1343PeerConnection::AddTransceiver(
1344 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1345 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001346 RTC_CHECK(IsUnifiedPlan())
1347 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001348 if (!track) {
1349 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1350 }
1351 cricket::MediaType media_type;
1352 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1353 media_type = cricket::MEDIA_TYPE_AUDIO;
1354 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1355 media_type = cricket::MEDIA_TYPE_VIDEO;
1356 } else {
1357 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1358 "Track kind is not audio or video");
1359 }
1360 return AddTransceiver(media_type, track, init);
1361}
1362
1363RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1364PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1365 return AddTransceiver(media_type, RtpTransceiverInit());
1366}
1367
1368RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1369PeerConnection::AddTransceiver(cricket::MediaType media_type,
1370 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001371 RTC_CHECK(IsUnifiedPlan())
1372 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001373 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1374 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1375 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1376 "media type is not audio or video");
1377 }
1378 return AddTransceiver(media_type, nullptr, init);
1379}
1380
1381RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1382PeerConnection::AddTransceiver(
1383 cricket::MediaType media_type,
1384 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001385 const RtpTransceiverInit& init,
1386 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001387 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1388 media_type == cricket::MEDIA_TYPE_VIDEO));
1389 if (track) {
1390 RTC_DCHECK_EQ(media_type,
1391 (track->kind() == MediaStreamTrackInterface::kAudioKind
1392 ? cricket::MEDIA_TYPE_AUDIO
1393 : cricket::MEDIA_TYPE_VIDEO));
1394 }
1395
1396 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001397 if (init.send_encodings.size() > 1) {
1398 LOG_AND_RETURN_ERROR(
1399 RTCErrorType::UNSUPPORTED_PARAMETER,
1400 "Attempted to create an encoder with more than 1 encoding parameter.");
1401 }
1402
1403 for (const auto& encoding : init.send_encodings) {
1404 if (encoding.ssrc.has_value()) {
1405 LOG_AND_RETURN_ERROR(
1406 RTCErrorType::UNSUPPORTED_PARAMETER,
1407 "Attempted to set an unimplemented parameter of RtpParameters.");
1408 }
1409 }
1410
1411 RtpParameters parameters;
1412 parameters.encodings = init.send_encodings;
1413 if (UnimplementedRtpParameterHasValue(parameters)) {
1414 LOG_AND_RETURN_ERROR(
1415 RTCErrorType::UNSUPPORTED_PARAMETER,
1416 "Attempted to set an unimplemented parameter of RtpParameters.");
1417 }
Steve Anton9158ef62017-11-27 13:01:52 -08001418
Steve Anton3d954a62018-04-02 11:27:23 -07001419 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1420 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001421 // Set the sender ID equal to the track ID if the track is specified unless
1422 // that sender ID is already in use.
1423 std::string sender_id =
1424 (track && !FindSenderById(track->id()) ? track->id()
1425 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001426 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1427 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001428 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1429 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1430 transceiver->internal()->set_direction(init.direction);
1431
Steve Anton22da89f2018-01-25 13:58:07 -08001432 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001433 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001434 }
Steve Antonf9381f02017-12-14 10:23:57 -08001435
1436 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1437}
1438
Steve Anton02ee47c2018-01-10 16:26:06 -08001439rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1440PeerConnection::CreateSender(
1441 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001442 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001443 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001444 const std::vector<std::string>& stream_ids,
1445 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001446 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1448 RTC_DCHECK(!track ||
1449 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1450 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1451 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001452 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001453 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001454 } else {
1455 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1456 RTC_DCHECK(!track ||
1457 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1458 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001459 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001460 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001461 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001462 bool set_track_succeeded = sender->SetTrack(track);
1463 RTC_DCHECK(set_track_succeeded);
1464 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001465 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001466 return sender;
1467}
1468
1469rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1470PeerConnection::CreateReceiver(cricket::MediaType media_type,
1471 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001472 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1473 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001474 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001475 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001476 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1477 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001478 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001479 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001480 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001481 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001482 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1483 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001484 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001485 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001486 return receiver;
1487}
1488
1489rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1490PeerConnection::CreateAndAddTransceiver(
1491 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1492 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1493 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001494 // Ensure that the new sender does not have an ID that is already in use by
1495 // another sender.
1496 // Allow receiver IDs to conflict since those come from remote SDP (which
1497 // could be invalid, but should not cause a crash).
1498 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001499 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1500 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001501 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001502 transceiver->internal()->SignalNegotiationNeeded.connect(
1503 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001504 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001505}
1506
Steve Anton52d86772018-02-20 15:48:12 -08001507void PeerConnection::OnNegotiationNeeded() {
1508 RTC_DCHECK_RUN_ON(signaling_thread());
1509 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001510 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001511}
1512
deadbeeffac06552015-11-25 11:26:01 -08001513rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001514 const std::string& kind,
1515 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001516 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1517 "Plan SdpSemantics. Please use AddTransceiver "
1518 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001519 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001520 if (IsClosed()) {
1521 return nullptr;
1522 }
Steve Anton4171afb2017-11-20 10:20:22 -08001523
Seth Hampson5b4f0752018-04-02 16:31:36 -07001524 // Internally we need to have one stream with Plan B semantics, so we
1525 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001526 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001527 if (stream_id.empty()) {
1528 stream_ids.push_back(rtc::CreateRandomUuid());
1529 RTC_LOG(LS_INFO)
1530 << "No stream_id specified for sender. Generated stream ID: "
1531 << stream_ids[0];
1532 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001533 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001534 }
1535
Steve Anton4171afb2017-11-20 10:20:22 -08001536 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001537 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001538 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001539 auto* audio_sender = new AudioRtpSender(
1540 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001541 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001542 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001543 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001544 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001545 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001546 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001547 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001548 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001549 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001550 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001551 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001552 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001553 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001554 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001555 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001556 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001557
deadbeefe1f9d832016-01-14 15:35:42 -08001558 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001559}
1560
deadbeef70ab1a12015-09-28 16:53:55 -07001561std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1562 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001563 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001564 for (auto sender : GetSendersInternal()) {
1565 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001566 }
1567 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001568}
1569
Steve Anton4171afb2017-11-20 10:20:22 -08001570std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1571PeerConnection::GetSendersInternal() const {
1572 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1573 all_senders;
1574 for (auto transceiver : transceivers_) {
1575 auto senders = transceiver->internal()->senders();
1576 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1577 }
1578 return all_senders;
1579}
1580
deadbeef70ab1a12015-09-28 16:53:55 -07001581std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1582PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001583 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001584 for (const auto& receiver : GetReceiversInternal()) {
1585 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001586 }
1587 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001588}
1589
Steve Anton4171afb2017-11-20 10:20:22 -08001590std::vector<
1591 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1592PeerConnection::GetReceiversInternal() const {
1593 std::vector<
1594 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1595 all_receivers;
1596 for (auto transceiver : transceivers_) {
1597 auto receivers = transceiver->internal()->receivers();
1598 all_receivers.insert(all_receivers.end(), receivers.begin(),
1599 receivers.end());
1600 }
1601 return all_receivers;
1602}
1603
Steve Anton9158ef62017-11-27 13:01:52 -08001604std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1605PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001606 RTC_CHECK(IsUnifiedPlan())
1607 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001608 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1609 for (auto transceiver : transceivers_) {
1610 all_transceivers.push_back(transceiver);
1611 }
1612 return all_transceivers;
1613}
1614
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001615bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001616 MediaStreamTrackInterface* track,
1617 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001618 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001619 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001620 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001621 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001622 return false;
1623 }
1624
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001625 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001626 // The StatsCollector is used to tell if a track is valid because it may
1627 // remember tracks that the PeerConnection previously removed.
1628 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001629 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1630 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001631 return false;
1632 }
Steve Antonad182762018-09-05 20:22:40 +00001633 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1634 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001635 return true;
1636}
1637
hbos74e1a4f2016-09-15 23:33:01 -07001638void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001639 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001640 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001641 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001642 stats_collector_->GetStatsReport(callback);
1643}
1644
Henrik Boström1df1bf82018-03-20 13:24:20 +01001645void PeerConnection::GetStats(
1646 rtc::scoped_refptr<RtpSenderInterface> selector,
1647 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1648 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1649 RTC_DCHECK(callback);
1650 RTC_DCHECK(stats_collector_);
1651 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1652 if (selector) {
1653 for (const auto& proxy_transceiver : transceivers_) {
1654 for (const auto& proxy_sender :
1655 proxy_transceiver->internal()->senders()) {
1656 if (proxy_sender == selector) {
1657 internal_sender = proxy_sender->internal();
1658 break;
1659 }
1660 }
1661 if (internal_sender)
1662 break;
1663 }
1664 }
1665 // If there is no |internal_sender| then |selector| is either null or does not
1666 // belong to the PeerConnection (in Plan B, senders can be removed from the
1667 // PeerConnection). This means that "all the stats objects representing the
1668 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1669 // produces an empty stats report.
1670 stats_collector_->GetStatsReport(internal_sender, callback);
1671}
1672
1673void PeerConnection::GetStats(
1674 rtc::scoped_refptr<RtpReceiverInterface> selector,
1675 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1676 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1677 RTC_DCHECK(callback);
1678 RTC_DCHECK(stats_collector_);
1679 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1680 if (selector) {
1681 for (const auto& proxy_transceiver : transceivers_) {
1682 for (const auto& proxy_receiver :
1683 proxy_transceiver->internal()->receivers()) {
1684 if (proxy_receiver == selector) {
1685 internal_receiver = proxy_receiver->internal();
1686 break;
1687 }
1688 }
1689 if (internal_receiver)
1690 break;
1691 }
1692 }
1693 // If there is no |internal_receiver| then |selector| is either null or does
1694 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1695 // the PeerConnection). This means that "all the stats objects representing
1696 // the selector" is an empty set. Invoking GetStatsReport() with a null
1697 // selector produces an empty stats report.
1698 stats_collector_->GetStatsReport(internal_receiver, callback);
1699}
1700
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1702 return signaling_state_;
1703}
1704
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001705PeerConnectionInterface::IceConnectionState
1706PeerConnection::ice_connection_state() {
1707 return ice_connection_state_;
1708}
1709
1710PeerConnectionInterface::IceGatheringState
1711PeerConnection::ice_gathering_state() {
1712 return ice_gathering_state_;
1713}
1714
Yves Gerey665174f2018-06-19 15:03:05 +02001715rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716 const std::string& label,
1717 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001718 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001719
deadbeefab9b2d12015-10-14 11:33:11 -07001720 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001721
kwibergd1fe2812016-04-27 06:47:29 -07001722 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001723 if (config) {
1724 internal_config.reset(new InternalDataChannelInit(*config));
1725 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001726 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001727 InternalCreateDataChannel(label, internal_config.get()));
1728 if (!channel.get()) {
1729 return nullptr;
1730 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001731
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001732 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1733 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001734 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001735 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001736 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001737 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001738 return DataChannelProxy::Create(signaling_thread(), channel.get());
1739}
1740
1741void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001742 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001743 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001744
nisse7ce109a2017-01-31 00:57:56 -08001745 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001746 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001747 return;
1748 }
deadbeefab9b2d12015-10-14 11:33:11 -07001749
Steve Anton8d3444d2017-10-20 15:30:51 -07001750 if (IsClosed()) {
1751 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001752 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001753 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001754 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001755 return;
1756 }
1757
zhihuang1c378ed2017-08-17 14:10:50 -07001758 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001759 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001760 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001761 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001762 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001763 return;
1764 }
1765
Steve Anton22da89f2018-01-25 13:58:07 -08001766 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1767 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1768 if (IsUnifiedPlan()) {
1769 RTCError error = HandleLegacyOfferOptions(options);
1770 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001771 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001772 return;
1773 }
1774 }
1775
zhihuang1c378ed2017-08-17 14:10:50 -07001776 cricket::MediaSessionOptions session_options;
1777 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001778 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779}
1780
Steve Anton22da89f2018-01-25 13:58:07 -08001781RTCError PeerConnection::HandleLegacyOfferOptions(
1782 const RTCOfferAnswerOptions& options) {
1783 RTC_DCHECK(IsUnifiedPlan());
1784
1785 if (options.offer_to_receive_audio == 0) {
1786 RemoveRecvDirectionFromReceivingTransceiversOfType(
1787 cricket::MEDIA_TYPE_AUDIO);
1788 } else if (options.offer_to_receive_audio == 1) {
1789 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1790 } else if (options.offer_to_receive_audio > 1) {
1791 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1792 "offer_to_receive_audio > 1 is not supported.");
1793 }
1794
1795 if (options.offer_to_receive_video == 0) {
1796 RemoveRecvDirectionFromReceivingTransceiversOfType(
1797 cricket::MEDIA_TYPE_VIDEO);
1798 } else if (options.offer_to_receive_video == 1) {
1799 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1800 } else if (options.offer_to_receive_video > 1) {
1801 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1802 "offer_to_receive_video > 1 is not supported.");
1803 }
1804
1805 return RTCError::OK();
1806}
1807
1808void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1809 cricket::MediaType media_type) {
1810 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001811 RtpTransceiverDirection new_direction =
1812 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1813 if (new_direction != transceiver->direction()) {
1814 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1815 << " transceiver (MID="
1816 << transceiver->mid().value_or("<not set>") << ") from "
1817 << RtpTransceiverDirectionToString(
1818 transceiver->direction())
1819 << " to "
1820 << RtpTransceiverDirectionToString(new_direction)
1821 << " since CreateOffer specified offer_to_receive=0";
1822 transceiver->internal()->set_direction(new_direction);
1823 }
Steve Anton22da89f2018-01-25 13:58:07 -08001824 }
1825}
1826
1827void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1828 cricket::MediaType media_type) {
1829 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001830 RTC_LOG(LS_INFO)
1831 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1832 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001833 RtpTransceiverInit init;
1834 init.direction = RtpTransceiverDirection::kRecvOnly;
1835 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1836 }
1837}
1838
1839std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1840PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1841 std::vector<
1842 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1843 receiving_transceivers;
1844 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001845 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001846 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1847 receiving_transceivers.push_back(transceiver);
1848 }
1849 }
1850 return receiving_transceivers;
1851}
1852
htaa2a49d92016-03-04 02:51:39 -08001853void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1854 const RTCOfferAnswerOptions& options) {
1855 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001856 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001857 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001858 return;
1859 }
1860
Steve Antondffead82018-02-06 10:31:29 -08001861 if (!(signaling_state_ == kHaveRemoteOffer ||
1862 signaling_state_ == kHaveLocalPrAnswer)) {
1863 std::string error =
1864 "PeerConnection cannot create an answer in a state other than "
1865 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001866 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001867 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001868 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001869 return;
1870 }
1871
Steve Antondffead82018-02-06 10:31:29 -08001872 // The remote description should be set if we're in the right state.
1873 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001874
Steve Anton22da89f2018-01-25 13:58:07 -08001875 if (IsUnifiedPlan()) {
1876 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1877 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1878 "supported with Unified Plan semantics. Use the "
1879 "RtpTransceiver API instead.";
1880 }
1881 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1882 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1883 "supported with Unified Plan semantics. Use the "
1884 "RtpTransceiver API instead.";
1885 }
1886 }
1887
htaa2a49d92016-03-04 02:51:39 -08001888 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001889 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001890
Steve Antond25da372017-11-06 14:50:29 -08001891 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892}
1893
1894void PeerConnection::SetLocalDescription(
1895 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001896 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001897 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001898
Steve Anton80dd7b52018-02-16 17:08:42 -08001899 // The SetLocalDescription contract is that we take ownership of the session
1900 // description regardless of the outcome, so wrap it in a unique_ptr right
1901 // away. Ideally, SetLocalDescription's signature will be changed to take the
1902 // description as a unique_ptr argument to formalize this agreement.
1903 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1904
nisse7ce109a2017-01-31 00:57:56 -08001905 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001906 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001907 return;
1908 }
Steve Anton8a006912017-12-04 15:25:56 -08001909
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001910 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001911 PostSetSessionDescriptionFailure(
1912 observer,
1913 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001914 return;
1915 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001916
Steve Anton80dd7b52018-02-16 17:08:42 -08001917 // If a session error has occurred the PeerConnection is in a possibly
1918 // inconsistent state so fail right away.
1919 if (session_error() != SessionError::kNone) {
1920 std::string error_message = GetSessionErrorMsg();
1921 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001922 PostSetSessionDescriptionFailure(
1923 observer,
1924 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001925 return;
1926 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001927
Steve Anton80dd7b52018-02-16 17:08:42 -08001928 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1929 if (!error.ok()) {
1930 std::string error_message = GetSetDescriptionErrorMessage(
1931 cricket::CS_LOCAL, desc->GetType(), error);
1932 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001933 PostSetSessionDescriptionFailure(
1934 observer,
1935 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001936 return;
1937 }
1938
1939 // Grab the description type before moving ownership to ApplyLocalDescription,
1940 // which may destroy it before returning.
1941 const SdpType type = desc->GetType();
1942
1943 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001944 // |desc| may be destroyed at this point.
1945
1946 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001947 // If ApplyLocalDescription fails, the PeerConnection could be in an
1948 // inconsistent state, so act conservatively here and set the session error
1949 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1950 SetSessionError(SessionError::kContent, error.message());
1951 std::string error_message =
1952 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1953 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001954 PostSetSessionDescriptionFailure(
1955 observer,
1956 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001957 return;
1958 }
Steve Anton8a006912017-12-04 15:25:56 -08001959 RTC_DCHECK(local_description());
1960
1961 PostSetSessionDescriptionSuccess(observer);
1962
Steve Antonad182762018-09-05 20:22:40 +00001963 // MaybeStartGathering needs to be called after posting
1964 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1965 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001966 transport_controller_->MaybeStartGathering();
1967
Steve Antona3a92c22017-12-07 10:27:41 -08001968 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001969 // TODO(deadbeef): We already had to hop to the network thread for
1970 // MaybeStartGathering...
1971 network_thread()->Invoke<void>(
1972 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1973 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001974 // Make UMA notes about what was agreed to.
1975 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001976 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001977 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001978}
1979
1980RTCError PeerConnection::ApplyLocalDescription(
1981 std::unique_ptr<SessionDescriptionInterface> desc) {
1982 RTC_DCHECK_RUN_ON(signaling_thread());
1983 RTC_DCHECK(desc);
1984
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 // Update stats here so that we have the most recent stats for tracks and
1986 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001987 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001988
Steve Antondcc3c022017-12-22 16:02:54 -08001989 // Take a reference to the old local description since it's used below to
1990 // compare against the new local description. When setting the new local
1991 // description, grab ownership of the replaced session description in case it
1992 // is the same as |old_local_description|, to keep it alive for the duration
1993 // of the method.
1994 const SessionDescriptionInterface* old_local_description =
1995 local_description();
1996 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001997 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001998 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001999 replaced_local_description = pending_local_description_
2000 ? std::move(pending_local_description_)
2001 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002002 current_local_description_ = std::move(desc);
2003 pending_local_description_ = nullptr;
2004 current_remote_description_ = std::move(pending_remote_description_);
2005 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002006 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002007 pending_local_description_ = std::move(desc);
2008 }
2009 // The session description to apply now must be accessed by
2010 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002011 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002012
Zhi Huange830e682018-03-30 10:48:35 -07002013 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2014 if (!error.ok()) {
2015 return error;
2016 }
2017
Steve Antondcc3c022017-12-22 16:02:54 -08002018 if (IsUnifiedPlan()) {
2019 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002020 cricket::CS_LOCAL, *local_description(), old_local_description,
2021 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002022 if (!error.ok()) {
2023 return error;
2024 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002025 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2026 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002027 for (auto transceiver : transceivers_) {
2028 const ContentInfo* content =
2029 FindMediaSectionForTransceiver(transceiver, local_description());
2030 if (!content) {
2031 continue;
2032 }
2033 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002034 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2035 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002036 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002037 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2038 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2039 // "recvonly", process the removal of a remote track for the media
2040 // description, given transceiver, removeList, and muteTracks.
2041 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2042 (transceiver->internal()->fired_direction() &&
2043 RtpTransceiverDirectionHasRecv(
2044 *transceiver->internal()->fired_direction()))) {
2045 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2046 &removed_streams);
2047 }
2048 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2049 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002050 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002051 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002052 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002053 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002054 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002055 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002056 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002057 }
2058 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002059 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002060 }
2061 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002062 // Media channels will be created only when offer is set. These may use new
2063 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002064 if (type == SdpType::kOffer) {
2065 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2066 // description is applied. Restore back to old description.
2067 RTCError error = CreateChannels(*local_description()->description());
2068 if (!error.ok()) {
2069 return error;
2070 }
2071 }
Steve Antondcc3c022017-12-22 16:02:54 -08002072 // Remove unused channels if MediaContentDescription is rejected.
2073 RemoveUnusedChannels(local_description()->description());
2074 }
Steve Anton8a006912017-12-04 15:25:56 -08002075
Zhi Huange830e682018-03-30 10:48:35 -07002076 error = UpdateSessionState(type, cricket::CS_LOCAL,
2077 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002078 if (!error.ok()) {
2079 return error;
2080 }
Steve Antondcc3c022017-12-22 16:02:54 -08002081
Steve Anton8a006912017-12-04 15:25:56 -08002082 if (remote_description()) {
2083 // Now that we have a local description, we can push down remote candidates.
2084 UseCandidatesInSessionDescription(remote_description());
2085 }
2086
2087 pending_ice_restarts_.clear();
2088 if (session_error() != SessionError::kNone) {
2089 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2090 }
2091
deadbeefab9b2d12015-10-14 11:33:11 -07002092 // If setting the description decided our SSL role, allocate any necessary
2093 // SCTP sids.
2094 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002095 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002096 AllocateSctpSids(role);
2097 }
2098
Steve Antond3679212018-01-17 17:41:02 -08002099 if (IsUnifiedPlan()) {
2100 for (auto transceiver : transceivers_) {
2101 const ContentInfo* content =
2102 FindMediaSectionForTransceiver(transceiver, local_description());
2103 if (!content) {
2104 continue;
2105 }
Steve Anton74255ff2018-01-24 18:32:57 -08002106 const auto& streams = content->media_description()->streams();
2107 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002108 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002109 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002110 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002111 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002112 } else {
2113 // 0 is a special value meaning "this sender has no associated send
2114 // stream". Need to call this so the sender won't attempt to configure
2115 // a no longer existing stream and run into DCHECKs in the lower
2116 // layers.
2117 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002118 }
2119 }
2120 } else {
2121 // Plan B semantics.
2122
Steve Antondcc3c022017-12-22 16:02:54 -08002123 // Update state and SSRC of local MediaStreams and DataChannels based on the
2124 // local session description.
2125 const cricket::ContentInfo* audio_content =
2126 GetFirstAudioContent(local_description()->description());
2127 if (audio_content) {
2128 if (audio_content->rejected) {
2129 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2130 } else {
2131 const cricket::AudioContentDescription* audio_desc =
2132 audio_content->media_description()->as_audio();
2133 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2134 }
deadbeeffaac4972015-11-12 15:33:07 -08002135 }
deadbeefab9b2d12015-10-14 11:33:11 -07002136
Steve Antondcc3c022017-12-22 16:02:54 -08002137 const cricket::ContentInfo* video_content =
2138 GetFirstVideoContent(local_description()->description());
2139 if (video_content) {
2140 if (video_content->rejected) {
2141 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2142 } else {
2143 const cricket::VideoContentDescription* video_desc =
2144 video_content->media_description()->as_video();
2145 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2146 }
deadbeeffaac4972015-11-12 15:33:07 -08002147 }
deadbeefab9b2d12015-10-14 11:33:11 -07002148 }
2149
2150 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002151 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002152 if (data_content) {
2153 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002154 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002155 if (rtc::starts_with(data_desc->protocol().data(),
2156 cricket::kMediaProtocolRtpPrefix)) {
2157 UpdateLocalRtpDataChannels(data_desc->streams());
2158 }
2159 }
2160
Steve Anton8a006912017-12-04 15:25:56 -08002161 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002162}
2163
2164void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002165 SetSessionDescriptionObserver* observer,
2166 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002167 SetRemoteDescription(
2168 std::unique_ptr<SessionDescriptionInterface>(desc),
2169 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2170 new SetRemoteDescriptionObserverAdapter(this, observer)));
2171}
2172
2173void PeerConnection::SetRemoteDescription(
2174 std::unique_ptr<SessionDescriptionInterface> desc,
2175 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002176 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002177
nisse7ce109a2017-01-31 00:57:56 -08002178 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002179 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002180 return;
2181 }
Steve Anton8a006912017-12-04 15:25:56 -08002182
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002184 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002185 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002186 return;
2187 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002188
Steve Anton80dd7b52018-02-16 17:08:42 -08002189 // If a session error has occurred the PeerConnection is in a possibly
2190 // inconsistent state so fail right away.
2191 if (session_error() != SessionError::kNone) {
2192 std::string error_message = GetSessionErrorMsg();
2193 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2194 observer->OnSetRemoteDescriptionComplete(
2195 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2196 return;
2197 }
Steve Anton71439a62018-02-15 11:53:06 -08002198
Steve Antonba42e992018-04-09 14:10:01 -07002199 if (desc->GetType() == SdpType::kOffer) {
2200 // Report to UMA the format of the received offer.
2201 ReportSdpFormatReceived(*desc);
2202 }
2203
Steve Anton80dd7b52018-02-16 17:08:42 -08002204 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002205 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002206 std::string error_message = GetSetDescriptionErrorMessage(
2207 cricket::CS_REMOTE, desc->GetType(), error);
2208 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002209 observer->OnSetRemoteDescriptionComplete(
2210 RTCError(error.type(), std::move(error_message)));
2211 return;
2212 }
Steve Anton71439a62018-02-15 11:53:06 -08002213
Steve Anton80dd7b52018-02-16 17:08:42 -08002214 // Grab the description type before moving ownership to
2215 // ApplyRemoteDescription, which may destroy it before returning.
2216 const SdpType type = desc->GetType();
2217
2218 error = ApplyRemoteDescription(std::move(desc));
2219 // |desc| may be destroyed at this point.
2220
2221 if (!error.ok()) {
2222 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2223 // inconsistent state, so act conservatively here and set the session error
2224 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2225 SetSessionError(SessionError::kContent, error.message());
2226 std::string error_message =
2227 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2228 RTC_LOG(LS_ERROR) << error_message;
2229 observer->OnSetRemoteDescriptionComplete(
2230 RTCError(error.type(), std::move(error_message)));
2231 return;
2232 }
2233 RTC_DCHECK(remote_description());
2234
2235 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002236 // TODO(deadbeef): We already had to hop to the network thread for
2237 // MaybeStartGathering...
2238 network_thread()->Invoke<void>(
2239 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2240 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002241 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002242 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002243 }
2244
2245 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002246 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002247}
2248
2249RTCError PeerConnection::ApplyRemoteDescription(
2250 std::unique_ptr<SessionDescriptionInterface> desc) {
2251 RTC_DCHECK_RUN_ON(signaling_thread());
2252 RTC_DCHECK(desc);
2253
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254 // Update stats here so that we have the most recent stats for tracks and
2255 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002256 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002257
Steve Antondcc3c022017-12-22 16:02:54 -08002258 // Take a reference to the old remote description since it's used below to
2259 // compare against the new remote description. When setting the new remote
2260 // description, grab ownership of the replaced session description in case it
2261 // is the same as |old_remote_description|, to keep it alive for the duration
2262 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002263 const SessionDescriptionInterface* old_remote_description =
2264 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002265 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002266 SdpType type = desc->GetType();
2267 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002268 replaced_remote_description = pending_remote_description_
2269 ? std::move(pending_remote_description_)
2270 : std::move(current_remote_description_);
2271 current_remote_description_ = std::move(desc);
2272 pending_remote_description_ = nullptr;
2273 current_local_description_ = std::move(pending_local_description_);
2274 } else {
2275 replaced_remote_description = std::move(pending_remote_description_);
2276 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277 }
Steve Anton8a006912017-12-04 15:25:56 -08002278 // The session description to apply now must be accessed by
2279 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002280 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002281
Zhi Huange830e682018-03-30 10:48:35 -07002282 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2283 if (!error.ok()) {
2284 return error;
2285 }
Steve Anton8a006912017-12-04 15:25:56 -08002286 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002287 if (IsUnifiedPlan()) {
2288 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002289 cricket::CS_REMOTE, *remote_description(), local_description(),
2290 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002291 if (!error.ok()) {
2292 return error;
2293 }
Steve Antondcc3c022017-12-22 16:02:54 -08002294 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002295 // Media channels will be created only when offer is set. These may use new
2296 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002297 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002298 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002299 // description is applied. Restore back to old description.
2300 RTCError error = CreateChannels(*remote_description()->description());
2301 if (!error.ok()) {
2302 return error;
2303 }
2304 }
Steve Antondcc3c022017-12-22 16:02:54 -08002305 // Remove unused channels if MediaContentDescription is rejected.
2306 RemoveUnusedChannels(remote_description()->description());
2307 }
Steve Anton8a006912017-12-04 15:25:56 -08002308
Zhi Huange830e682018-03-30 10:48:35 -07002309 // NOTE: Candidates allocation will be initiated only when
2310 // SetLocalDescription is called.
2311 error = UpdateSessionState(type, cricket::CS_REMOTE,
2312 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002313 if (!error.ok()) {
2314 return error;
2315 }
2316
2317 if (local_description() &&
2318 !UseCandidatesInSessionDescription(remote_description())) {
2319 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2320 }
2321
2322 if (old_remote_description) {
2323 for (const cricket::ContentInfo& content :
2324 old_remote_description->description()->contents()) {
2325 // Check if this new SessionDescription contains new ICE ufrag and
2326 // password that indicates the remote peer requests an ICE restart.
2327 // TODO(deadbeef): When we start storing both the current and pending
2328 // remote description, this should reset pending_ice_restarts and compare
2329 // against the current description.
2330 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2331 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002332 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002333 pending_ice_restarts_.insert(content.name);
2334 }
2335 } else {
2336 // We retain all received candidates only if ICE is not restarted.
2337 // When ICE is restarted, all previous candidates belong to an old
2338 // generation and should not be kept.
2339 // TODO(deadbeef): This goes against the W3C spec which says the remote
2340 // description should only contain candidates from the last set remote
2341 // description plus any candidates added since then. We should remove
2342 // this once we're sure it won't break anything.
2343 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2344 old_remote_description, content.name, mutable_remote_description());
2345 }
2346 }
2347 }
2348
2349 if (session_error() != SessionError::kNone) {
2350 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2351 }
2352
2353 // Set the the ICE connection state to connecting since the connection may
2354 // become writable with peer reflexive candidates before any remote candidate
2355 // is signaled.
2356 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2357 // is to have a new signal the indicates a change in checking state from the
2358 // transport and expose a new checking() member from transport that can be
2359 // read to determine the current checking state. The existing SignalConnecting
2360 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002361 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002362 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002363 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2364 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2365 }
2366
deadbeefab9b2d12015-10-14 11:33:11 -07002367 // If setting the description decided our SSL role, allocate any necessary
2368 // SCTP sids.
2369 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002370 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002371 AllocateSctpSids(role);
2372 }
2373
Steve Antondcc3c022017-12-22 16:02:54 -08002374 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002375 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002376 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002377 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002378 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002379 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002380 for (auto transceiver : transceivers_) {
2381 const ContentInfo* content =
2382 FindMediaSectionForTransceiver(transceiver, remote_description());
2383 if (!content) {
2384 continue;
2385 }
2386 const MediaContentDescription* media_desc = content->media_description();
2387 RtpTransceiverDirection local_direction =
2388 RtpTransceiverDirectionReversed(media_desc->direction());
2389 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2390 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2391 // transceiver's current direction is neither sendrecv nor recvonly,
2392 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002393 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002394 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002395 // The remote description has signaled the stream IDs.
2396 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002397 }
Steve Antondcc3c022017-12-22 16:02:54 -08002398 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002399 (!transceiver->fired_direction() ||
2400 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002401 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002402 << content->name << " (added to "
2403 << GetStreamIdsString(stream_ids) << ").";
2404
2405 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2406 for (const std::string& stream_id : stream_ids) {
2407 rtc::scoped_refptr<MediaStreamInterface> stream =
2408 remote_streams_->find(stream_id);
2409 if (!stream) {
2410 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2411 MediaStream::Create(stream_id));
2412 remote_streams_->AddStream(stream);
2413 added_streams.push_back(stream);
2414 }
2415 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002416 }
Steve Anton3172c032018-05-03 15:30:18 -07002417 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002418 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2419 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002420 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002421 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002422 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002423 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2424 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2425 // removal of a remote track for the media description, given transceiver,
2426 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002427 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002428 (transceiver->fired_direction() &&
2429 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2430 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2431 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002432 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002433 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2434 transceiver->internal()->set_fired_direction(local_direction);
2435 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2436 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002437 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002438 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2439 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002440 transceiver->internal()->set_current_direction(local_direction);
2441 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002442 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2443 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002444 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002445 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2446 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002447 transceiver->Stop();
2448 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002449 if (!content->rejected &&
2450 RtpTransceiverDirectionHasRecv(local_direction)) {
2451 // Set ssrc to 0 in the case of an unsignalled ssrc.
2452 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002453 if (!media_desc->streams().empty() &&
2454 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002455 ssrc = media_desc->streams()[0].first_ssrc();
2456 }
2457 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002458 }
Steve Antondcc3c022017-12-22 16:02:54 -08002459 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002460 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002461 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002462 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002463 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002464 observer->OnTrack(transceiver);
2465 observer->OnAddTrack(transceiver->receiver(),
2466 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002467 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002468 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002469 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002470 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002471 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002472 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002473 }
2474 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002475 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002476 }
Steve Antondcc3c022017-12-22 16:02:54 -08002477 }
2478
Henrik Boströmfdb92012017-11-09 19:55:44 +01002479 const cricket::ContentInfo* audio_content =
2480 GetFirstAudioContent(remote_description()->description());
2481 const cricket::ContentInfo* video_content =
2482 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002483 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002484 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002485 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002486 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002487 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002488 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002489
2490 // Check if the descriptions include streams, just in case the peer supports
2491 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002492 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002493 (audio_desc && !audio_desc->streams().empty()) ||
2494 (video_desc && !video_desc->streams().empty())) {
2495 remote_peer_supports_msid_ = true;
2496 }
deadbeefab9b2d12015-10-14 11:33:11 -07002497
2498 // We wait to signal new streams until we finish processing the description,
2499 // since only at that point will new streams have all their tracks.
2500 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2501
Steve Antondcc3c022017-12-22 16:02:54 -08002502 if (!IsUnifiedPlan()) {
2503 // TODO(steveanton): When removing RTP senders/receivers in response to a
2504 // rejected media section, there is some cleanup logic that expects the
2505 // voice/ video channel to still be set. But in this method the voice/video
2506 // channel would have been destroyed by the SetRemoteDescription caller
2507 // above so the cleanup that relies on them fails to run. The RemoveSenders
2508 // calls should be moved to right before the DestroyChannel calls to fix
2509 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002510
Steve Antondcc3c022017-12-22 16:02:54 -08002511 // Find all audio rtp streams and create corresponding remote AudioTracks
2512 // and MediaStreams.
2513 if (audio_content) {
2514 if (audio_content->rejected) {
2515 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2516 } else {
2517 bool default_audio_track_needed =
2518 !remote_peer_supports_msid_ &&
2519 RtpTransceiverDirectionHasSend(audio_desc->direction());
2520 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2521 default_audio_track_needed, audio_desc->type(),
2522 new_streams);
2523 }
deadbeeffaac4972015-11-12 15:33:07 -08002524 }
deadbeefab9b2d12015-10-14 11:33:11 -07002525
Steve Antondcc3c022017-12-22 16:02:54 -08002526 // Find all video rtp streams and create corresponding remote VideoTracks
2527 // and MediaStreams.
2528 if (video_content) {
2529 if (video_content->rejected) {
2530 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2531 } else {
2532 bool default_video_track_needed =
2533 !remote_peer_supports_msid_ &&
2534 RtpTransceiverDirectionHasSend(video_desc->direction());
2535 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2536 default_video_track_needed, video_desc->type(),
2537 new_streams);
2538 }
deadbeeffaac4972015-11-12 15:33:07 -08002539 }
deadbeefab9b2d12015-10-14 11:33:11 -07002540
Steve Antondcc3c022017-12-22 16:02:54 -08002541 // Update the DataChannels with the information from the remote peer.
2542 if (data_desc) {
2543 if (rtc::starts_with(data_desc->protocol().data(),
2544 cricket::kMediaProtocolRtpPrefix)) {
2545 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2546 }
deadbeefab9b2d12015-10-14 11:33:11 -07002547 }
deadbeefab9b2d12015-10-14 11:33:11 -07002548
Steve Antondcc3c022017-12-22 16:02:54 -08002549 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002550 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002551 for (size_t i = 0; i < new_streams->count(); ++i) {
2552 MediaStreamInterface* new_stream = new_streams->at(i);
2553 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002554 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002555 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2556 }
deadbeefab9b2d12015-10-14 11:33:11 -07002557
Steve Antondcc3c022017-12-22 16:02:54 -08002558 UpdateEndedRemoteMediaStreams();
2559 }
deadbeefab9b2d12015-10-14 11:33:11 -07002560
Steve Anton8a006912017-12-04 15:25:56 -08002561 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002562}
2563
Steve Anton0f5400a2018-07-17 14:25:36 -07002564void PeerConnection::ProcessRemovalOfRemoteTrack(
2565 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2566 transceiver,
2567 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2568 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2569 RTC_DCHECK(transceiver->mid());
2570 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2571 << *transceiver->mid();
2572 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2573 transceiver->internal()->receiver_internal()->streams();
2574 // This will remove the remote track from the streams.
2575 transceiver->internal()->receiver_internal()->set_stream_ids({});
2576 remove_list->push_back(transceiver);
2577 // Remove any streams that no longer have tracks.
2578 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2579 // of streams, see if the stream was removed by checking if this was the
2580 // last receiver with that stream ID.
2581 for (auto stream : media_streams) {
2582 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2583 remote_streams_->RemoveStream(stream);
2584 removed_streams->push_back(stream);
2585 }
2586 }
2587}
2588
Steve Antondcc3c022017-12-22 16:02:54 -08002589RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2590 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002591 const SessionDescriptionInterface& new_session,
2592 const SessionDescriptionInterface* old_local_description,
2593 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002594 RTC_DCHECK(IsUnifiedPlan());
2595
Steve Anton7464fca2018-01-19 11:10:37 -08002596 const cricket::ContentGroup* bundle_group = nullptr;
2597 if (new_session.GetType() == SdpType::kOffer) {
2598 auto bundle_group_or_error =
2599 GetEarlyBundleGroup(*new_session.description());
2600 if (!bundle_group_or_error.ok()) {
2601 return bundle_group_or_error.MoveError();
2602 }
2603 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002604 }
Steve Antondcc3c022017-12-22 16:02:54 -08002605
Steve Antondcc3c022017-12-22 16:02:54 -08002606 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002607 for (size_t i = 0; i < new_contents.size(); ++i) {
2608 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002609 cricket::MediaType media_type = new_content.media_description()->type();
2610 seen_mids_.insert(new_content.name);
2611 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2612 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002613 const cricket::ContentInfo* old_local_content = nullptr;
2614 if (old_local_description &&
2615 i < old_local_description->description()->contents().size()) {
2616 old_local_content =
2617 &old_local_description->description()->contents()[i];
2618 }
2619 const cricket::ContentInfo* old_remote_content = nullptr;
2620 if (old_remote_description &&
2621 i < old_remote_description->description()->contents().size()) {
2622 old_remote_content =
2623 &old_remote_description->description()->contents()[i];
2624 }
Steve Antondcc3c022017-12-22 16:02:54 -08002625 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002626 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2627 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002628 if (!transceiver_or_error.ok()) {
2629 return transceiver_or_error.MoveError();
2630 }
2631 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002632 RTCError error =
2633 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2634 if (!error.ok()) {
2635 return error;
2636 }
2637 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002638 if (GetDataMid() && new_content.name != *GetDataMid()) {
2639 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002640 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2641 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002642 continue;
2643 }
2644 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2645 if (!error.ok()) {
2646 return error;
2647 }
Steve Antondcc3c022017-12-22 16:02:54 -08002648 } else {
2649 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2650 "Unknown section type.");
2651 }
2652 }
2653
2654 return RTCError::OK();
2655}
2656
2657RTCError PeerConnection::UpdateTransceiverChannel(
2658 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2659 transceiver,
2660 const cricket::ContentInfo& content,
2661 const cricket::ContentGroup* bundle_group) {
2662 RTC_DCHECK(IsUnifiedPlan());
2663 RTC_DCHECK(transceiver);
2664 cricket::BaseChannel* channel = transceiver->internal()->channel();
2665 if (content.rejected) {
2666 if (channel) {
2667 transceiver->internal()->SetChannel(nullptr);
2668 DestroyBaseChannel(channel);
2669 }
2670 } else {
2671 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002672 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002673 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002674 } else {
Steve Anton69470252018-02-09 11:43:08 -08002675 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002676 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002677 }
2678 if (!channel) {
2679 LOG_AND_RETURN_ERROR(
2680 RTCErrorType::INTERNAL_ERROR,
2681 "Failed to create channel for mid=" + content.name);
2682 }
2683 transceiver->internal()->SetChannel(channel);
2684 }
2685 }
2686 return RTCError::OK();
2687}
2688
Steve Antonfa2260d2017-12-28 16:38:23 -08002689RTCError PeerConnection::UpdateDataChannel(
2690 cricket::ContentSource source,
2691 const cricket::ContentInfo& content,
2692 const cricket::ContentGroup* bundle_group) {
2693 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002694 // If data channels are disabled, ignore this media section. CreateAnswer
2695 // will take care of rejecting it.
2696 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002697 }
2698 if (content.rejected) {
2699 DestroyDataChannel();
2700 } else {
2701 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002702 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002703 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2704 "Failed to create data channel.");
2705 }
2706 }
2707 if (source == cricket::CS_REMOTE) {
2708 const MediaContentDescription* data_desc = content.media_description();
2709 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2710 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2711 }
2712 }
2713 }
2714 return RTCError::OK();
2715}
2716
Steve Antondcc3c022017-12-22 16:02:54 -08002717RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2718PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002719 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002720 size_t mline_index,
2721 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002722 const ContentInfo* old_local_content,
2723 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002724 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002725 // If this is an offer then the m= section might be recycled. If the m=
2726 // section is being recycled (defined as: rejected in the current local or
2727 // remote description and not rejected in new description), dissociate the
2728 // currently associated RtpTransceiver by setting its mid property to null,
2729 // and discard the mapping between the transceiver and its m= section index.
2730 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2731 old_remote_content)) {
2732 // We want to dissociate the transceiver that has the rejected mid.
2733 const std::string& old_mid =
2734 (old_local_content && old_local_content->rejected)
2735 ? old_local_content->name
2736 : old_remote_content->name;
2737 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002738 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002739 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2740 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002741 old_transceiver->internal()->set_mid(absl::nullopt);
2742 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002743 }
2744 }
2745 const MediaContentDescription* media_desc = content.media_description();
2746 auto transceiver = GetAssociatedTransceiver(content.name);
2747 if (source == cricket::CS_LOCAL) {
2748 // Find the RtpTransceiver that corresponds to this m= section, using the
2749 // mapping between transceivers and m= section indices established when
2750 // creating the offer.
2751 if (!transceiver) {
2752 transceiver = GetTransceiverByMLineIndex(mline_index);
2753 }
2754 if (!transceiver) {
2755 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2756 "Unknown transceiver");
2757 }
2758 } else {
2759 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2760 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2761 // of the same type...
2762 if (!transceiver &&
2763 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2764 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2765 }
2766 // If no RtpTransceiver was found in the previous step, create one with a
2767 // recvonly direction.
2768 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002769 RTC_LOG(LS_INFO) << "Adding "
2770 << cricket::MediaTypeToString(media_desc->type())
2771 << " transceiver for MID=" << content.name
2772 << " at i=" << mline_index
2773 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002774 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002775 auto sender =
2776 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002777 std::string receiver_id;
2778 if (!media_desc->streams().empty()) {
2779 receiver_id = media_desc->streams()[0].id;
2780 } else {
2781 receiver_id = rtc::CreateRandomUuid();
2782 }
2783 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002784 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002785 transceiver->internal()->set_direction(
2786 RtpTransceiverDirection::kRecvOnly);
2787 }
2788 }
2789 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002790 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002791 LOG_AND_RETURN_ERROR(
2792 RTCErrorType::INVALID_PARAMETER,
2793 "Transceiver type does not match media description type.");
2794 }
2795 // Associate the found or created RtpTransceiver with the m= section by
2796 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2797 // section, and establish a mapping between the transceiver and the index of
2798 // the m= section.
2799 transceiver->internal()->set_mid(content.name);
2800 transceiver->internal()->set_mline_index(mline_index);
2801 return std::move(transceiver);
2802}
2803
2804rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2805PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2806 RTC_DCHECK(IsUnifiedPlan());
2807 for (auto transceiver : transceivers_) {
2808 if (transceiver->mid() == mid) {
2809 return transceiver;
2810 }
2811 }
2812 return nullptr;
2813}
2814
2815rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2816PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2817 RTC_DCHECK(IsUnifiedPlan());
2818 for (auto transceiver : transceivers_) {
2819 if (transceiver->internal()->mline_index() == mline_index) {
2820 return transceiver;
2821 }
2822 }
2823 return nullptr;
2824}
2825
2826rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2827PeerConnection::FindAvailableTransceiverToReceive(
2828 cricket::MediaType media_type) const {
2829 RTC_DCHECK(IsUnifiedPlan());
2830 // From JSEP section 5.10 (Applying a Remote Description):
2831 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2832 // the same type that were added to the PeerConnection by addTrack and are not
2833 // associated with any m= section and are not stopped, find the first such
2834 // RtpTransceiver.
2835 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002836 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002837 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2838 !transceiver->stopped()) {
2839 return transceiver;
2840 }
2841 }
2842 return nullptr;
2843}
2844
Steve Antoned10bd92017-12-05 10:52:59 -08002845const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2846 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2847 transceiver,
2848 const SessionDescriptionInterface* sdesc) const {
2849 RTC_DCHECK(transceiver);
2850 RTC_DCHECK(sdesc);
2851 if (IsUnifiedPlan()) {
2852 if (!transceiver->internal()->mid()) {
2853 // This transceiver is not associated with a media section yet.
2854 return nullptr;
2855 }
2856 return sdesc->description()->GetContentByName(
2857 *transceiver->internal()->mid());
2858 } else {
2859 // Plan B only allows at most one audio and one video section, so use the
2860 // first media section of that type.
2861 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002862 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002863 }
2864}
2865
deadbeef46c73892016-11-16 19:42:04 -08002866PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2867 return configuration_;
2868}
2869
deadbeef293e9262017-01-11 12:28:30 -08002870bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2871 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002872 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002873 if (IsClosed()) {
2874 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2875 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2876 }
2877
Qingsi Wanga2d60672018-04-11 16:57:45 -07002878 // According to JSEP, after setLocalDescription, changing the candidate pool
2879 // size is not allowed, and changing the set of ICE servers will not result
2880 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002881 if (local_description() && configuration.ice_candidate_pool_size !=
2882 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002883 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2884 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002885 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002886 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002887
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002888 if (local_description() &&
2889 configuration.use_media_transport != configuration_.use_media_transport) {
2890 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2891 "SetLocalDescription.";
2892 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2893 }
2894
2895 if (remote_description() &&
2896 configuration.use_media_transport != configuration_.use_media_transport) {
2897 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2898 "SetRemoteDescription.";
2899 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2900 }
2901
deadbeef293e9262017-01-11 12:28:30 -08002902 // The simplest (and most future-compatible) way to tell if the config was
2903 // modified in an invalid way is to copy each property we do support
2904 // modifying, then use operator==. There are far more properties we don't
2905 // support modifying than those we do, and more could be added.
2906 RTCConfiguration modified_config = configuration_;
2907 modified_config.servers = configuration.servers;
2908 modified_config.type = configuration.type;
2909 modified_config.ice_candidate_pool_size =
2910 configuration.ice_candidate_pool_size;
2911 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002912 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002913 modified_config.ice_check_interval_strong_connectivity =
2914 configuration.ice_check_interval_strong_connectivity;
2915 modified_config.ice_check_interval_weak_connectivity =
2916 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002917 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2918 modified_config.ice_unwritable_min_checks =
2919 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002920 modified_config.stun_candidate_keepalive_interval =
2921 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002922 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002923 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002924 modified_config.active_reset_srtp_params =
2925 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002926 modified_config.use_media_transport = configuration.use_media_transport;
deadbeef293e9262017-01-11 12:28:30 -08002927 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002928 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002929 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2930 }
2931
Steve Anton038834f2017-07-14 15:59:59 -07002932 // Validate the modified configuration.
2933 RTCError validate_error = ValidateConfiguration(modified_config);
2934 if (!validate_error.ok()) {
2935 return SafeSetError(std::move(validate_error), error);
2936 }
2937
deadbeef293e9262017-01-11 12:28:30 -08002938 // Note that this isn't possible through chromium, since it's an unsigned
2939 // short in WebIDL.
2940 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002941 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002942 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2943 }
2944
2945 // Parse ICE servers before hopping to network thread.
2946 cricket::ServerAddresses stun_servers;
2947 std::vector<cricket::RelayServerConfig> turn_servers;
2948 RTCErrorType parse_error =
2949 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2950 if (parse_error != RTCErrorType::NONE) {
2951 return SafeSetError(parse_error, error);
2952 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002953 // Note if STUN or TURN servers were supplied.
2954 if (!stun_servers.empty()) {
2955 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2956 }
2957 if (!turn_servers.empty()) {
2958 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2959 }
deadbeef293e9262017-01-11 12:28:30 -08002960
2961 // In theory this shouldn't fail.
2962 if (!network_thread()->Invoke<bool>(
2963 RTC_FROM_HERE,
2964 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2965 stun_servers, turn_servers, modified_config.type,
2966 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002967 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002968 modified_config.turn_customizer,
2969 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002970 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002971 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2972 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002973
deadbeefd1a38b52016-12-10 13:15:33 -08002974 // As described in JSEP, calling setConfiguration with new ICE servers or
2975 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2976 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002977 if (modified_config.servers != configuration_.servers ||
2978 modified_config.type != configuration_.type ||
2979 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002980 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002981 }
skvladd1f5fda2017-02-03 16:54:05 -08002982
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002983 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07002984 transport_controller_->SetMediaTransportFactory(
2985 modified_config.use_media_transport ? factory_->media_transport_factory()
2986 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08002987
Zhi Huangb57e1692018-06-12 11:41:11 -07002988 if (configuration_.active_reset_srtp_params !=
2989 modified_config.active_reset_srtp_params) {
2990 transport_controller_->SetActiveResetSrtpParams(
2991 modified_config.active_reset_srtp_params);
2992 }
2993
deadbeef293e9262017-01-11 12:28:30 -08002994 configuration_ = modified_config;
2995 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002996}
2997
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002998bool PeerConnection::AddIceCandidate(
2999 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003000 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003001 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003002 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003003 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003004 return false;
3005 }
Steve Antond25da372017-11-06 14:50:29 -08003006
3007 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003008 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003009 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003010 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003011 return false;
3012 }
3013
3014 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003015 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003016 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003017 return false;
3018 }
3019
3020 bool valid = false;
3021 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3022 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003023 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003024 return false;
3025 }
3026
3027 // Add this candidate to the remote session description.
3028 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003029 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003030 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003031 return false;
3032 }
3033
3034 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003035 bool result = UseCandidate(ice_candidate);
3036 if (result) {
3037 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3038 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3039 } else {
3040 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3041 }
3042 return result;
Steve Antond25da372017-11-06 14:50:29 -08003043 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003044 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003045 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003046 return true;
3047 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003048}
3049
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003050bool PeerConnection::RemoveIceCandidates(
3051 const std::vector<cricket::Candidate>& candidates) {
3052 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003053 if (IsClosed()) {
3054 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3055 return false;
3056 }
3057
Steve Antond25da372017-11-06 14:50:29 -08003058 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003059 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3060 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003061 return false;
3062 }
3063
3064 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003065 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003066 return false;
3067 }
3068
3069 size_t number_removed =
3070 mutable_remote_description()->RemoveCandidates(candidates);
3071 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003072 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003073 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003074 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003075 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003076 }
3077
3078 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003079 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3080 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003081 RTC_LOG(LS_ERROR)
3082 << "RemoveIceCandidates: Error when removing remote candidates: "
3083 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003084 }
3085 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003086}
3087
Niels Möller0c4f7be2018-05-07 14:01:37 +02003088RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003089 if (!worker_thread()->IsCurrent()) {
3090 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003091 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003092 }
3093
Niels Möller0c4f7be2018-05-07 14:01:37 +02003094 const bool has_min = bitrate.min_bitrate_bps.has_value();
3095 const bool has_start = bitrate.start_bitrate_bps.has_value();
3096 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003097 if (has_min && *bitrate.min_bitrate_bps < 0) {
3098 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3099 "min_bitrate_bps <= 0");
3100 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003101 if (has_start) {
3102 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003103 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003104 "start_bitrate_bps < min_bitrate_bps");
3105 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003106 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3107 "curent_bitrate_bps < 0");
3108 }
3109 }
3110 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003111 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003112 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003113 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003114 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3115 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3116 "max_bitrate_bps < min_bitrate_bps");
3117 } else if (*bitrate.max_bitrate_bps < 0) {
3118 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3119 "max_bitrate_bps < 0");
3120 }
3121 }
3122
zstein4b979802017-06-02 14:37:37 -07003123 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003124 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003125
3126 return RTCError::OK();
3127}
3128
Alex Narest78609d52017-10-20 10:37:47 +02003129void PeerConnection::SetBitrateAllocationStrategy(
3130 std::unique_ptr<rtc::BitrateAllocationStrategy>
3131 bitrate_allocation_strategy) {
3132 rtc::Thread* worker_thread = factory_->worker_thread();
3133 if (!worker_thread->IsCurrent()) {
3134 rtc::BitrateAllocationStrategy* strategy_raw =
3135 bitrate_allocation_strategy.release();
3136 auto functor = [this, strategy_raw]() {
3137 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003138 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003139 };
3140 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3141 return;
3142 }
3143 RTC_DCHECK(call_.get());
3144 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3145}
3146
henrika5f6bf242017-11-01 11:06:56 +01003147void PeerConnection::SetAudioPlayout(bool playout) {
3148 if (!worker_thread()->IsCurrent()) {
3149 worker_thread()->Invoke<void>(
3150 RTC_FROM_HERE,
3151 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3152 return;
3153 }
3154 auto audio_state =
3155 factory_->channel_manager()->media_engine()->GetAudioState();
3156 audio_state->SetPlayout(playout);
3157}
3158
3159void PeerConnection::SetAudioRecording(bool recording) {
3160 if (!worker_thread()->IsCurrent()) {
3161 worker_thread()->Invoke<void>(
3162 RTC_FROM_HERE,
3163 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3164 return;
3165 }
3166 auto audio_state =
3167 factory_->channel_manager()->media_engine()->GetAudioState();
3168 audio_state->SetRecording(recording);
3169}
3170
Steve Anton8c0f7a72017-10-03 10:03:10 -07003171std::unique_ptr<rtc::SSLCertificate>
3172PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003173 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3174 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003175 return nullptr;
3176 }
Steve Antonf25303e2018-10-16 15:23:31 -07003177 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003178}
3179
Zhi Huang70b820f2018-01-27 14:16:15 -08003180std::unique_ptr<rtc::SSLCertChain>
3181PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003182 auto audio_transceiver = GetFirstAudioTransceiver();
3183 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003184 return nullptr;
3185 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003186 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003187 audio_transceiver->internal()->channel()->transport_name());
3188}
3189
3190rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3191PeerConnection::GetFirstAudioTransceiver() const {
3192 for (auto transceiver : transceivers_) {
3193 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3194 return transceiver;
3195 }
3196 }
3197 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003198}
3199
ivoc14d5dbe2016-07-04 07:06:55 -07003200bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3201 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003202 // TODO(eladalon): It would be better to not allow negative values into PC.
3203 const size_t max_size = (max_size_bytes < 0)
3204 ? RtcEventLog::kUnlimitedOutput
3205 : rtc::saturated_cast<size_t>(max_size_bytes);
3206 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003207 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003208 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003209}
3210
Bjorn Tereliusde939432017-11-20 17:38:14 +01003211bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3212 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003213 // TODO(eladalon): In C++14, this can be done with a lambda.
3214 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003215 bool operator()() {
3216 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3217 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003218 PeerConnection* const pc;
3219 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003220 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003221 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003222 return worker_thread()->Invoke<bool>(
3223 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003224}
3225
3226void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003227 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003228 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3229}
3230
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003231const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003232 return pending_local_description_ ? pending_local_description_.get()
3233 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234}
3235
3236const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003237 return pending_remote_description_ ? pending_remote_description_.get()
3238 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003239}
3240
deadbeeffe4a8a42016-12-20 17:56:17 -08003241const SessionDescriptionInterface* PeerConnection::current_local_description()
3242 const {
Steve Anton75737c02017-11-06 10:37:17 -08003243 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003244}
3245
3246const SessionDescriptionInterface* PeerConnection::current_remote_description()
3247 const {
Steve Anton75737c02017-11-06 10:37:17 -08003248 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003249}
3250
3251const SessionDescriptionInterface* PeerConnection::pending_local_description()
3252 const {
Steve Anton75737c02017-11-06 10:37:17 -08003253 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003254}
3255
3256const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3257 const {
Steve Anton75737c02017-11-06 10:37:17 -08003258 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003259}
3260
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003261void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003262 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003263 // Update stats here so that we have the most recent stats for tracks and
3264 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003265 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003266
Steve Anton75737c02017-11-06 10:37:17 -08003267 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003268 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003269
Steve Anton8af21862017-12-15 11:20:13 -08003270 for (auto transceiver : transceivers_) {
3271 transceiver->Stop();
3272 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003273
3274 // Ensure that all asynchronous stats requests are completed before destroying
3275 // the transport controller below.
3276 if (stats_collector_) {
3277 stats_collector_->WaitForPendingRequest();
3278 }
3279
3280 // Don't destroy BaseChannels until after stats has been cleaned up so that
3281 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003282 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003283
Qingsi Wang93a84392018-01-30 17:13:09 -08003284 // The event log is used in the transport controller, which must be outlived
3285 // by the former. CreateOffer by the peer connection is implemented
3286 // asynchronously and if the peer connection is closed without resetting the
3287 // WebRTC session description factory, the session description factory would
3288 // call the transport controller.
3289 webrtc_session_desc_factory_.reset();
3290 transport_controller_.reset();
3291
deadbeef42a42632017-03-10 15:18:00 -08003292 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003293 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3294 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003295
Steve Anton978b8762017-09-29 12:15:02 -07003296 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003297 call_.reset();
3298 // The event log must outlive call (and any other object that uses it).
3299 event_log_.reset();
3300 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003301 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003302 // The .h file says that observer can be discarded after close() returns.
3303 // Make sure this is true.
3304 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003305}
3306
Steve Antonad182762018-09-05 20:22:40 +00003307void PeerConnection::OnMessage(rtc::Message* msg) {
3308 switch (msg->message_id) {
3309 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3310 SetSessionDescriptionMsg* param =
3311 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3312 param->observer->OnSuccess();
3313 delete param;
3314 break;
3315 }
3316 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3317 SetSessionDescriptionMsg* param =
3318 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3319 param->observer->OnFailure(std::move(param->error));
3320 delete param;
3321 break;
3322 }
3323 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3324 CreateSessionDescriptionMsg* param =
3325 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3326 param->observer->OnFailure(std::move(param->error));
3327 delete param;
3328 break;
3329 }
3330 case MSG_GETSTATS: {
3331 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3332 StatsReports reports;
3333 stats_->GetStats(param->track, &reports);
3334 param->observer->OnComplete(reports);
3335 delete param;
3336 break;
3337 }
3338 case MSG_FREE_DATACHANNELS: {
3339 sctp_data_channels_to_free_.clear();
3340 break;
3341 }
3342 case MSG_REPORT_USAGE_PATTERN: {
3343 ReportUsagePattern();
3344 break;
3345 }
3346 default:
3347 RTC_NOTREACHED() << "Not implemented";
3348 break;
3349 }
3350}
3351
Steve Antonafb0bb72018-02-20 11:35:37 -08003352cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3353 RTC_DCHECK(!IsUnifiedPlan());
3354 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3355 GetAudioTransceiver()->internal()->channel());
3356 if (voice_channel) {
3357 return voice_channel->media_channel();
3358 } else {
3359 return nullptr;
3360 }
3361}
3362
3363cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3364 RTC_DCHECK(!IsUnifiedPlan());
3365 auto* video_channel = static_cast<cricket::VideoChannel*>(
3366 GetVideoTransceiver()->internal()->channel());
3367 if (video_channel) {
3368 return video_channel->media_channel();
3369 } else {
3370 return nullptr;
3371 }
3372}
3373
Steve Anton4171afb2017-11-20 10:20:22 -08003374void PeerConnection::CreateAudioReceiver(
3375 MediaStreamInterface* stream,
3376 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003377 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3378 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003379 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3380 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003381 auto* audio_receiver = new AudioRtpReceiver(
3382 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003383 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003384 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3385 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3386 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003387 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003388 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003389 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003390}
3391
Steve Anton4171afb2017-11-20 10:20:22 -08003392void PeerConnection::CreateVideoReceiver(
3393 MediaStreamInterface* stream,
3394 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003395 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3396 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003397 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3398 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003399 auto* video_receiver = new VideoRtpReceiver(
3400 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003401 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003402 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3403 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3404 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003405 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003406 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003407 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003408}
3409
deadbeef70ab1a12015-09-28 16:53:55 -07003410// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3411// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003412rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003413 const RtpSenderInfo& remote_sender_info) {
3414 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3415 if (!receiver) {
3416 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3417 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003418 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003419 }
Steve Anton4171afb2017-11-20 10:20:22 -08003420 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3421 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3422 } else {
3423 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3424 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003425 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003426}
3427
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003428void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3429 MediaStreamInterface* stream) {
3430 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003431 RTC_DCHECK(track);
3432 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003433 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003434 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003435 // We already have a sender for this track, so just change the stream_id
3436 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003437 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003438 return;
3439 }
3440
3441 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003442 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003443 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003444 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003445 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003446 // If the sender has already been configured in SDP, we call SetSsrc,
3447 // which will connect the sender to the underlying transport. This can
3448 // occur if a local session description that contains the ID of the sender
3449 // is set before AddStream is called. It can also occur if the local
3450 // session description is not changed and RemoveStream is called, and
3451 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003452 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003453 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003454 if (sender_info) {
3455 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003456 }
3457}
3458
3459// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3460// indefinitely, when we have unified plan SDP.
3461void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3462 MediaStreamInterface* stream) {
3463 RTC_DCHECK(!IsClosed());
3464 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003465 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003466 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3467 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003468 return;
3469 }
Steve Anton4171afb2017-11-20 10:20:22 -08003470 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003471}
3472
3473void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3474 MediaStreamInterface* stream) {
3475 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003476 RTC_DCHECK(track);
3477 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003478 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003479 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003480 // We already have a sender for this track, so just change the stream_id
3481 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003482 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003483 return;
3484 }
3485
3486 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003487 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003488 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003489 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003490 GetVideoTransceiver()->internal()->AddSender(new_sender);
3491 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003492 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003493 if (sender_info) {
3494 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003495 }
3496}
3497
3498void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3499 MediaStreamInterface* stream) {
3500 RTC_DCHECK(!IsClosed());
3501 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003502 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003503 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3504 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003505 return;
3506 }
Steve Anton4171afb2017-11-20 10:20:22 -08003507 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003508}
3509
Steve Antonba818672017-11-06 10:21:57 -08003510void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003511 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003512 if (ice_connection_state_ == new_state) {
3513 return;
3514 }
3515
deadbeefcbecd352015-09-23 11:50:27 -07003516 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003517 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003518 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003519 return;
3520 }
Steve Antonba818672017-11-06 10:21:57 -08003521
Mirko Bonadei675513b2017-11-09 11:09:25 +01003522 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3523 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003524 RTC_DCHECK(ice_connection_state_ !=
3525 PeerConnectionInterface::kIceConnectionClosed);
3526
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003527 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003528 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003529}
3530
3531void PeerConnection::OnIceGatheringChange(
3532 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003533 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003534 if (IsClosed()) {
3535 return;
3536 }
3537 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003538 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003539}
3540
jbauch81bf7b02017-03-25 08:31:12 -07003541void PeerConnection::OnIceCandidate(
3542 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003543 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003544 if (IsClosed()) {
3545 return;
3546 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003547 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003548 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3549 candidate->candidate().address().IsPrivateIP()) {
3550 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3551 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003552 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003553}
3554
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003555void PeerConnection::OnIceCandidatesRemoved(
3556 const std::vector<cricket::Candidate>& candidates) {
3557 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003558 if (IsClosed()) {
3559 return;
3560 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003561 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003562}
3563
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003564void PeerConnection::ChangeSignalingState(
3565 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003566 RTC_DCHECK(signaling_thread()->IsCurrent());
3567 if (signaling_state_ == signaling_state) {
3568 return;
3569 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003570 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3571 << GetSignalingStateString(signaling_state_)
3572 << " New state: "
3573 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003574 signaling_state_ = signaling_state;
3575 if (signaling_state == kClosed) {
3576 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003577 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003578 if (ice_gathering_state_ != kIceGatheringComplete) {
3579 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003580 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003581 }
3582 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003583 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003584}
3585
deadbeefeb459812015-12-15 19:24:43 -08003586void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3587 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003588 if (IsClosed()) {
3589 return;
3590 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003591 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003592 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003593}
3594
deadbeefeb459812015-12-15 19:24:43 -08003595void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3596 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003597 if (IsClosed()) {
3598 return;
3599 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003600 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003601 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003602}
3603
3604void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3605 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003606 if (IsClosed()) {
3607 return;
3608 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003609 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003610 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003611}
3612
3613void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3614 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003615 if (IsClosed()) {
3616 return;
3617 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003618 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003619 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003620}
3621
Henrik Boström31638672017-11-23 17:48:32 +01003622void PeerConnection::PostSetSessionDescriptionSuccess(
3623 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003624 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3625 signaling_thread()->Post(RTC_FROM_HERE, this,
3626 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003627}
3628
deadbeefab9b2d12015-10-14 11:33:11 -07003629void PeerConnection::PostSetSessionDescriptionFailure(
3630 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003631 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003632 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003633 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3634 msg->error = std::move(error);
3635 signaling_thread()->Post(RTC_FROM_HERE, this,
3636 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003637}
3638
3639void PeerConnection::PostCreateSessionDescriptionFailure(
3640 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003641 RTCError error) {
3642 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003643 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3644 msg->error = std::move(error);
3645 signaling_thread()->Post(RTC_FROM_HERE, this,
3646 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003647}
3648
zhihuang1c378ed2017-08-17 14:10:50 -07003649void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003650 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003651 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003652 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003653
Steve Antondcc3c022017-12-22 16:02:54 -08003654 if (IsUnifiedPlan()) {
3655 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3656 } else {
3657 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3658 }
3659
Steve Antonfa2260d2017-12-28 16:38:23 -08003660 // Intentionally unset the data channel type for RTP data channel with the
3661 // second condition. Otherwise the RTP data channels would be successfully
3662 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3663 // when building with chromium. We want to leave RTP data channels broken, so
3664 // people won't try to use them.
3665 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3666 session_options->data_channel_type = data_channel_type();
3667 }
3668
Steve Antondcc3c022017-12-22 16:02:54 -08003669 // Apply ICE restart flag and renomination flag.
3670 for (auto& options : session_options->media_description_options) {
3671 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3672 options.transport_options.enable_ice_renomination =
3673 configuration_.enable_ice_renomination;
3674 }
3675
3676 session_options->rtcp_cname = rtcp_cname_;
3677 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003678 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003679 session_options->pooled_ice_credentials =
3680 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3681 RTC_FROM_HERE,
3682 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3683 port_allocator_.get()));
Steve Antondcc3c022017-12-22 16:02:54 -08003684}
3685
3686void PeerConnection::GetOptionsForPlanBOffer(
3687 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3688 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003689 // Figure out transceiver directional preferences.
3690 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3691 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3692
3693 // By default, generate sendrecv/recvonly m= sections.
3694 bool recv_audio = true;
3695 bool recv_video = true;
3696
3697 // By default, only offer a new m= section if we have media to send with it.
3698 bool offer_new_audio_description = send_audio;
3699 bool offer_new_video_description = send_video;
3700 bool offer_new_data_description = HasDataChannels();
3701
3702 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003703 if (offer_answer_options.offer_to_receive_audio !=
3704 RTCOfferAnswerOptions::kUndefined) {
3705 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003706 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003707 offer_new_audio_description ||
3708 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003709 }
Steve Antondcc3c022017-12-22 16:02:54 -08003710 if (offer_answer_options.offer_to_receive_video !=
3711 RTCOfferAnswerOptions::kUndefined) {
3712 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003713 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003714 offer_new_video_description ||
3715 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003716 }
3717
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003718 absl::optional<size_t> audio_index;
3719 absl::optional<size_t> video_index;
3720 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003721 // If a current description exists, generate m= sections in the same order,
3722 // using the first audio/video/data section that appears and rejecting
3723 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003724 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003725 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003726 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003727 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3728 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3729 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003730 }
3731
zhihuang1c378ed2017-08-17 14:10:50 -07003732 // Add audio/video/data m= sections to the end if needed.
3733 if (!audio_index && offer_new_audio_description) {
3734 session_options->media_description_options.push_back(
3735 cricket::MediaDescriptionOptions(
3736 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003737 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3738 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003739 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003740 }
zhihuang1c378ed2017-08-17 14:10:50 -07003741 if (!video_index && offer_new_video_description) {
3742 session_options->media_description_options.push_back(
3743 cricket::MediaDescriptionOptions(
3744 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003745 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3746 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003747 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003748 }
zhihuang1c378ed2017-08-17 14:10:50 -07003749 if (!data_index && offer_new_data_description) {
3750 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003751 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003752 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003753 }
3754
3755 cricket::MediaDescriptionOptions* audio_media_description_options =
3756 !audio_index ? nullptr
3757 : &session_options->media_description_options[*audio_index];
3758 cricket::MediaDescriptionOptions* video_media_description_options =
3759 !video_index ? nullptr
3760 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003761
Steve Anton4171afb2017-11-20 10:20:22 -08003762 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003763 video_media_description_options,
3764 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003765}
3766
3767// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3768// and return a reference to it.
3769// Generated MIDs should be no more than 3 bytes long to take up less space in
3770// the RTP packet.
3771static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3772 RTC_DCHECK(used_mids);
3773 // We're boring: just generate MIDs 0, 1, 2, ...
3774 size_t i = 0;
3775 std::set<std::string>::iterator it;
3776 bool inserted;
3777 do {
3778 std::string mid = rtc::ToString(i++);
3779 auto insert_result = used_mids->insert(mid);
3780 it = insert_result.first;
3781 inserted = insert_result.second;
3782 } while (!inserted);
3783 return *it;
3784}
3785
3786static cricket::MediaDescriptionOptions
3787GetMediaDescriptionOptionsForTransceiver(
3788 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3789 transceiver,
3790 const std::string& mid) {
3791 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003792 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003793 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003794 // This behavior is specified in JSEP. The gist is that:
3795 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3796 // sendrecv.
3797 // 2. If the MSID is included, then it must be included in any subsequent
3798 // offer/answer exactly the same until the RtpTransceiver is stopped.
3799 if (!transceiver->stopped() &&
3800 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3801 transceiver->internal()->has_ever_been_used_to_send())) {
3802 cricket::SenderOptions sender_options;
3803 sender_options.track_id = transceiver->sender()->id();
3804 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003805 int num_send_encoding_layers =
3806 transceiver->sender()->init_send_encodings().size();
3807 sender_options.num_sim_layers =
3808 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003809 media_description_options.sender_options.push_back(sender_options);
3810 }
Steve Antondcc3c022017-12-22 16:02:54 -08003811 return media_description_options;
3812}
3813
3814void PeerConnection::GetOptionsForUnifiedPlanOffer(
3815 const RTCOfferAnswerOptions& offer_answer_options,
3816 cricket::MediaSessionOptions* session_options) {
3817 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3818 // Offers) and 5.2.2 (Subsequent Offers).
3819 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3820 const ContentInfos& local_contents =
3821 (local_description() ? local_description()->description()->contents()
3822 : ContentInfos());
3823 const ContentInfos& remote_contents =
3824 (remote_description() ? remote_description()->description()->contents()
3825 : ContentInfos());
3826 // The mline indices that can be recycled. New transceivers should reuse these
3827 // slots first.
3828 std::queue<size_t> recycleable_mline_indices;
3829 // Track the MIDs used in previous offer/answer exchanges and the current
3830 // offer so that new, unique MIDs are generated.
3831 std::set<std::string> used_mids = seen_mids_;
3832 // First, go through each media section that exists in either the local or
3833 // remote description and generate a media section in this offer for the
3834 // associated transceiver. If a media section can be recycled, generate a
3835 // default, rejected media section here that can be later overwritten.
3836 for (size_t i = 0;
3837 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3838 // Either |local_content| or |remote_content| is non-null.
3839 const ContentInfo* local_content =
3840 (i < local_contents.size() ? &local_contents[i] : nullptr);
3841 const ContentInfo* remote_content =
3842 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3843 bool had_been_rejected = (local_content && local_content->rejected) ||
3844 (remote_content && remote_content->rejected);
3845 const std::string& mid =
3846 (local_content ? local_content->name : remote_content->name);
3847 cricket::MediaType media_type =
3848 (local_content ? local_content->media_description()->type()
3849 : remote_content->media_description()->type());
3850 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3851 media_type == cricket::MEDIA_TYPE_VIDEO) {
3852 auto transceiver = GetAssociatedTransceiver(mid);
3853 RTC_CHECK(transceiver);
3854 // A media section is considered eligible for recycling if it is marked as
3855 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003856 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003857 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003858 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3859 RtpTransceiverDirection::kInactive,
3860 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003861 recycleable_mline_indices.push(i);
3862 } else {
3863 session_options->media_description_options.push_back(
3864 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3865 // CreateOffer shouldn't really cause any state changes in
3866 // PeerConnection, but we need a way to match new transceivers to new
3867 // media sections in SetLocalDescription and JSEP specifies this is done
3868 // by recording the index of the media section generated for the
3869 // transceiver in the offer.
3870 transceiver->internal()->set_mline_index(i);
3871 }
3872 } else {
3873 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003874 RTC_CHECK(GetDataMid());
3875 if (had_been_rejected || mid != *GetDataMid()) {
3876 session_options->media_description_options.push_back(
3877 GetMediaDescriptionOptionsForRejectedData(mid));
3878 } else {
3879 session_options->media_description_options.push_back(
3880 GetMediaDescriptionOptionsForActiveData(mid));
3881 }
Steve Antondcc3c022017-12-22 16:02:54 -08003882 }
3883 }
3884 // Next, look for transceivers that are newly added (that is, are not stopped
3885 // and not associated). Reuse media sections marked as recyclable first,
3886 // otherwise append to the end of the offer. New media sections should be
3887 // added in the order they were added to the PeerConnection.
3888 for (auto transceiver : transceivers_) {
3889 if (transceiver->mid() || transceiver->stopped()) {
3890 continue;
3891 }
3892 size_t mline_index;
3893 if (!recycleable_mline_indices.empty()) {
3894 mline_index = recycleable_mline_indices.front();
3895 recycleable_mline_indices.pop();
3896 session_options->media_description_options[mline_index] =
3897 GetMediaDescriptionOptionsForTransceiver(transceiver,
3898 AllocateMid(&used_mids));
3899 } else {
3900 mline_index = session_options->media_description_options.size();
3901 session_options->media_description_options.push_back(
3902 GetMediaDescriptionOptionsForTransceiver(transceiver,
3903 AllocateMid(&used_mids)));
3904 }
3905 // See comment above for why CreateOffer changes the transceiver's state.
3906 transceiver->internal()->set_mline_index(mline_index);
3907 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003908 // Lastly, add a m-section if we have local data channels and an m section
3909 // does not already exist.
3910 if (!GetDataMid() && HasDataChannels()) {
3911 session_options->media_description_options.push_back(
3912 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3913 }
Steve Antondcc3c022017-12-22 16:02:54 -08003914}
3915
3916void PeerConnection::GetOptionsForAnswer(
3917 const RTCOfferAnswerOptions& offer_answer_options,
3918 cricket::MediaSessionOptions* session_options) {
3919 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3920
3921 if (IsUnifiedPlan()) {
3922 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3923 } else {
3924 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3925 }
3926
Steve Antonfa2260d2017-12-28 16:38:23 -08003927 // Intentionally unset the data channel type for RTP data channel. Otherwise
3928 // the RTP data channels would be successfully negotiated by default and the
3929 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3930 // We want to leave RTP data channels broken, so people won't try to use them.
3931 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3932 session_options->data_channel_type = data_channel_type();
3933 }
3934
Steve Antondcc3c022017-12-22 16:02:54 -08003935 // Apply ICE renomination flag.
3936 for (auto& options : session_options->media_description_options) {
3937 options.transport_options.enable_ice_renomination =
3938 configuration_.enable_ice_renomination;
3939 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003940
3941 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003942 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003943 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003944 session_options->pooled_ice_credentials =
3945 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3946 RTC_FROM_HERE,
3947 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3948 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07003949}
3950
Steve Antondcc3c022017-12-22 16:02:54 -08003951void PeerConnection::GetOptionsForPlanBAnswer(
3952 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003953 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003954 // Figure out transceiver directional preferences.
3955 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3956 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3957
3958 // By default, generate sendrecv/recvonly m= sections. The direction is also
3959 // restricted by the direction in the offer.
3960 bool recv_audio = true;
3961 bool recv_video = true;
3962
3963 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003964 if (offer_answer_options.offer_to_receive_audio !=
3965 RTCOfferAnswerOptions::kUndefined) {
3966 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003967 }
Steve Antondcc3c022017-12-22 16:02:54 -08003968 if (offer_answer_options.offer_to_receive_video !=
3969 RTCOfferAnswerOptions::kUndefined) {
3970 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003971 }
3972
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003973 absl::optional<size_t> audio_index;
3974 absl::optional<size_t> video_index;
3975 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003976
3977 // Generate m= sections that match those in the offer.
3978 // Note that mediasession.cc will handle intersection our preferred
3979 // direction with the offered direction.
3980 GenerateMediaDescriptionOptions(
3981 remote_description(),
3982 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3983 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3984 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003985
3986 cricket::MediaDescriptionOptions* audio_media_description_options =
3987 !audio_index ? nullptr
3988 : &session_options->media_description_options[*audio_index];
3989 cricket::MediaDescriptionOptions* video_media_description_options =
3990 !video_index ? nullptr
3991 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003992
Steve Anton4171afb2017-11-20 10:20:22 -08003993 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003994 video_media_description_options,
3995 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003996}
zhihuangaf388472016-11-02 16:49:48 -07003997
Steve Antondcc3c022017-12-22 16:02:54 -08003998void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3999 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4000 cricket::MediaSessionOptions* session_options) {
4001 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4002 // Answers) and 5.3.2 (Subsequent Answers).
4003 RTC_DCHECK(remote_description());
4004 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4005 for (const ContentInfo& content :
4006 remote_description()->description()->contents()) {
4007 cricket::MediaType media_type = content.media_description()->type();
4008 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4009 media_type == cricket::MEDIA_TYPE_VIDEO) {
4010 auto transceiver = GetAssociatedTransceiver(content.name);
4011 RTC_CHECK(transceiver);
4012 session_options->media_description_options.push_back(
4013 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4014 } else {
4015 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004016 // Reject all data sections if data channels are disabled.
4017 // Reject a data section if it has already been rejected.
4018 // Reject all data sections except for the first one.
4019 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4020 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004021 session_options->media_description_options.push_back(
4022 GetMediaDescriptionOptionsForRejectedData(content.name));
4023 } else {
4024 session_options->media_description_options.push_back(
4025 GetMediaDescriptionOptionsForActiveData(content.name));
4026 }
Steve Antondcc3c022017-12-22 16:02:54 -08004027 }
4028 }
htaa2a49d92016-03-04 02:51:39 -08004029}
4030
zhihuang1c378ed2017-08-17 14:10:50 -07004031void PeerConnection::GenerateMediaDescriptionOptions(
4032 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004033 RtpTransceiverDirection audio_direction,
4034 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004035 absl::optional<size_t>* audio_index,
4036 absl::optional<size_t>* video_index,
4037 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004038 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004039 for (const cricket::ContentInfo& content :
4040 session_desc->description()->contents()) {
4041 if (IsAudioContent(&content)) {
4042 // If we already have an audio m= section, reject this extra one.
4043 if (*audio_index) {
4044 session_options->media_description_options.push_back(
4045 cricket::MediaDescriptionOptions(
4046 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004047 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004048 } else {
4049 session_options->media_description_options.push_back(
4050 cricket::MediaDescriptionOptions(
4051 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004052 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004053 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004054 }
4055 } else if (IsVideoContent(&content)) {
4056 // If we already have an video m= section, reject this extra one.
4057 if (*video_index) {
4058 session_options->media_description_options.push_back(
4059 cricket::MediaDescriptionOptions(
4060 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004061 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004062 } else {
4063 session_options->media_description_options.push_back(
4064 cricket::MediaDescriptionOptions(
4065 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004066 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004067 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004068 }
4069 } else {
4070 RTC_DCHECK(IsDataContent(&content));
4071 // If we already have an data m= section, reject this extra one.
4072 if (*data_index) {
4073 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004074 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004075 } else {
4076 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004077 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004078 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004079 }
4080 }
htaa2a49d92016-03-04 02:51:39 -08004081 }
deadbeefab9b2d12015-10-14 11:33:11 -07004082}
4083
Steve Antonfa2260d2017-12-28 16:38:23 -08004084cricket::MediaDescriptionOptions
4085PeerConnection::GetMediaDescriptionOptionsForActiveData(
4086 const std::string& mid) const {
4087 // Direction for data sections is meaningless, but legacy endpoints might
4088 // expect sendrecv.
4089 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4090 RtpTransceiverDirection::kSendRecv,
4091 /*stopped=*/false);
4092 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4093 return options;
4094}
4095
4096cricket::MediaDescriptionOptions
4097PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4098 const std::string& mid) const {
4099 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4100 RtpTransceiverDirection::kInactive,
4101 /*stopped=*/true);
4102 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4103 return options;
4104}
4105
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004106absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004107 switch (data_channel_type_) {
4108 case cricket::DCT_RTP:
4109 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004110 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004111 }
4112 return rtp_data_channel_->content_name();
4113 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004114 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004115 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004116 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004117 }
4118}
4119
Steve Anton4171afb2017-11-20 10:20:22 -08004120void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4121 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4122 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004123 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004124}
4125
Steve Anton4171afb2017-11-20 10:20:22 -08004126void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004127 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004128 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004129 cricket::MediaType media_type,
4130 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004131 RTC_DCHECK(!IsUnifiedPlan());
4132
Steve Anton4171afb2017-11-20 10:20:22 -08004133 std::vector<RtpSenderInfo>* current_senders =
4134 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004135
Steve Anton4171afb2017-11-20 10:20:22 -08004136 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004137 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004138 for (auto sender_it = current_senders->begin();
4139 sender_it != current_senders->end();
4140 /* incremented manually */) {
4141 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004142 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004143 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004144 std::string params_stream_id;
4145 if (params) {
4146 params_stream_id =
4147 (!params->first_stream_id().empty() ? params->first_stream_id()
4148 : kDefaultStreamId);
4149 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004150 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004151 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004152 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004153 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004154 sender_exists) {
4155 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004156 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004157 OnRemoteSenderRemoved(info, media_type);
4158 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004159 }
4160 }
4161
Steve Anton4171afb2017-11-20 10:20:22 -08004162 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004163 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004164 if (!params.has_ssrcs()) {
4165 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4166 // sender, this means it is coming from a Unified Plan endpoint,so we just
4167 // create a default.
4168 default_sender_needed = true;
4169 break;
4170 }
4171
Seth Hampson845e8782018-03-02 11:34:10 -08004172 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004173 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004174 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4175 // not supported in Plan B, we just take the first here and create the
4176 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004177 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004178 (!params.first_stream_id().empty() ? params.first_stream_id()
4179 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004180 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004181 uint32_t ssrc = params.first_ssrc();
4182
4183 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004184 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004185 if (!stream) {
4186 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004187 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004188 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004189 remote_streams_->AddStream(stream);
4190 new_streams->AddStream(stream);
4191 }
4192
Steve Anton4171afb2017-11-20 10:20:22 -08004193 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004194 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004195 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004196 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004197 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004198 }
4199 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004200
Steve Anton4171afb2017-11-20 10:20:22 -08004201 // Add default sender if necessary.
4202 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004203 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004204 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004205 if (!default_stream) {
4206 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004207 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004208 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004209 remote_streams_->AddStream(default_stream);
4210 new_streams->AddStream(default_stream);
4211 }
Steve Anton4171afb2017-11-20 10:20:22 -08004212 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4213 ? kDefaultAudioSenderId
4214 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004215 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004216 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004217 if (!default_sender_info) {
4218 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004219 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004220 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004221 }
4222 }
deadbeefab9b2d12015-10-14 11:33:11 -07004223}
4224
Steve Anton4171afb2017-11-20 10:20:22 -08004225void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4226 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004227 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4228 << " receiver for track_id=" << sender_info.sender_id
4229 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004230
Steve Anton3d954a62018-04-02 11:27:23 -07004231 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004232 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004233 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004234 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004235 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004236 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004237 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004238 }
4239}
4240
Steve Anton4171afb2017-11-20 10:20:22 -08004241void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4242 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004243 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4244 << " receiver for track_id=" << sender_info.sender_id
4245 << " and stream_id=" << sender_info.stream_id;
4246
Seth Hampson845e8782018-03-02 11:34:10 -08004247 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004248
Henrik Boström933d8b02017-10-10 10:05:16 -07004249 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004250 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004251 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4252 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004253 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004254 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004255 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004256 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004257 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004258 }
4259 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004260 // Stopping or destroying a VideoRtpReceiver will end the
4261 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004262 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004263 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004264 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004265 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004266 // There's no guarantee the track is still available, e.g. the track may
4267 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004268 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004269 }
4270 } else {
nisseede5da42017-01-12 05:15:36 -08004271 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004272 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004273 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004274 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004275 }
deadbeefab9b2d12015-10-14 11:33:11 -07004276}
4277
4278void PeerConnection::UpdateEndedRemoteMediaStreams() {
4279 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4280 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4281 MediaStreamInterface* stream = remote_streams_->at(i);
4282 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4283 streams_to_remove.push_back(stream);
4284 }
4285 }
4286
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004287 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004288 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004289 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004290 }
4291}
4292
Steve Anton4171afb2017-11-20 10:20:22 -08004293void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004294 const std::vector<cricket::StreamParams>& streams,
4295 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004296 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004297
Seth Hampson845e8782018-03-02 11:34:10 -08004298 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004299 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004300 for (auto sender_it = current_senders->begin();
4301 sender_it != current_senders->end();
4302 /* incremented manually */) {
4303 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004304 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004305 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4306 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004307 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004308 OnLocalSenderRemoved(info, media_type);
4309 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004310 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004311 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004312 }
4313 }
4314
Steve Anton4171afb2017-11-20 10:20:22 -08004315 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004316 for (const cricket::StreamParams& params : streams) {
4317 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004318 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004319 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004320 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004321 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004322 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004323 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004324 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004325 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004326 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004327 }
4328 }
4329}
4330
Steve Anton4171afb2017-11-20 10:20:22 -08004331void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4332 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004333 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004334 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004335 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004336 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4337 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004338 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004339 return;
4340 }
4341
deadbeeffac06552015-11-25 11:26:01 -08004342 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004343 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004344 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004345 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004346 }
deadbeeffac06552015-11-25 11:26:01 -08004347
Seth Hampson5b4f0752018-04-02 16:31:36 -07004348 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004349 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004350}
4351
Steve Anton4171afb2017-11-20 10:20:22 -08004352void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4353 cricket::MediaType media_type) {
4354 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004355 if (!sender) {
4356 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004357 // SessionDescriptions has been renegotiated.
4358 return;
4359 }
deadbeeffac06552015-11-25 11:26:01 -08004360
4361 // A sender has been removed from the SessionDescription but it's still
4362 // associated with the PeerConnection. This only occurs if the SDP doesn't
4363 // match with the calls to CreateSender, AddStream and RemoveStream.
4364 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004365 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004366 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004367 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004368 }
deadbeeffac06552015-11-25 11:26:01 -08004369
Steve Anton4171afb2017-11-20 10:20:22 -08004370 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004371}
4372
4373void PeerConnection::UpdateLocalRtpDataChannels(
4374 const cricket::StreamParamsVec& streams) {
4375 std::vector<std::string> existing_channels;
4376
4377 // Find new and active data channels.
4378 for (const cricket::StreamParams& params : streams) {
4379 // |it->sync_label| is actually the data channel label. The reason is that
4380 // we use the same naming of data channels as we do for
4381 // MediaStreams and Tracks.
4382 // For MediaStreams, the sync_label is the MediaStream label and the
4383 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004384 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004385 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004386 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004387 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004388 continue;
4389 }
4390 // Set the SSRC the data channel should use for sending.
4391 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4392 existing_channels.push_back(data_channel_it->first);
4393 }
4394
4395 UpdateClosingRtpDataChannels(existing_channels, true);
4396}
4397
4398void PeerConnection::UpdateRemoteRtpDataChannels(
4399 const cricket::StreamParamsVec& streams) {
4400 std::vector<std::string> existing_channels;
4401
4402 // Find new and active data channels.
4403 for (const cricket::StreamParams& params : streams) {
4404 // The data channel label is either the mslabel or the SSRC if the mslabel
4405 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004406 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004407 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004408 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004409 auto data_channel_it = rtp_data_channels_.find(label);
4410 if (data_channel_it == rtp_data_channels_.end()) {
4411 // This is a new data channel.
4412 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4413 } else {
4414 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4415 }
4416 existing_channels.push_back(label);
4417 }
4418
4419 UpdateClosingRtpDataChannels(existing_channels, false);
4420}
4421
4422void PeerConnection::UpdateClosingRtpDataChannels(
4423 const std::vector<std::string>& active_channels,
4424 bool is_local_update) {
4425 auto it = rtp_data_channels_.begin();
4426 while (it != rtp_data_channels_.end()) {
4427 DataChannel* data_channel = it->second;
4428 if (std::find(active_channels.begin(), active_channels.end(),
4429 data_channel->label()) != active_channels.end()) {
4430 ++it;
4431 continue;
4432 }
4433
4434 if (is_local_update) {
4435 data_channel->SetSendSsrc(0);
4436 } else {
4437 data_channel->RemotePeerRequestClose();
4438 }
4439
4440 if (data_channel->state() == DataChannel::kClosed) {
4441 rtp_data_channels_.erase(it);
4442 it = rtp_data_channels_.begin();
4443 } else {
4444 ++it;
4445 }
4446 }
4447}
4448
4449void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4450 uint32_t remote_ssrc) {
4451 rtc::scoped_refptr<DataChannel> channel(
4452 InternalCreateDataChannel(label, nullptr));
4453 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004454 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004455 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004456 return;
4457 }
4458 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004459 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4460 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004461 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004462}
4463
4464rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4465 const std::string& label,
4466 const InternalDataChannelInit* config) {
4467 if (IsClosed()) {
4468 return nullptr;
4469 }
Steve Anton75737c02017-11-06 10:37:17 -08004470 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004471 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004472 << "InternalCreateDataChannel: Data is not supported in this call.";
4473 return nullptr;
4474 }
4475 InternalDataChannelInit new_config =
4476 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004477 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004478 if (new_config.id < 0) {
4479 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004480 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004481 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004482 RTC_LOG(LS_ERROR)
4483 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004484 return nullptr;
4485 }
4486 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004487 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004488 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004489 return nullptr;
4490 }
4491 }
4492
Steve Anton75737c02017-11-06 10:37:17 -08004493 rtc::scoped_refptr<DataChannel> channel(
4494 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004495 if (!channel) {
4496 sid_allocator_.ReleaseSid(new_config.id);
4497 return nullptr;
4498 }
4499
4500 if (channel->data_channel_type() == cricket::DCT_RTP) {
4501 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004502 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4503 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004504 return nullptr;
4505 }
4506 rtp_data_channels_[channel->label()] = channel;
4507 } else {
4508 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4509 sctp_data_channels_.push_back(channel);
4510 channel->SignalClosed.connect(this,
4511 &PeerConnection::OnSctpDataChannelClosed);
4512 }
4513
Steve Anton2d8609c2018-01-23 16:38:46 -08004514 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004515 return channel;
4516}
4517
4518bool PeerConnection::HasDataChannels() const {
4519 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4520}
4521
4522void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4523 for (const auto& channel : sctp_data_channels_) {
4524 if (channel->id() < 0) {
4525 int sid;
4526 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004527 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004528 continue;
4529 }
4530 channel->SetSctpSid(sid);
4531 }
4532 }
4533}
4534
4535void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004536 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004537 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4538 ++it) {
4539 if (it->get() == channel) {
4540 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004541 // After the closing procedure is done, it's safe to use this ID for
4542 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004543 sid_allocator_.ReleaseSid(channel->id());
4544 }
deadbeefbd292462015-12-14 18:15:29 -08004545 // Since this method is triggered by a signal from the DataChannel,
4546 // we can't free it directly here; we need to free it asynchronously.
4547 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004548 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004549 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4550 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004551 return;
4552 }
4553 }
4554}
4555
deadbeefab9b2d12015-10-14 11:33:11 -07004556void PeerConnection::OnDataChannelDestroyed() {
4557 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4558 // DataChannel may callback to us and try to modify the list.
4559 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4560 temp_rtp_dcs.swap(rtp_data_channels_);
4561 for (const auto& kv : temp_rtp_dcs) {
4562 kv.second->OnTransportChannelDestroyed();
4563 }
4564
4565 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4566 temp_sctp_dcs.swap(sctp_data_channels_);
4567 for (const auto& channel : temp_sctp_dcs) {
4568 channel->OnTransportChannelDestroyed();
4569 }
4570}
4571
4572void PeerConnection::OnDataChannelOpenMessage(
4573 const std::string& label,
4574 const InternalDataChannelInit& config) {
4575 rtc::scoped_refptr<DataChannel> channel(
4576 InternalCreateDataChannel(label, &config));
4577 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004578 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004579 return;
4580 }
4581
deadbeefa601f5c2016-06-06 14:27:39 -07004582 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4583 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004584 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004585 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004586}
4587
Steve Anton4171afb2017-11-20 10:20:22 -08004588rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4589PeerConnection::GetAudioTransceiver() const {
4590 // This method only works with Plan B SDP, where there is a single
4591 // audio/video transceiver.
4592 RTC_DCHECK(!IsUnifiedPlan());
4593 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004594 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004595 return transceiver;
4596 }
4597 }
4598 RTC_NOTREACHED();
4599 return nullptr;
4600}
4601
4602rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4603PeerConnection::GetVideoTransceiver() const {
4604 // This method only works with Plan B SDP, where there is a single
4605 // audio/video transceiver.
4606 RTC_DCHECK(!IsUnifiedPlan());
4607 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004608 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004609 return transceiver;
4610 }
4611 }
4612 RTC_NOTREACHED();
4613 return nullptr;
4614}
4615
4616// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4617// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004618bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004619 switch (type) {
4620 case cricket::MEDIA_TYPE_AUDIO:
4621 return !GetAudioTransceiver()->internal()->senders().empty();
4622 case cricket::MEDIA_TYPE_VIDEO:
4623 return !GetVideoTransceiver()->internal()->senders().empty();
4624 case cricket::MEDIA_TYPE_DATA:
4625 return false;
4626 }
4627 RTC_NOTREACHED();
4628 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004629}
4630
Steve Anton4171afb2017-11-20 10:20:22 -08004631rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4632PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4633 for (auto transceiver : transceivers_) {
4634 for (auto sender : transceiver->internal()->senders()) {
4635 if (sender->track() == track) {
4636 return sender;
4637 }
4638 }
4639 }
4640 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004641}
4642
Steve Anton4171afb2017-11-20 10:20:22 -08004643rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4644PeerConnection::FindSenderById(const std::string& sender_id) const {
4645 for (auto transceiver : transceivers_) {
4646 for (auto sender : transceiver->internal()->senders()) {
4647 if (sender->id() == sender_id) {
4648 return sender;
4649 }
4650 }
4651 }
4652 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004653}
4654
Steve Anton4171afb2017-11-20 10:20:22 -08004655rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4656PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4657 for (auto transceiver : transceivers_) {
4658 for (auto receiver : transceiver->internal()->receivers()) {
4659 if (receiver->id() == receiver_id) {
4660 return receiver;
4661 }
4662 }
4663 }
4664 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004665}
4666
Steve Anton4171afb2017-11-20 10:20:22 -08004667std::vector<PeerConnection::RtpSenderInfo>*
4668PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4669 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4670 media_type == cricket::MEDIA_TYPE_VIDEO);
4671 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4672 ? &remote_audio_sender_infos_
4673 : &remote_video_sender_infos_;
4674}
4675
4676std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004677 cricket::MediaType media_type) {
4678 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4679 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004680 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4681 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004682}
4683
Steve Anton4171afb2017-11-20 10:20:22 -08004684const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4685 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004686 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004687 const std::string sender_id) const {
4688 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004689 if (sender_info.stream_id == stream_id &&
4690 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004691 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004692 }
4693 }
4694 return nullptr;
4695}
4696
4697DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4698 for (const auto& channel : sctp_data_channels_) {
4699 if (channel->id() == sid) {
4700 return channel;
4701 }
4702 }
4703 return nullptr;
4704}
4705
deadbeef91dd5672016-05-18 16:55:30 -07004706bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004707 const cricket::ServerAddresses& stun_servers,
4708 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004709 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004710 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004711 // To handle both internal and externally created port allocator, we will
4712 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004713 port_allocator_flags_ = port_allocator_->flags();
4714 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4715 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4716 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004717 // If the disable-IPv6 flag was specified, we'll not override it
4718 // by experiment.
4719 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004720 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004721 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4722 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004723 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004724 }
4725
zhihuangb09b3f92017-03-07 14:40:51 -08004726 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004727 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004728 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004729 }
4730
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004731 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004732 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004733 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004734 }
4735
honghaiz60347052016-05-31 18:29:12 -07004736 if (configuration.candidate_network_policy ==
4737 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004738 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004739 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004740 }
4741
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004742 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004743 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004744 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4745 }
4746
Qingsi Wanga2d60672018-04-11 16:57:45 -07004747 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004748 // No step delay is used while allocating ports.
4749 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4750 port_allocator_->set_candidate_filter(
4751 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004752 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004753
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004754 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004755 for (auto& turn_server : turn_servers_copy) {
4756 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004757 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004758 // Call this last since it may create pooled allocator sessions using the
4759 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004760 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004761 stun_servers, std::move(turn_servers_copy),
4762 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4763 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004764 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004765 return true;
4766}
4767
deadbeef91dd5672016-05-18 16:55:30 -07004768bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004769 const cricket::ServerAddresses& stun_servers,
4770 const std::vector<cricket::RelayServerConfig>& turn_servers,
4771 IceTransportsType type,
4772 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004773 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004774 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004775 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004776 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004777 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004778 // According to JSEP, after setLocalDescription, changing the candidate pool
4779 // size is not allowed, and changing the set of ICE servers will not result
4780 // in new candidates being gathered.
4781 if (local_description()) {
4782 port_allocator_->FreezeCandidatePool();
4783 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004784 // Add the custom tls turn servers if they exist.
4785 auto turn_servers_copy = turn_servers;
4786 for (auto& turn_server : turn_servers_copy) {
4787 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4788 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004789 // Call this last since it may create pooled allocator sessions using the
4790 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004791 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004792 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4793 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004794}
4795
Steve Antonba818672017-11-06 10:21:57 -08004796cricket::ChannelManager* PeerConnection::channel_manager() const {
4797 return factory_->channel_manager();
4798}
4799
Elad Alon99c3fe52017-10-13 16:29:40 +02004800bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004801 std::unique_ptr<RtcEventLogOutput> output,
4802 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004803 if (!event_log_) {
4804 return false;
4805 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004806 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004807}
4808
4809void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004810 if (event_log_) {
4811 event_log_->StopLogging();
4812 }
ivoc14d5dbe2016-07-04 07:06:55 -07004813}
nisseeaabdf62017-05-05 02:23:02 -07004814
Steve Anton75737c02017-11-06 10:37:17 -08004815cricket::BaseChannel* PeerConnection::GetChannel(
4816 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004817 for (auto transceiver : transceivers_) {
4818 cricket::BaseChannel* channel = transceiver->internal()->channel();
4819 if (channel && channel->content_name() == content_name) {
4820 return channel;
4821 }
Steve Anton75737c02017-11-06 10:37:17 -08004822 }
4823 if (rtp_data_channel() &&
4824 rtp_data_channel()->content_name() == content_name) {
4825 return rtp_data_channel();
4826 }
4827 return nullptr;
4828}
4829
4830bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4831 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004832 RTC_LOG(LS_INFO)
4833 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004834 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004835 return false;
4836 }
4837 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004838 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004839 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004840 return false;
4841 }
4842
Zhi Huange830e682018-03-30 10:48:35 -07004843 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4844 if (dtls_role) {
4845 *role = *dtls_role;
4846 return true;
4847 }
4848 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004849}
4850
4851bool PeerConnection::GetSslRole(const std::string& content_name,
4852 rtc::SSLRole* role) {
4853 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004854 RTC_LOG(LS_INFO)
4855 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004856 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004857 return false;
4858 }
4859
Zhi Huange830e682018-03-30 10:48:35 -07004860 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4861 if (dtls_role) {
4862 *role = *dtls_role;
4863 return true;
4864 }
4865 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004866}
4867
Steve Antonf8470812017-12-04 10:46:21 -08004868void PeerConnection::SetSessionError(SessionError error,
4869 const std::string& error_desc) {
4870 RTC_DCHECK_RUN_ON(signaling_thread());
4871 if (error != session_error_) {
4872 session_error_ = error;
4873 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004874 }
4875}
4876
Zhi Huange830e682018-03-30 10:48:35 -07004877RTCError PeerConnection::UpdateSessionState(
4878 SdpType type,
4879 cricket::ContentSource source,
4880 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004881 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004882
4883 // If there's already a pending error then no state transition should happen.
4884 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004885 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004886
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004887 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004888 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004889 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004890 }
4891
4892 // Update the signaling state according to the specified state machine (see
4893 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004894 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004895 ChangeSignalingState(source == cricket::CS_LOCAL
4896 ? PeerConnectionInterface::kHaveLocalOffer
4897 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004898 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004899 ChangeSignalingState(source == cricket::CS_LOCAL
4900 ? PeerConnectionInterface::kHaveLocalPrAnswer
4901 : PeerConnectionInterface::kHaveRemotePrAnswer);
4902 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004903 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004904 ChangeSignalingState(PeerConnectionInterface::kStable);
4905 }
4906
4907 // Update internal objects according to the session description's media
4908 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004909 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004910 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004911 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004912 }
4913
Steve Anton8a006912017-12-04 15:25:56 -08004914 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004915}
4916
Steve Anton8a006912017-12-04 15:25:56 -08004917RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004918 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004919 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004920 const SessionDescriptionInterface* sdesc =
4921 (source == cricket::CS_LOCAL ? local_description()
4922 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004923 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004924
4925 // Push down the new SDP media section for each audio/video transceiver.
4926 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004927 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004928 FindMediaSectionForTransceiver(transceiver, sdesc);
4929 cricket::BaseChannel* channel = transceiver->internal()->channel();
4930 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004931 continue;
4932 }
4933 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004934 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004935 if (!content_desc) {
4936 continue;
4937 }
4938 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004939 bool success = (source == cricket::CS_LOCAL)
4940 ? channel->SetLocalContent(content_desc, type, &error)
4941 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004942 if (!success) {
4943 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4944 }
4945 }
4946
4947 // If using the RtpDataChannel, push down the new SDP section for it too.
4948 if (rtp_data_channel_) {
4949 const ContentInfo* data_content =
4950 cricket::GetFirstDataContent(sdesc->description());
4951 if (data_content && !data_content->rejected) {
4952 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004953 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004954 if (data_desc) {
4955 std::string error;
4956 bool success =
4957 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004958 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004959 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004960 if (!success) {
4961 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4962 std::move(error));
4963 }
Steve Anton75737c02017-11-06 10:37:17 -08004964 }
4965 }
4966 }
Steve Antoned10bd92017-12-05 10:52:59 -08004967
Steve Anton75737c02017-11-06 10:37:17 -08004968 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4969 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4970 if (sctp_transport_ && local_description() && remote_description() &&
4971 cricket::GetFirstDataContent(local_description()->description()) &&
4972 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004973 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004974 RTC_FROM_HERE,
4975 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004976 if (!success) {
4977 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4978 "Failed to push down SCTP parameters.");
4979 }
Steve Anton75737c02017-11-06 10:37:17 -08004980 }
Steve Antoned10bd92017-12-05 10:52:59 -08004981
Steve Anton8a006912017-12-04 15:25:56 -08004982 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004983}
4984
4985bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4986 RTC_DCHECK(network_thread()->IsCurrent());
4987 RTC_DCHECK(local_description());
4988 RTC_DCHECK(remote_description());
4989 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4990 // When we support "max-message-size", that would also be pushed down here.
4991 return sctp_transport_->Start(
4992 GetSctpPort(local_description()->description()),
4993 GetSctpPort(remote_description()->description()));
4994}
4995
Steve Anton8a006912017-12-04 15:25:56 -08004996RTCError PeerConnection::PushdownTransportDescription(
4997 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004998 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004999 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005000
Zhi Huange830e682018-03-30 10:48:35 -07005001 if (source == cricket::CS_LOCAL) {
5002 const SessionDescriptionInterface* sdesc = local_description();
5003 RTC_DCHECK(sdesc);
5004 return transport_controller_->SetLocalDescription(type,
5005 sdesc->description());
5006 } else {
5007 const SessionDescriptionInterface* sdesc = remote_description();
5008 RTC_DCHECK(sdesc);
5009 return transport_controller_->SetRemoteDescription(type,
5010 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005011 }
Steve Anton75737c02017-11-06 10:37:17 -08005012}
5013
5014bool PeerConnection::GetTransportDescription(
5015 const SessionDescription* description,
5016 const std::string& content_name,
5017 cricket::TransportDescription* tdesc) {
5018 if (!description || !tdesc) {
5019 return false;
5020 }
5021 const TransportInfo* transport_info =
5022 description->GetTransportInfoByName(content_name);
5023 if (!transport_info) {
5024 return false;
5025 }
5026 *tdesc = transport_info->description;
5027 return true;
5028}
5029
Steve Anton75737c02017-11-06 10:37:17 -08005030cricket::IceConfig PeerConnection::ParseIceConfig(
5031 const PeerConnectionInterface::RTCConfiguration& config) const {
5032 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005033 switch (config.continual_gathering_policy) {
5034 case PeerConnectionInterface::GATHER_ONCE:
5035 gathering_policy = cricket::GATHER_ONCE;
5036 break;
5037 case PeerConnectionInterface::GATHER_CONTINUALLY:
5038 gathering_policy = cricket::GATHER_CONTINUALLY;
5039 break;
5040 default:
5041 RTC_NOTREACHED();
5042 gathering_policy = cricket::GATHER_ONCE;
5043 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005044
Steve Anton75737c02017-11-06 10:37:17 -08005045 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005046 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5047 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005048 ice_config.prioritize_most_likely_candidate_pairs =
5049 config.prioritize_most_likely_ice_candidate_pairs;
5050 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005051 RTCConfigurationToIceConfigOptionalInt(
5052 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005053 ice_config.continual_gathering_policy = gathering_policy;
5054 ice_config.presume_writable_when_fully_relayed =
5055 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005056 ice_config.ice_check_interval_strong_connectivity =
5057 config.ice_check_interval_strong_connectivity;
5058 ice_config.ice_check_interval_weak_connectivity =
5059 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005060 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005061 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005062 ice_config.regather_all_networks_interval_range =
5063 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005064 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005065 return ice_config;
5066}
5067
Steve Anton75737c02017-11-06 10:37:17 -08005068bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5069 std::string* track_id) {
5070 if (!local_description()) {
5071 return false;
5072 }
5073 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5074 track_id);
5075}
5076
5077bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5078 std::string* track_id) {
5079 if (!remote_description()) {
5080 return false;
5081 }
5082 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5083 track_id);
5084}
5085
5086bool PeerConnection::SendData(const cricket::SendDataParams& params,
5087 const rtc::CopyOnWriteBuffer& payload,
5088 cricket::SendDataResult* result) {
5089 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005090 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005091 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005092 return false;
5093 }
5094 return rtp_data_channel_
5095 ? rtp_data_channel_->SendData(params, payload, result)
5096 : network_thread()->Invoke<bool>(
5097 RTC_FROM_HERE,
5098 Bind(&cricket::SctpTransportInternal::SendData,
5099 sctp_transport_.get(), params, payload, result));
5100}
5101
5102bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5103 if (!rtp_data_channel_ && !sctp_transport_) {
5104 // Don't log an error here, because DataChannels are expected to call
5105 // ConnectDataChannel in this state. It's the only way to initially tell
5106 // whether or not the underlying transport is ready.
5107 return false;
5108 }
5109 if (rtp_data_channel_) {
5110 rtp_data_channel_->SignalReadyToSendData.connect(
5111 webrtc_data_channel, &DataChannel::OnChannelReady);
5112 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5113 &DataChannel::OnDataReceived);
5114 } else {
5115 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5116 &DataChannel::OnChannelReady);
5117 SignalSctpDataReceived.connect(webrtc_data_channel,
5118 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005119 SignalSctpClosingProcedureStartedRemotely.connect(
5120 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5121 SignalSctpClosingProcedureComplete.connect(
5122 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005123 }
5124 return true;
5125}
5126
5127void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5128 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005129 RTC_LOG(LS_ERROR)
5130 << "DisconnectDataChannel called when rtp_data_channel_ and "
5131 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005132 return;
5133 }
5134 if (rtp_data_channel_) {
5135 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5136 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5137 } else {
5138 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5139 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005140 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5141 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005142 }
5143}
5144
5145void PeerConnection::AddSctpDataStream(int sid) {
5146 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005147 RTC_LOG(LS_ERROR)
5148 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005149 return;
5150 }
5151 network_thread()->Invoke<void>(
5152 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5153 sctp_transport_.get(), sid));
5154}
5155
5156void PeerConnection::RemoveSctpDataStream(int sid) {
5157 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005158 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005159 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005160 return;
5161 }
5162 network_thread()->Invoke<void>(
5163 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5164 sctp_transport_.get(), sid));
5165}
5166
5167bool PeerConnection::ReadyToSendData() const {
5168 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5169 sctp_ready_to_send_data_;
5170}
5171
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005172absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005173 if (sctp_mid_ && transport_controller_) {
5174 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5175 if (dtls_transport) {
5176 return dtls_transport->transport_name();
5177 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005178 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005179 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005180 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005181}
5182
Qingsi Wang72a43a12018-02-20 16:03:18 -08005183cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5184 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005185 network_thread()->Invoke<void>(
5186 RTC_FROM_HERE,
5187 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5188 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005189 return candidate_states_list;
5190}
5191
Steve Anton5dfde182018-02-06 10:34:40 -08005192std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5193 const {
5194 std::map<std::string, std::string> transport_names_by_mid;
5195 for (auto transceiver : transceivers_) {
5196 cricket::BaseChannel* channel = transceiver->internal()->channel();
5197 if (channel) {
5198 transport_names_by_mid[channel->content_name()] =
5199 channel->transport_name();
5200 }
Steve Anton75737c02017-11-06 10:37:17 -08005201 }
Steve Anton5dfde182018-02-06 10:34:40 -08005202 if (rtp_data_channel_) {
5203 transport_names_by_mid[rtp_data_channel_->content_name()] =
5204 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005205 }
5206 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005207 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005208 RTC_DCHECK(transport_name);
5209 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005210 }
Steve Anton5dfde182018-02-06 10:34:40 -08005211 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005212}
5213
Steve Anton5dfde182018-02-06 10:34:40 -08005214std::map<std::string, cricket::TransportStats>
5215PeerConnection::GetTransportStatsByNames(
5216 const std::set<std::string>& transport_names) {
5217 if (!network_thread()->IsCurrent()) {
5218 return network_thread()
5219 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5220 RTC_FROM_HERE,
5221 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005222 }
Steve Anton5dfde182018-02-06 10:34:40 -08005223 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5224 for (const std::string& transport_name : transport_names) {
5225 cricket::TransportStats transport_stats;
5226 bool success =
5227 transport_controller_->GetStats(transport_name, &transport_stats);
5228 if (success) {
5229 transport_stats_by_name[transport_name] = std::move(transport_stats);
5230 } else {
5231 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5232 << transport_name;
5233 }
5234 }
5235 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005236}
5237
5238bool PeerConnection::GetLocalCertificate(
5239 const std::string& transport_name,
5240 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005241 if (!certificate) {
5242 return false;
5243 }
5244 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5245 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005246}
5247
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005248std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005249 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005250 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005251}
5252
5253cricket::DataChannelType PeerConnection::data_channel_type() const {
5254 return data_channel_type_;
5255}
5256
5257bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5258 return pending_ice_restarts_.find(content_name) !=
5259 pending_ice_restarts_.end();
5260}
5261
Steve Anton75737c02017-11-06 10:37:17 -08005262bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5263 return transport_controller_->NeedsIceRestart(content_name);
5264}
5265
5266void PeerConnection::OnCertificateReady(
5267 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5268 transport_controller_->SetLocalCertificate(certificate);
5269}
5270
5271void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005272 SetSessionError(SessionError::kTransport,
5273 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005274}
5275
5276void PeerConnection::OnTransportControllerConnectionState(
5277 cricket::IceConnectionState state) {
5278 switch (state) {
5279 case cricket::kIceConnectionConnecting:
5280 // If the current state is Connected or Completed, then there were
5281 // writable channels but now there are not, so the next state must
5282 // be Disconnected.
5283 // kIceConnectionConnecting is currently used as the default,
5284 // un-connected state by the TransportController, so its only use is
5285 // detecting disconnections.
5286 if (ice_connection_state_ ==
5287 PeerConnectionInterface::kIceConnectionConnected ||
5288 ice_connection_state_ ==
5289 PeerConnectionInterface::kIceConnectionCompleted) {
5290 SetIceConnectionState(
5291 PeerConnectionInterface::kIceConnectionDisconnected);
5292 }
5293 break;
5294 case cricket::kIceConnectionFailed:
5295 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5296 break;
5297 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005298 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005299 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005300 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005301 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005302 break;
5303 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005304 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005305 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005306 if (ice_connection_state_ !=
5307 PeerConnectionInterface::kIceConnectionConnected) {
5308 // If jumping directly from "checking" to "connected",
5309 // signal "connected" first.
5310 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5311 }
5312 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005313 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005314 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005315 break;
5316 default:
5317 RTC_NOTREACHED();
5318 }
5319}
5320
5321void PeerConnection::OnTransportControllerCandidatesGathered(
5322 const std::string& transport_name,
5323 const cricket::Candidates& candidates) {
5324 RTC_DCHECK(signaling_thread()->IsCurrent());
5325 int sdp_mline_index;
5326 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005327 RTC_LOG(LS_ERROR)
5328 << "OnTransportControllerCandidatesGathered: content name "
5329 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005330 return;
5331 }
5332
5333 for (cricket::Candidates::const_iterator citer = candidates.begin();
5334 citer != candidates.end(); ++citer) {
5335 // Use transport_name as the candidate media id.
5336 std::unique_ptr<JsepIceCandidate> candidate(
5337 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5338 if (local_description()) {
5339 mutable_local_description()->AddCandidate(candidate.get());
5340 }
5341 OnIceCandidate(std::move(candidate));
5342 }
5343}
5344
5345void PeerConnection::OnTransportControllerCandidatesRemoved(
5346 const std::vector<cricket::Candidate>& candidates) {
5347 RTC_DCHECK(signaling_thread()->IsCurrent());
5348 // Sanity check.
5349 for (const cricket::Candidate& candidate : candidates) {
5350 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005351 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005352 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005353 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005354 return;
5355 }
5356 }
5357
5358 if (local_description()) {
5359 mutable_local_description()->RemoveCandidates(candidates);
5360 }
5361 OnIceCandidatesRemoved(candidates);
5362}
5363
5364void PeerConnection::OnTransportControllerDtlsHandshakeError(
5365 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005366 RTC_HISTOGRAM_ENUMERATION(
5367 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5368 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005369}
5370
Steve Antoned10bd92017-12-05 10:52:59 -08005371void PeerConnection::EnableSending() {
5372 for (auto transceiver : transceivers_) {
5373 cricket::BaseChannel* channel = transceiver->internal()->channel();
5374 if (channel && !channel->enabled()) {
5375 channel->Enable(true);
5376 }
Steve Anton75737c02017-11-06 10:37:17 -08005377 }
5378
Steve Anton4171afb2017-11-20 10:20:22 -08005379 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005380 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005381 }
Steve Anton75737c02017-11-06 10:37:17 -08005382}
5383
5384// Returns the media index for a local ice candidate given the content name.
5385bool PeerConnection::GetLocalCandidateMediaIndex(
5386 const std::string& content_name,
5387 int* sdp_mline_index) {
5388 if (!local_description() || !sdp_mline_index) {
5389 return false;
5390 }
5391
5392 bool content_found = false;
5393 const ContentInfos& contents = local_description()->description()->contents();
5394 for (size_t index = 0; index < contents.size(); ++index) {
5395 if (contents[index].name == content_name) {
5396 *sdp_mline_index = static_cast<int>(index);
5397 content_found = true;
5398 break;
5399 }
5400 }
5401 return content_found;
5402}
5403
5404bool PeerConnection::UseCandidatesInSessionDescription(
5405 const SessionDescriptionInterface* remote_desc) {
5406 if (!remote_desc) {
5407 return true;
5408 }
5409 bool ret = true;
5410
5411 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5412 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5413 for (size_t n = 0; n < candidates->count(); ++n) {
5414 const IceCandidateInterface* candidate = candidates->at(n);
5415 bool valid = false;
5416 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5417 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005418 RTC_LOG(LS_INFO)
5419 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005420 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005421 }
5422 continue;
5423 }
5424 ret = UseCandidate(candidate);
5425 if (!ret) {
5426 break;
5427 }
5428 }
5429 }
5430 return ret;
5431}
5432
5433bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5434 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5435 size_t remote_content_size =
5436 remote_description()->description()->contents().size();
5437 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005438 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005439 return false;
5440 }
5441
5442 cricket::ContentInfo content =
5443 remote_description()->description()->contents()[mediacontent_index];
5444 std::vector<cricket::Candidate> candidates;
5445 candidates.push_back(candidate->candidate());
5446 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005447 RTCError error =
5448 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005449 if (error.ok()) {
5450 // Candidates successfully submitted for checking.
5451 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5452 ice_connection_state_ ==
5453 PeerConnectionInterface::kIceConnectionDisconnected) {
5454 // If state is New, then the session has just gotten its first remote ICE
5455 // candidates, so go to Checking.
5456 // If state is Disconnected, the session is re-using old candidates or
5457 // receiving additional ones, so go to Checking.
5458 // If state is Connected, stay Connected.
5459 // TODO(bemasc): If state is Connected, and the new candidates are for a
5460 // newly added transport, then the state actually _should_ move to
5461 // checking. Add a way to distinguish that case.
5462 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5463 }
5464 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005465 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005466 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005467 }
5468 return true;
5469}
5470
5471void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005472 // Destroy video channel first since it may have a pointer to the
5473 // voice channel.
5474 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005475 if (!video_info || video_info->rejected) {
5476 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005477 }
5478
Steve Anton6fec8802017-12-04 10:37:29 -08005479 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5480 if (!audio_info || audio_info->rejected) {
5481 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005482 }
5483
5484 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5485 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005486 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005487 }
5488}
5489
Steve Antondcc3c022017-12-22 16:02:54 -08005490RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5491 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005492 const cricket::ContentGroup* bundle_group = nullptr;
5493 if (configuration_.bundle_policy ==
5494 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005495 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005496 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005497 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5498 "max-bundle configured but session description "
5499 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005500 }
5501 }
Steve Antondcc3c022017-12-22 16:02:54 -08005502 return std::move(bundle_group);
5503}
5504
5505RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005506 // Creating the media channels. Transports should already have been created
5507 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005508 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005509 if (voice && !voice->rejected &&
5510 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005511 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005512 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005513 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5514 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005515 }
5516 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5517 }
5518
Steve Antondcc3c022017-12-22 16:02:54 -08005519 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005520 if (video && !video->rejected &&
5521 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005522 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005523 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005524 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5525 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005526 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005527 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005528 }
5529
Steve Antondcc3c022017-12-22 16:02:54 -08005530 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005531 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5532 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005533 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005534 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5535 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005536 }
5537 }
5538
Steve Anton8a006912017-12-04 15:25:56 -08005539 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005540}
5541
Steve Anton4171afb2017-11-20 10:20:22 -08005542// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005543cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005544 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005545 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5546 MediaTransportInterface* media_transport = GetMediaTransport(mid);
5547
Steve Anton75737c02017-11-06 10:37:17 -08005548 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005549 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Zhi Huange830e682018-03-30 10:48:35 -07005550 signaling_thread(), mid, SrtpRequired(),
5551 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005552 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005553 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005554 }
Steve Anton75737c02017-11-06 10:37:17 -08005555 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5556 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005557 voice_channel->SignalSentPacket.connect(this,
5558 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005559 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005560
Steve Antoneda6ccd2017-12-04 10:21:55 -08005561 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005562}
5563
Steve Anton4171afb2017-11-20 10:20:22 -08005564// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005565cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005566 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005567 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5568
5569 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005570 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005571 call_.get(), configuration_.media_config, rtp_transport,
5572 signaling_thread(), mid, SrtpRequired(),
5573 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005574 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005575 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005576 }
Steve Anton75737c02017-11-06 10:37:17 -08005577 video_channel->SignalDtlsSrtpSetupFailure.connect(
5578 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005579 video_channel->SignalSentPacket.connect(this,
5580 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005581 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005582
Steve Antoneda6ccd2017-12-04 10:21:55 -08005583 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005584}
5585
Zhi Huange830e682018-03-30 10:48:35 -07005586bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005587 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5588 if (sctp) {
5589 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005590 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005591 << "Trying to create SCTP transport, but didn't compile with "
5592 "SCTP support (HAVE_SCTP)";
5593 return false;
5594 }
5595 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005596 RTC_FROM_HERE,
5597 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005598 return false;
5599 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005600 for (const auto& channel : sctp_data_channels_) {
5601 channel->OnTransportChannelCreated();
5602 }
Steve Anton75737c02017-11-06 10:37:17 -08005603 } else {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005604 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Steve Anton75737c02017-11-06 10:37:17 -08005605 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005606 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5607 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005608 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005609 return false;
5610 }
Steve Anton75737c02017-11-06 10:37:17 -08005611 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5612 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5613 rtp_data_channel_->SignalSentPacket.connect(
5614 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005615 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005616 }
5617
Steve Anton75737c02017-11-06 10:37:17 -08005618 return true;
5619}
5620
5621Call::Stats PeerConnection::GetCallStats() {
5622 if (!worker_thread()->IsCurrent()) {
5623 return worker_thread()->Invoke<Call::Stats>(
5624 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5625 }
5626 if (call_) {
5627 return call_->GetStats();
5628 } else {
5629 return Call::Stats();
5630 }
5631}
5632
Zhi Huange830e682018-03-30 10:48:35 -07005633bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005634 RTC_DCHECK(network_thread()->IsCurrent());
5635 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005636 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005637 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005638 RTC_DCHECK(dtls_transport);
5639 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005640 RTC_DCHECK(sctp_transport_);
5641 sctp_invoker_.reset(new rtc::AsyncInvoker());
5642 sctp_transport_->SignalReadyToSendData.connect(
5643 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5644 sctp_transport_->SignalDataReceived.connect(
5645 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005646 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5647 // another thread. Would be nice if there was a helper class similar to
5648 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5649 // code.
5650 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5651 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5652 sctp_transport_->SignalClosingProcedureComplete.connect(
5653 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005654 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005655 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005656 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005657}
5658
5659void PeerConnection::DestroySctpTransport_n() {
5660 RTC_DCHECK(network_thread()->IsCurrent());
5661 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005662 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005663 sctp_invoker_.reset(nullptr);
5664 sctp_ready_to_send_data_ = false;
5665}
5666
5667void PeerConnection::OnSctpTransportReadyToSendData_n() {
5668 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5669 RTC_DCHECK(network_thread()->IsCurrent());
5670 // Note: Cannot use rtc::Bind here because it will grab a reference to
5671 // PeerConnection and potentially cause PeerConnection to live longer than
5672 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5673 // be destroyed before PeerConnection is destroyed, and at that point all
5674 // pending tasks will be cleared.
5675 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5676 OnSctpTransportReadyToSendData_s(true);
5677 });
5678}
5679
5680void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5681 RTC_DCHECK(signaling_thread()->IsCurrent());
5682 sctp_ready_to_send_data_ = ready;
5683 SignalSctpReadyToSendData(ready);
5684}
5685
5686void PeerConnection::OnSctpTransportDataReceived_n(
5687 const cricket::ReceiveDataParams& params,
5688 const rtc::CopyOnWriteBuffer& payload) {
5689 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5690 RTC_DCHECK(network_thread()->IsCurrent());
5691 // Note: Cannot use rtc::Bind here because it will grab a reference to
5692 // PeerConnection and potentially cause PeerConnection to live longer than
5693 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5694 // be destroyed before PeerConnection is destroyed, and at that point all
5695 // pending tasks will be cleared.
5696 sctp_invoker_->AsyncInvoke<void>(
5697 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5698 OnSctpTransportDataReceived_s(params, payload);
5699 });
5700}
5701
5702void PeerConnection::OnSctpTransportDataReceived_s(
5703 const cricket::ReceiveDataParams& params,
5704 const rtc::CopyOnWriteBuffer& payload) {
5705 RTC_DCHECK(signaling_thread()->IsCurrent());
5706 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5707 // Received OPEN message; parse and signal that a new data channel should
5708 // be created.
5709 std::string label;
5710 InternalDataChannelInit config;
5711 config.id = params.ssrc;
5712 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005713 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5714 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005715 return;
5716 }
5717 config.open_handshake_role = InternalDataChannelInit::kAcker;
5718 OnDataChannelOpenMessage(label, config);
5719 } else {
5720 // Otherwise just forward the signal.
5721 SignalSctpDataReceived(params, payload);
5722 }
5723}
5724
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005725void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005726 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5727 RTC_DCHECK(network_thread()->IsCurrent());
5728 sctp_invoker_->AsyncInvoke<void>(
5729 RTC_FROM_HERE, signaling_thread(),
5730 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005731 &SignalSctpClosingProcedureStartedRemotely, sid));
5732}
5733
5734void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5735 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5736 RTC_DCHECK(network_thread()->IsCurrent());
5737 sctp_invoker_->AsyncInvoke<void>(
5738 RTC_FROM_HERE, signaling_thread(),
5739 rtc::Bind(&sigslot::signal1<int>::operator(),
5740 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005741}
5742
5743// Returns false if bundle is enabled and rtcp_mux is disabled.
5744bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5745 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5746 if (!bundle_enabled)
5747 return true;
5748
5749 const cricket::ContentGroup* bundle_group =
5750 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5751 RTC_DCHECK(bundle_group != NULL);
5752
5753 const cricket::ContentInfos& contents = desc->contents();
5754 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5755 citer != contents.end(); ++citer) {
5756 const cricket::ContentInfo* content = (&*citer);
5757 RTC_DCHECK(content != NULL);
5758 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005759 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005760 if (!HasRtcpMuxEnabled(content))
5761 return false;
5762 }
5763 }
5764 // RTCP-MUX is enabled in all the contents.
5765 return true;
5766}
5767
5768bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005769 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005770}
5771
Steve Anton8a006912017-12-04 15:25:56 -08005772RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005773 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005774 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005775 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005776 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005777 }
5778
5779 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005780 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005781 }
5782
Steve Anton3828c062017-12-06 10:34:51 -08005783 SdpType type = sdesc->GetType();
5784 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5785 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005786 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005787 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005788 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005789 }
5790
5791 // Verify crypto settings.
5792 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005793 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5794 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005795 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005796 if (!crypto_error.ok()) {
5797 return crypto_error;
5798 }
Steve Anton75737c02017-11-06 10:37:17 -08005799 }
5800
5801 // Verify ice-ufrag and ice-pwd.
5802 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005803 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5804 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005805 }
5806
5807 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005808 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5809 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005810 }
5811
5812 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5813 // m-lines that do not rtcp-mux enabled.
5814
5815 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005816 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005817 // With an answer we want to compare the new answer session description with
5818 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005819 const cricket::SessionDescription* offer_desc =
5820 (source == cricket::CS_LOCAL) ? remote_description()->description()
5821 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005822 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5823 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5824 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005825 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5826 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005827 }
5828 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005829 // The re-offers should respect the order of m= sections in current
5830 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005831 // With a re-offer, either the current local or current remote descriptions
5832 // could be the most up to date, so we would like to check against both of
5833 // them if they exist. It could be the case that one of them has a 0 port
5834 // for a media section, but the other does not. This is important to check
5835 // against in the case that we are recycling an m= section.
5836 const cricket::SessionDescription* current_desc = nullptr;
5837 const cricket::SessionDescription* secondary_current_desc = nullptr;
5838 if (local_description()) {
5839 current_desc = local_description()->description();
5840 if (remote_description()) {
5841 secondary_current_desc = remote_description()->description();
5842 }
5843 } else if (remote_description()) {
5844 current_desc = remote_description()->description();
5845 }
Steve Anton75737c02017-11-06 10:37:17 -08005846 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005847 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5848 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5850 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005851 }
5852 }
5853
Steve Antonba42e992018-04-09 14:10:01 -07005854 if (IsUnifiedPlan()) {
5855 // Ensure that each audio and video media section has at most one
5856 // "StreamParams". This will return an error if receiving a session
5857 // description from a "Plan B" endpoint which adds multiple tracks of the
5858 // same type. With Unified Plan, there can only be at most one track per
5859 // media section.
5860 for (const ContentInfo& content : sdesc->description()->contents()) {
5861 const MediaContentDescription& desc = *content.description;
5862 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5863 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5864 desc.streams().size() > 1u) {
5865 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5866 "Media section has more than one track specified "
5867 "with a=ssrc lines which is not supported with "
5868 "Unified Plan.");
5869 }
5870 }
5871 }
5872
Steve Anton8a006912017-12-04 15:25:56 -08005873 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005874}
5875
Steve Anton3828c062017-12-06 10:34:51 -08005876bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005877 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005878 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005879 return (state == PeerConnectionInterface::kStable) ||
5880 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005881 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005882 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005883 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5884 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5885 }
5886}
5887
Steve Anton3828c062017-12-06 10:34:51 -08005888bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005889 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005890 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005891 return (state == PeerConnectionInterface::kStable) ||
5892 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005893 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005894 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005895 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5896 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5897 }
5898}
5899
Steve Antonf8470812017-12-04 10:46:21 -08005900const char* PeerConnection::SessionErrorToString(SessionError error) const {
5901 switch (error) {
5902 case SessionError::kNone:
5903 return "ERROR_NONE";
5904 case SessionError::kContent:
5905 return "ERROR_CONTENT";
5906 case SessionError::kTransport:
5907 return "ERROR_TRANSPORT";
5908 }
5909 RTC_NOTREACHED();
5910 return "";
5911}
5912
Steve Anton75737c02017-11-06 10:37:17 -08005913std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02005914 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08005915 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5916 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02005917 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08005918}
5919
Steve Anton8e20f172018-03-06 10:55:04 -08005920void PeerConnection::ReportSdpFormatReceived(
5921 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005922 int num_audio_mlines = 0;
5923 int num_video_mlines = 0;
5924 int num_audio_tracks = 0;
5925 int num_video_tracks = 0;
5926 for (const ContentInfo& content : remote_offer.description()->contents()) {
5927 cricket::MediaType media_type = content.media_description()->type();
5928 int num_tracks = std::max(
5929 1, static_cast<int>(content.media_description()->streams().size()));
5930 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5931 num_audio_mlines += 1;
5932 num_audio_tracks += num_tracks;
5933 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5934 num_video_mlines += 1;
5935 num_video_tracks += num_tracks;
5936 }
5937 }
5938 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5939 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5940 format = kSdpFormatReceivedComplexUnifiedPlan;
5941 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5942 format = kSdpFormatReceivedComplexPlanB;
5943 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5944 format = kSdpFormatReceivedSimple;
5945 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005946 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5947 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005948}
5949
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005950void PeerConnection::NoteUsageEvent(UsageEvent event) {
5951 RTC_DCHECK_RUN_ON(signaling_thread());
5952 usage_event_accumulator_ |= static_cast<int>(event);
5953}
5954
5955void PeerConnection::ReportUsagePattern() const {
5956 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005957 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5958 usage_event_accumulator_,
5959 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005960 const int bad_bits =
5961 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5962 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5963 const int good_bits =
5964 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5965 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5966 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5967 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5968 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005969 // If called after close(), we can't report, because observer may have
5970 // been deallocated, and therefore pointer is null. Write to log instead.
5971 if (observer_) {
5972 Observer()->OnInterestingUsage(usage_event_accumulator_);
5973 } else {
5974 RTC_LOG(LS_INFO) << "Interesting usage signature "
5975 << usage_event_accumulator_
5976 << " observed after observer shutdown";
5977 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005978 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005979}
5980
Steve Anton0ffaaa22018-02-23 10:31:30 -08005981void PeerConnection::ReportNegotiatedSdpSemantics(
5982 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005983 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005984 switch (answer.description()->msid_signaling()) {
5985 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005986 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005987 break;
5988 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005989 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005990 break;
5991 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005992 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005993 break;
5994 case cricket::kMsidSignalingMediaSection |
5995 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005996 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005997 break;
5998 default:
5999 RTC_NOTREACHED();
6000 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006001 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6002 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006003}
6004
Steve Anton75737c02017-11-06 10:37:17 -08006005// We need to check the local/remote description for the Transport instead of
6006// the session, because a new Transport added during renegotiation may have
6007// them unset while the session has them set from the previous negotiation.
6008// Not doing so may trigger the auto generation of transport description and
6009// mess up DTLS identity information, ICE credential, etc.
6010bool PeerConnection::ReadyToUseRemoteCandidate(
6011 const IceCandidateInterface* candidate,
6012 const SessionDescriptionInterface* remote_desc,
6013 bool* valid) {
6014 *valid = true;
6015
6016 const SessionDescriptionInterface* current_remote_desc =
6017 remote_desc ? remote_desc : remote_description();
6018
6019 if (!current_remote_desc) {
6020 return false;
6021 }
6022
6023 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6024 size_t remote_content_size =
6025 current_remote_desc->description()->contents().size();
6026 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006027 RTC_LOG(LS_ERROR)
6028 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6029 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006030
6031 *valid = false;
6032 return false;
6033 }
6034
6035 cricket::ContentInfo content =
6036 current_remote_desc->description()->contents()[mediacontent_index];
6037
6038 const std::string transport_name = GetTransportName(content.name);
6039 if (transport_name.empty()) {
6040 return false;
6041 }
Zhi Huange830e682018-03-30 10:48:35 -07006042 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006043}
6044
6045bool PeerConnection::SrtpRequired() const {
6046 return dtls_enabled_ ||
6047 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6048}
6049
6050void PeerConnection::OnTransportControllerGatheringState(
6051 cricket::IceGatheringState state) {
6052 RTC_DCHECK(signaling_thread()->IsCurrent());
6053 if (state == cricket::kIceGatheringGathering) {
6054 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6055 } else if (state == cricket::kIceGatheringComplete) {
6056 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6057 }
6058}
6059
6060void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006061 std::map<std::string, std::set<cricket::MediaType>>
6062 media_types_by_transport_name;
6063 for (auto transceiver : transceivers_) {
6064 if (transceiver->internal()->channel()) {
6065 const std::string& transport_name =
6066 transceiver->internal()->channel()->transport_name();
6067 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006068 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006069 }
Steve Anton75737c02017-11-06 10:37:17 -08006070 }
6071 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006072 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6073 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006074 }
Zhi Huange830e682018-03-30 10:48:35 -07006075
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006076 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006077 if (transport_name) {
6078 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006079 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006080 }
Zhi Huange830e682018-03-30 10:48:35 -07006081
Steve Antonc7b964c2018-02-01 14:39:45 -08006082 for (const auto& entry : media_types_by_transport_name) {
6083 const std::string& transport_name = entry.first;
6084 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006085 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006086 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006087 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006088 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006089 }
6090 }
6091}
6092// Walk through the ConnectionInfos to gather best connection usage
6093// for IPv4 and IPv6.
6094void PeerConnection::ReportBestConnectionState(
6095 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006096 for (const cricket::TransportChannelStats& channel_stats :
6097 stats.channel_stats) {
6098 for (const cricket::ConnectionInfo& connection_info :
6099 channel_stats.connection_infos) {
6100 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006101 continue;
6102 }
6103
Steve Antonc7b964c2018-02-01 14:39:45 -08006104 const cricket::Candidate& local = connection_info.local_candidate;
6105 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006106
6107 // Increment the counter for IceCandidatePairType.
6108 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6109 (local.type() == RELAY_PORT_TYPE &&
6110 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006111 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6112 GetIceCandidatePairCounter(local, remote),
6113 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006114 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006115 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6116 GetIceCandidatePairCounter(local, remote),
6117 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006118 } else {
6119 RTC_CHECK(0);
6120 }
Steve Anton75737c02017-11-06 10:37:17 -08006121
6122 // Increment the counter for IP type.
6123 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006124 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6125 kBestConnections_IPv4,
6126 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006127 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006128 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6129 kBestConnections_IPv6,
6130 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006131 } else {
6132 RTC_CHECK(0);
6133 }
6134
6135 return;
6136 }
6137 }
6138}
6139
6140void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006141 const cricket::TransportStats& stats,
6142 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006143 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6144 return;
6145 }
6146
6147 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6148 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6149 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6150 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6151 return;
6152 }
6153
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006154 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6155 for (cricket::MediaType media_type : media_types) {
6156 switch (media_type) {
6157 case cricket::MEDIA_TYPE_AUDIO:
6158 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6159 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6160 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6161 break;
6162 case cricket::MEDIA_TYPE_VIDEO:
6163 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6164 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6165 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6166 break;
6167 case cricket::MEDIA_TYPE_DATA:
6168 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6169 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6170 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6171 break;
6172 default:
6173 RTC_NOTREACHED();
6174 continue;
6175 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006176 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006177 }
6178
6179 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6180 for (cricket::MediaType media_type : media_types) {
6181 switch (media_type) {
6182 case cricket::MEDIA_TYPE_AUDIO:
6183 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6184 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6185 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6186 break;
6187 case cricket::MEDIA_TYPE_VIDEO:
6188 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6189 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6190 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6191 break;
6192 case cricket::MEDIA_TYPE_DATA:
6193 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6194 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6195 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6196 break;
6197 default:
6198 RTC_NOTREACHED();
6199 continue;
6200 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006201 }
Steve Anton75737c02017-11-06 10:37:17 -08006202 }
6203}
6204
6205void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6206 RTC_DCHECK(worker_thread()->IsCurrent());
6207 RTC_DCHECK(call_);
6208 call_->OnSentPacket(sent_packet);
6209}
6210
6211const std::string PeerConnection::GetTransportName(
6212 const std::string& content_name) {
6213 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006214 if (channel) {
6215 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006216 }
Steve Anton6fec8802017-12-04 10:37:29 -08006217 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006218 RTC_DCHECK(sctp_mid_);
6219 if (content_name == *sctp_mid_) {
6220 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006221 }
6222 }
6223 // Return an empty string if failed to retrieve the transport name.
6224 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006225}
6226
Steve Anton6fec8802017-12-04 10:37:29 -08006227void PeerConnection::DestroyTransceiverChannel(
6228 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6229 transceiver) {
6230 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006231
Steve Anton6fec8802017-12-04 10:37:29 -08006232 cricket::BaseChannel* channel = transceiver->internal()->channel();
6233 if (channel) {
6234 transceiver->internal()->SetChannel(nullptr);
6235 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006236 }
6237}
6238
6239void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006240 if (rtp_data_channel_) {
6241 OnDataChannelDestroyed();
6242 DestroyBaseChannel(rtp_data_channel_);
6243 rtp_data_channel_ = nullptr;
6244 }
6245
6246 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6247 // grab a reference to this PeerConnection. If this is called from the
6248 // PeerConnection destructor, the RefCountedObject vtable will have already
6249 // been destroyed (since it is a subclass of PeerConnection) and using
6250 // rtc::Bind will cause "Pure virtual function called" error to appear.
6251
6252 if (sctp_transport_) {
6253 OnDataChannelDestroyed();
6254 network_thread()->Invoke<void>(RTC_FROM_HERE,
6255 [this] { DestroySctpTransport_n(); });
6256 }
6257}
6258
6259void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6260 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006261 switch (channel->media_type()) {
6262 case cricket::MEDIA_TYPE_AUDIO:
6263 channel_manager()->DestroyVoiceChannel(
6264 static_cast<cricket::VoiceChannel*>(channel));
6265 break;
6266 case cricket::MEDIA_TYPE_VIDEO:
6267 channel_manager()->DestroyVideoChannel(
6268 static_cast<cricket::VideoChannel*>(channel));
6269 break;
6270 case cricket::MEDIA_TYPE_DATA:
6271 channel_manager()->DestroyRtpDataChannel(
6272 static_cast<cricket::RtpDataChannel*>(channel));
6273 break;
6274 default:
6275 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6276 break;
6277 }
Zhi Huange830e682018-03-30 10:48:35 -07006278}
Steve Anton6fec8802017-12-04 10:37:29 -08006279
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006280bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006281 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006282 RtpTransportInternal* rtp_transport,
6283 cricket::DtlsTransportInternal* dtls_transport) {
6284 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006285 auto base_channel = GetChannel(mid);
6286 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006287 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006288 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006289 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006290 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006291 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006292 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006293}
6294
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006295PeerConnectionObserver* PeerConnection::Observer() const {
6296 // In earlier production code, the pointer was not cleared on close,
6297 // which might have led to undefined behavior if the observer was not
6298 // deallocated, or strange crashes if it was.
6299 // We use CHECK in order to catch such behavior if it exists.
6300 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6301 RTC_CHECK(observer_);
6302 return observer_;
6303}
6304
Harald Alvestrand89061872018-01-02 14:08:34 +01006305void PeerConnection::ClearStatsCache() {
6306 if (stats_collector_) {
6307 stats_collector_->ClearCachedStatsReport();
6308 }
6309}
6310
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006311void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006312 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6313 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006314}
6315
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006316} // namespace webrtc