blob: 4bdaead3171eb2872f8c22c77406a8f8f7b12fdc [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
Steve Anton75737c02017-11-06 10:37:17 -0800521// Get the SCTP port out of a SessionDescription.
522// Return -1 if not found.
523int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800524 const cricket::DataContentDescription* data_desc =
525 GetFirstDataContentDescription(session_description);
526 RTC_DCHECK(data_desc);
527 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800528 return -1;
529 }
Steve Anton75737c02017-11-06 10:37:17 -0800530 std::string value;
531 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
532 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800533 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800534 if (!codec.Matches(match_pattern)) {
535 continue;
536 }
537 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
538 return rtc::FromString<int>(value);
539 }
540 }
541 return -1;
542}
543
Steve Anton75737c02017-11-06 10:37:17 -0800544// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
545bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
546 const SessionDescriptionInterface* new_desc,
547 const std::string& content_name) {
548 if (!old_desc) {
549 return false;
550 }
551 const SessionDescription* new_sd = new_desc->description();
552 const SessionDescription* old_sd = old_desc->description();
553 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
554 if (!cinfo || cinfo->rejected) {
555 return false;
556 }
557 // If the content isn't rejected, check if ufrag and password has changed.
558 const cricket::TransportDescription* new_transport_desc =
559 new_sd->GetTransportDescriptionByName(content_name);
560 const cricket::TransportDescription* old_transport_desc =
561 old_sd->GetTransportDescriptionByName(content_name);
562 if (!new_transport_desc || !old_transport_desc) {
563 // No transport description exists. This is not an ICE restart.
564 return false;
565 }
566 if (cricket::IceCredentialsChanged(
567 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
568 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100569 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
570 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800571 return true;
572 }
573 return false;
574}
575
Steve Anton80dd7b52018-02-16 17:08:42 -0800576// Generates a string error message for SetLocalDescription/SetRemoteDescription
577// from an RTCError.
578std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
579 SdpType type,
580 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200581 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800582 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
583 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200584 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800585}
586
Seth Hampson5b4f0752018-04-02 16:31:36 -0700587std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
588 std::string output = "streams=[";
589 const char* separator = "";
590 for (const auto& stream_id : stream_ids) {
591 output.append(separator).append(stream_id);
592 separator = ", ";
593 }
594 output.append("]");
595 return output;
596}
597
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200598absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700599 int rtc_configuration_parameter) {
600 if (rtc_configuration_parameter ==
601 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200602 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700603 }
604 return rtc_configuration_parameter;
605}
606
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800607cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
608 switch (type) {
609 case DataMessageType::kText:
610 return cricket::DMT_TEXT;
611 case DataMessageType::kBinary:
612 return cricket::DMT_BINARY;
613 case DataMessageType::kControl:
614 return cricket::DMT_CONTROL;
615 default:
616 return cricket::DMT_NONE;
617 }
618 return cricket::DMT_NONE;
619}
620
621DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
622 switch (type) {
623 case cricket::DMT_TEXT:
624 return DataMessageType::kText;
625 case cricket::DMT_BINARY:
626 return DataMessageType::kBinary;
627 case cricket::DMT_CONTROL:
628 return DataMessageType::kControl;
629 case cricket::DMT_NONE:
630 default:
631 RTC_NOTREACHED();
632 }
633 return DataMessageType::kControl;
634}
635
Steve Anton75737c02017-11-06 10:37:17 -0800636} // namespace
637
Henrik Boström31638672017-11-23 17:48:32 +0100638// Upon completion, posts a task to execute the callback of the
639// SetSessionDescriptionObserver asynchronously on the same thread. At this
640// point, the state of the peer connection might no longer reflect the effects
641// of the SetRemoteDescription operation, as the peer connection could have been
642// modified during the post.
643// TODO(hbos): Remove this class once we remove the version of
644// PeerConnectionInterface::SetRemoteDescription() that takes a
645// SetSessionDescriptionObserver as an argument.
646class PeerConnection::SetRemoteDescriptionObserverAdapter
647 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
648 public:
649 SetRemoteDescriptionObserverAdapter(
650 rtc::scoped_refptr<PeerConnection> pc,
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
652 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
653
654 // SetRemoteDescriptionObserverInterface implementation.
655 void OnSetRemoteDescriptionComplete(RTCError error) override {
656 if (error.ok())
657 pc_->PostSetSessionDescriptionSuccess(wrapper_);
658 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100659 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100660 }
661
662 private:
663 rtc::scoped_refptr<PeerConnection> pc_;
664 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
665};
666
deadbeef293e9262017-01-11 12:28:30 -0800667bool PeerConnectionInterface::RTCConfiguration::operator==(
668 const PeerConnectionInterface::RTCConfiguration& o) const {
669 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700670 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800671 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000672 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700673 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800674 BundlePolicy bundle_policy;
675 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700676 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
677 int ice_candidate_pool_size;
678 bool disable_ipv6;
679 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700680 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100681 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700682 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200683 absl::optional<int> screencast_min_bitrate;
684 absl::optional<bool> combined_audio_video_bwe;
685 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800686 TcpCandidatePolicy tcp_candidate_policy;
687 CandidateNetworkPolicy candidate_network_policy;
688 int audio_jitter_buffer_max_packets;
689 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100690 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800691 int ice_connection_receiving_timeout;
692 int ice_backup_candidate_pair_ping_interval;
693 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800694 bool prioritize_most_likely_ice_candidate_pairs;
695 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800696 bool prune_turn_ports;
697 bool presume_writable_when_fully_relayed;
698 bool enable_ice_renomination;
699 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200700 absl::optional<int> ice_check_interval_strong_connectivity;
701 absl::optional<int> ice_check_interval_weak_connectivity;
702 absl::optional<int> ice_check_min_interval;
703 absl::optional<int> ice_unwritable_timeout;
704 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800705 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200706 absl::optional<int> stun_candidate_keepalive_interval;
707 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200708 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800709 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200710 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700711 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700712 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700713 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700714 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100715 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800716 };
717 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
718 "Did you add something to RTCConfiguration and forget to "
719 "update operator==?");
720 return type == o.type && servers == o.servers &&
721 bundle_policy == o.bundle_policy &&
722 rtcp_mux_policy == o.rtcp_mux_policy &&
723 tcp_candidate_policy == o.tcp_candidate_policy &&
724 candidate_network_policy == o.candidate_network_policy &&
725 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
726 audio_jitter_buffer_fast_accelerate ==
727 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100728 audio_jitter_buffer_min_delay_ms ==
729 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800730 ice_connection_receiving_timeout ==
731 o.ice_connection_receiving_timeout &&
732 ice_backup_candidate_pair_ping_interval ==
733 o.ice_backup_candidate_pair_ping_interval &&
734 continual_gathering_policy == o.continual_gathering_policy &&
735 certificates == o.certificates &&
736 prioritize_most_likely_ice_candidate_pairs ==
737 o.prioritize_most_likely_ice_candidate_pairs &&
738 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800739 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700740 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100741 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800742 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800743 screencast_min_bitrate == o.screencast_min_bitrate &&
744 combined_audio_video_bwe == o.combined_audio_video_bwe &&
745 enable_dtls_srtp == o.enable_dtls_srtp &&
746 ice_candidate_pool_size == o.ice_candidate_pool_size &&
747 prune_turn_ports == o.prune_turn_ports &&
748 presume_writable_when_fully_relayed ==
749 o.presume_writable_when_fully_relayed &&
750 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800751 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800752 ice_check_interval_strong_connectivity ==
753 o.ice_check_interval_strong_connectivity &&
754 ice_check_interval_weak_connectivity ==
755 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700756 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700757 ice_unwritable_timeout == o.ice_unwritable_timeout &&
758 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800759 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800760 stun_candidate_keepalive_interval ==
761 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200762 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800763 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800764 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700765 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700766 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700767 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700768 use_media_transport_for_data_channels ==
769 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100770 crypto_options == o.crypto_options &&
771 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800772}
773
774bool PeerConnectionInterface::RTCConfiguration::operator!=(
775 const PeerConnectionInterface::RTCConfiguration& o) const {
776 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800777}
778
zhihuang8f65cdf2016-05-06 18:40:30 -0700779// Generate a RTCP CNAME when a PeerConnection is created.
780std::string GenerateRtcpCname() {
781 std::string cname;
782 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100783 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800784 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700785 }
786 return cname;
787}
788
zhihuang1c378ed2017-08-17 14:10:50 -0700789bool ValidateOfferAnswerOptions(
790 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
791 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
792 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700793}
794
zhihuang1c378ed2017-08-17 14:10:50 -0700795// From |rtc_options|, fill parts of |session_options| shared by all generated
796// m= sections (in other words, nothing that involves a map/array).
797void ExtractSharedMediaSessionOptions(
798 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
799 cricket::MediaSessionOptions* session_options) {
800 session_options->vad_enabled = rtc_options.voice_activity_detection;
801 session_options->bundle_enabled = rtc_options.use_rtp_mux;
802}
zhihuanga77e6bb2017-08-14 18:17:48 -0700803
zhihuang38ede132017-06-15 12:52:32 -0700804PeerConnection::PeerConnection(PeerConnectionFactory* factory,
805 std::unique_ptr<RtcEventLog> event_log,
806 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700808 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700809 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700810 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700811 remote_streams_(StreamCollection::Create()),
812 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813
814PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100815 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800816 RTC_DCHECK_RUN_ON(signaling_thread());
817
Steve Anton8af21862017-12-15 11:20:13 -0800818 // Need to stop transceivers before destroying the stats collector because
819 // AudioRtpSender has a reference to the StatsCollector it will update when
820 // stopping.
821 for (auto transceiver : transceivers_) {
822 transceiver->Stop();
823 }
Steve Anton4171afb2017-11-20 10:20:22 -0800824
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700825 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800826 if (stats_collector_) {
827 stats_collector_->WaitForPendingRequest();
828 stats_collector_ = nullptr;
829 }
Steve Anton75737c02017-11-06 10:37:17 -0800830
Steve Anton8af21862017-12-15 11:20:13 -0800831 // Don't destroy BaseChannels until after stats has been cleaned up so that
832 // the last stats request can still read from the channels.
833 DestroyAllChannels();
834
Mirko Bonadei675513b2017-11-09 11:09:25 +0100835 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800836
837 webrtc_session_desc_factory_.reset();
838 sctp_invoker_.reset();
839 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800840 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800841 transport_controller_.reset();
842
deadbeef91dd5672016-05-18 16:55:30 -0700843 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700844 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700845 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700846 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700847 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700848 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800849 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700850 event_log_.reset();
851 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852}
853
Steve Anton8af21862017-12-15 11:20:13 -0800854void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800855 // Destroy video channels first since they may have a pointer to a voice
856 // channel.
857 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800858 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800859 DestroyTransceiverChannel(transceiver);
860 }
861 }
862 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800863 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800864 DestroyTransceiverChannel(transceiver);
865 }
866 }
867 DestroyDataChannel();
868}
869
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000871 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700872 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100873 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700874
875 RTCError config_error = ValidateConfiguration(configuration);
876 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100877 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700878 return false;
879 }
880
Benjamin Wrightcab58882018-05-02 15:12:47 -0700881 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100882 RTC_LOG(LS_ERROR)
883 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100884 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800885 return false;
886 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200887
Benjamin Wrightcab58882018-05-02 15:12:47 -0700888 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800889 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100890 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100891 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800892 return false;
893 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700894
Benjamin Wrightcab58882018-05-02 15:12:47 -0700895 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700896 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700898 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800899
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200900 cricket::ServerAddresses stun_servers;
901 std::vector<cricket::RelayServerConfig> turn_servers;
902
903 RTCErrorType parse_error =
904 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
905 if (parse_error != RTCErrorType::NONE) {
906 return false;
907 }
908
deadbeef91dd5672016-05-18 16:55:30 -0700909 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700910 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700911 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200912 RTC_FROM_HERE,
913 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
914 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915 return false;
916 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200917 // If initialization was successful, note if STUN or TURN servers
918 // were supplied.
919 if (!stun_servers.empty()) {
920 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
921 }
922 if (!turn_servers.empty()) {
923 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
924 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700926 // Send information about IPv4/IPv6 status.
927 PeerConnectionAddressFamilyCounter address_family;
928 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
929 address_family = kPeerConnection_IPv6;
930 } else {
931 address_family = kPeerConnection_IPv4;
932 }
933 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
934 kPeerConnectionAddressFamilyCounter_Max);
935
Zhi Huange830e682018-03-30 10:48:35 -0700936 const PeerConnectionFactoryInterface::Options& options = factory_->options();
937
Steve Anton75737c02017-11-06 10:37:17 -0800938 // RFC 3264: The numeric value of the session id and version in the
939 // o line MUST be representable with a "64 bit signed integer".
940 // Due to this constraint session id |session_id_| is max limited to
941 // LLONG_MAX.
942 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700943 JsepTransportController::Config config;
944 config.redetermine_role_on_ice_restart =
945 configuration.redetermine_role_on_ice_restart;
946 config.ssl_max_version = factory_->options().ssl_max_version;
947 config.disable_encryption = options.disable_encryption;
948 config.bundle_policy = configuration.bundle_policy;
949 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700950 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
951 // stub.
952 config.crypto_options = configuration.crypto_options.has_value()
953 ? *configuration.crypto_options
954 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700955 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700956 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700957#if defined(ENABLE_EXTERNAL_AUTH)
958 config.enable_external_auth = true;
959#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700960 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700961
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700962 if (configuration.use_media_transport ||
963 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700964 if (!factory_->media_transport_factory()) {
965 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700966 << "PeerConnecton is initialized with use_media_transport = true or "
967 << "use_media_transport_for_data_channels = true "
968 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700969 return false;
970 }
971
972 config.media_transport_factory = factory_->media_transport_factory();
973 }
974
Zhi Huange830e682018-03-30 10:48:35 -0700975 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700976 signaling_thread(), network_thread(), port_allocator_.get(),
977 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700978 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +0000979 this, &PeerConnection::OnTransportControllerConnectionState);
980 transport_controller_->SignalStandardizedIceConnectionState.connect(
981 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +0200982 transport_controller_->SignalConnectionState.connect(
983 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700984 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800985 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700986 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800987 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700988 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800989 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
990 transport_controller_->SignalDtlsHandshakeError.connect(
991 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
992
993 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700994
deadbeefab9b2d12015-10-14 11:33:11 -0700995 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700996 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997
Steve Antonba818672017-11-06 10:21:57 -0800998 configuration_ = configuration;
999
Steve Anton75737c02017-11-06 10:37:17 -08001000 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1001 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1002 if (!configuration.certificates.empty()) {
1003 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1004 // just picking the first one. The decision should be made based on the DTLS
1005 // handshake. The DTLS negotiations need to know about all certificates.
1006 certificate = configuration.certificates[0];
1007 }
1008
Steve Antond25da372017-11-06 14:50:29 -08001009 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001010
1011 if (options.disable_encryption) {
1012 dtls_enabled_ = false;
1013 } else {
1014 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001015 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001016 // |configuration| can override the default |dtls_enabled_| value.
1017 if (configuration.enable_dtls_srtp) {
1018 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1019 }
1020 }
1021
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001022 if (configuration.use_media_transport_for_data_channels) {
1023 if (configuration.enable_rtp_data_channel) {
1024 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1025 "use_media_transport_for_data_channels are "
1026 "incompatible and cannot both be set to true";
1027 return false;
1028 }
1029 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1030 } else if (configuration.enable_rtp_data_channel) {
1031 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1032 // set. It takes precendence over the disable_sctp_data_channels
1033 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001034 data_channel_type_ = cricket::DCT_RTP;
1035 } else {
1036 // DTLS has to be enabled to use SCTP.
1037 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1038 data_channel_type_ = cricket::DCT_SCTP;
1039 }
1040 }
1041
1042 video_options_.screencast_min_bitrate_kbps =
1043 configuration.screencast_min_bitrate;
1044 audio_options_.combined_audio_video_bwe =
1045 configuration.combined_audio_video_bwe;
1046
1047 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001048 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001049
1050 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001051 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001052
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001053 audio_options_.audio_jitter_buffer_min_delay_ms =
1054 configuration.audio_jitter_buffer_min_delay_ms;
1055
Steve Anton75737c02017-11-06 10:37:17 -08001056 // Whether the certificate generator/certificate is null or not determines
1057 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1058 // the right instructions by clearing the variables if needed.
1059 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001060 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001061 certificate = nullptr;
1062 } else if (certificate) {
1063 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001064 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001065 }
1066
1067 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1068 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001069 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001070 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1071 this, &PeerConnection::OnCertificateReady);
1072
1073 if (options.disable_encryption) {
1074 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1075 }
1076
1077 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001078 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001079 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080
Steve Anton4171afb2017-11-20 10:20:22 -08001081 // Add default audio/video transceivers for Plan B SDP.
1082 if (!IsUnifiedPlan()) {
1083 transceivers_.push_back(
1084 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1085 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1086 transceivers_.push_back(
1087 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1088 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1089 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001090 int delay_ms =
1091 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001092 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1093 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094 return true;
1095}
1096
Steve Anton038834f2017-07-14 15:59:59 -07001097RTCError PeerConnection::ValidateConfiguration(
1098 const RTCConfiguration& config) const {
1099 if (config.ice_regather_interval_range &&
1100 config.continual_gathering_policy == GATHER_ONCE) {
1101 return RTCError(RTCErrorType::INVALID_PARAMETER,
1102 "ice_regather_interval_range specified but continual "
1103 "gathering policy is GATHER_ONCE");
1104 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001105 auto result =
1106 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1107 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001108}
1109
Yves Gerey665174f2018-06-19 15:03:05 +02001110rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001111 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1112 "Plan SdpSemantics. Please use GetSenders "
1113 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001114 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115}
1116
Yves Gerey665174f2018-06-19 15:03:05 +02001117rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001118 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1119 "Plan SdpSemantics. Please use GetReceivers "
1120 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001121 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122}
1123
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001124bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001125 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1126 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001127 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001128 if (IsClosed()) {
1129 return false;
1130 }
deadbeefab9b2d12015-10-14 11:33:11 -07001131 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132 return false;
1133 }
deadbeefab9b2d12015-10-14 11:33:11 -07001134
1135 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001136 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1137 observer->SignalAudioTrackAdded.connect(this,
1138 &PeerConnection::OnAudioTrackAdded);
1139 observer->SignalAudioTrackRemoved.connect(
1140 this, &PeerConnection::OnAudioTrackRemoved);
1141 observer->SignalVideoTrackAdded.connect(this,
1142 &PeerConnection::OnVideoTrackAdded);
1143 observer->SignalVideoTrackRemoved.connect(
1144 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001145 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001146
deadbeefab9b2d12015-10-14 11:33:11 -07001147 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001148 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001149 }
1150 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001151 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001152 }
1153
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001154 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001155 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156 return true;
1157}
1158
1159void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001160 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1161 "Plan SdpSemantics. Please use RemoveTrack "
1162 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001163 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001164 if (!IsClosed()) {
1165 for (const auto& track : local_stream->GetAudioTracks()) {
1166 RemoveAudioTrack(track.get(), local_stream);
1167 }
1168 for (const auto& track : local_stream->GetVideoTracks()) {
1169 RemoveVideoTrack(track.get(), local_stream);
1170 }
deadbeefab9b2d12015-10-14 11:33:11 -07001171 }
deadbeefab9b2d12015-10-14 11:33:11 -07001172 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001173 stream_observers_.erase(
1174 std::remove_if(
1175 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001176 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001177 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001178 }),
1179 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001180
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001181 if (IsClosed()) {
1182 return;
1183 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001184 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185}
1186
Steve Anton2d6c76a2018-01-05 17:10:52 -08001187RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001188 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001189 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001190 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001191 if (!track) {
1192 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1193 }
1194 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1195 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1196 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1197 "Track has invalid kind: " + track->kind());
1198 }
Steve Antonf9381f02017-12-14 10:23:57 -08001199 if (IsClosed()) {
1200 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1201 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001202 }
Steve Anton4171afb2017-11-20 10:20:22 -08001203 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001204 LOG_AND_RETURN_ERROR(
1205 RTCErrorType::INVALID_PARAMETER,
1206 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001207 }
Steve Antonf9381f02017-12-14 10:23:57 -08001208 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001209 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1210 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001211 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001212 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001213 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001214 }
1215 return sender_or_error;
1216}
deadbeefe1f9d832016-01-14 15:35:42 -08001217
Steve Antonf9381f02017-12-14 10:23:57 -08001218RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1219PeerConnection::AddTrackPlanB(
1220 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001221 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001222 if (stream_ids.size() > 1u) {
1223 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1224 "AddTrack with more than one stream is not "
1225 "supported with Plan B semantics.");
1226 }
1227 std::vector<std::string> adjusted_stream_ids = stream_ids;
1228 if (adjusted_stream_ids.empty()) {
1229 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1230 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001231 cricket::MediaType media_type =
1232 (track->kind() == MediaStreamTrackInterface::kAudioKind
1233 ? cricket::MEDIA_TYPE_AUDIO
1234 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001235 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001236 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001237 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001238 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001239 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001240 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001241 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001242 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001243 if (sender_info) {
1244 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001245 }
Steve Antonf9381f02017-12-14 10:23:57 -08001246 } else {
1247 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001248 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001249 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001250 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001251 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001252 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001253 if (sender_info) {
1254 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001255 }
deadbeefe1f9d832016-01-14 15:35:42 -08001256 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001257 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001258}
deadbeefe1f9d832016-01-14 15:35:42 -08001259
Steve Antonf9381f02017-12-14 10:23:57 -08001260RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1261PeerConnection::AddTrackUnifiedPlan(
1262 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001263 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001264 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1265 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001266 RTC_LOG(LS_INFO) << "Reusing an existing "
1267 << cricket::MediaTypeToString(transceiver->media_type())
1268 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001269 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001270 transceiver->internal()->set_direction(
1271 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001272 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001273 transceiver->internal()->set_direction(
1274 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001275 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001276 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001277 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001278 } else {
1279 cricket::MediaType media_type =
1280 (track->kind() == MediaStreamTrackInterface::kAudioKind
1281 ? cricket::MEDIA_TYPE_AUDIO
1282 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001283 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1284 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001285 std::string sender_id = track->id();
1286 // Avoid creating a sender with an existing ID by generating a random ID.
1287 // This can happen if this is the second time AddTrack has created a sender
1288 // for this track.
1289 if (FindSenderById(sender_id)) {
1290 sender_id = rtc::CreateRandomUuid();
1291 }
Florent Castelli892acf02018-10-01 22:47:20 +02001292 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001293 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1294 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001295 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001296 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001297 }
Steve Antonf9381f02017-12-14 10:23:57 -08001298 return transceiver->sender();
1299}
1300
1301rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1302PeerConnection::FindFirstTransceiverForAddedTrack(
1303 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1304 RTC_DCHECK(track);
1305 for (auto transceiver : transceivers_) {
1306 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001307 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001308 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001309 !transceiver->internal()->has_ever_been_used_to_send() &&
1310 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001311 return transceiver;
1312 }
1313 }
1314 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001315}
1316
1317bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1318 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001319 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001320}
1321
Steve Anton24db5732018-07-23 10:27:33 -07001322RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001323 rtc::scoped_refptr<RtpSenderInterface> sender) {
1324 if (!sender) {
1325 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1326 }
deadbeefe1f9d832016-01-14 15:35:42 -08001327 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001328 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1329 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001330 }
Steve Antonf9381f02017-12-14 10:23:57 -08001331 if (IsUnifiedPlan()) {
1332 auto transceiver = FindTransceiverBySender(sender);
1333 if (!transceiver || !sender->track()) {
1334 return RTCError::OK();
1335 }
1336 sender->SetTrack(nullptr);
1337 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001338 transceiver->internal()->set_direction(
1339 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001340 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001341 transceiver->internal()->set_direction(
1342 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001343 }
Steve Anton4171afb2017-11-20 10:20:22 -08001344 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001345 bool removed;
1346 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1347 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1348 } else {
1349 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1350 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1351 }
1352 if (!removed) {
1353 LOG_AND_RETURN_ERROR(
1354 RTCErrorType::INVALID_PARAMETER,
1355 "Couldn't find sender " + sender->id() + " to remove.");
1356 }
Steve Anton4171afb2017-11-20 10:20:22 -08001357 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001358 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001359 return RTCError::OK();
1360}
1361
1362rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1363PeerConnection::FindTransceiverBySender(
1364 rtc::scoped_refptr<RtpSenderInterface> sender) {
1365 for (auto transceiver : transceivers_) {
1366 if (transceiver->sender() == sender) {
1367 return transceiver;
1368 }
1369 }
1370 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001371}
1372
Steve Anton9158ef62017-11-27 13:01:52 -08001373RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1374PeerConnection::AddTransceiver(
1375 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1376 return AddTransceiver(track, RtpTransceiverInit());
1377}
1378
1379RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1380PeerConnection::AddTransceiver(
1381 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1382 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001383 RTC_CHECK(IsUnifiedPlan())
1384 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001385 if (!track) {
1386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1387 }
1388 cricket::MediaType media_type;
1389 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1390 media_type = cricket::MEDIA_TYPE_AUDIO;
1391 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1392 media_type = cricket::MEDIA_TYPE_VIDEO;
1393 } else {
1394 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1395 "Track kind is not audio or video");
1396 }
1397 return AddTransceiver(media_type, track, init);
1398}
1399
1400RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1401PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1402 return AddTransceiver(media_type, RtpTransceiverInit());
1403}
1404
1405RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1406PeerConnection::AddTransceiver(cricket::MediaType media_type,
1407 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001408 RTC_CHECK(IsUnifiedPlan())
1409 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001410 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1411 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1413 "media type is not audio or video");
1414 }
1415 return AddTransceiver(media_type, nullptr, init);
1416}
1417
1418RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1419PeerConnection::AddTransceiver(
1420 cricket::MediaType media_type,
1421 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001422 const RtpTransceiverInit& init,
1423 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001424 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1425 media_type == cricket::MEDIA_TYPE_VIDEO));
1426 if (track) {
1427 RTC_DCHECK_EQ(media_type,
1428 (track->kind() == MediaStreamTrackInterface::kAudioKind
1429 ? cricket::MEDIA_TYPE_AUDIO
1430 : cricket::MEDIA_TYPE_VIDEO));
1431 }
1432
1433 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001434 if (init.send_encodings.size() > 1) {
1435 LOG_AND_RETURN_ERROR(
1436 RTCErrorType::UNSUPPORTED_PARAMETER,
1437 "Attempted to create an encoder with more than 1 encoding parameter.");
1438 }
1439
1440 for (const auto& encoding : init.send_encodings) {
1441 if (encoding.ssrc.has_value()) {
1442 LOG_AND_RETURN_ERROR(
1443 RTCErrorType::UNSUPPORTED_PARAMETER,
1444 "Attempted to set an unimplemented parameter of RtpParameters.");
1445 }
1446 }
1447
1448 RtpParameters parameters;
1449 parameters.encodings = init.send_encodings;
1450 if (UnimplementedRtpParameterHasValue(parameters)) {
1451 LOG_AND_RETURN_ERROR(
1452 RTCErrorType::UNSUPPORTED_PARAMETER,
1453 "Attempted to set an unimplemented parameter of RtpParameters.");
1454 }
Steve Anton9158ef62017-11-27 13:01:52 -08001455
Steve Anton3d954a62018-04-02 11:27:23 -07001456 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1457 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001458 // Set the sender ID equal to the track ID if the track is specified unless
1459 // that sender ID is already in use.
1460 std::string sender_id =
1461 (track && !FindSenderById(track->id()) ? track->id()
1462 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001463 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1464 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001465 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1466 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1467 transceiver->internal()->set_direction(init.direction);
1468
Steve Anton22da89f2018-01-25 13:58:07 -08001469 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001470 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001471 }
Steve Antonf9381f02017-12-14 10:23:57 -08001472
1473 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1474}
1475
Steve Anton02ee47c2018-01-10 16:26:06 -08001476rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1477PeerConnection::CreateSender(
1478 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001479 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001480 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001481 const std::vector<std::string>& stream_ids,
1482 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001483 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001484 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1485 RTC_DCHECK(!track ||
1486 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1487 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1488 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001489 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001490 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001491 } else {
1492 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1493 RTC_DCHECK(!track ||
1494 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1495 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001496 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001497 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001498 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001499 bool set_track_succeeded = sender->SetTrack(track);
1500 RTC_DCHECK(set_track_succeeded);
1501 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001502 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001503 return sender;
1504}
1505
1506rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1507PeerConnection::CreateReceiver(cricket::MediaType media_type,
1508 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001509 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1510 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001511 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001512 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001513 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1514 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001515 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001516 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001517 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001518 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001519 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1520 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001521 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001522 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001523 return receiver;
1524}
1525
1526rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1527PeerConnection::CreateAndAddTransceiver(
1528 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1529 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1530 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001531 // Ensure that the new sender does not have an ID that is already in use by
1532 // another sender.
1533 // Allow receiver IDs to conflict since those come from remote SDP (which
1534 // could be invalid, but should not cause a crash).
1535 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001536 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1537 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001538 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001539 transceiver->internal()->SignalNegotiationNeeded.connect(
1540 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001541 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001542}
1543
Steve Anton52d86772018-02-20 15:48:12 -08001544void PeerConnection::OnNegotiationNeeded() {
1545 RTC_DCHECK_RUN_ON(signaling_thread());
1546 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001547 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001548}
1549
deadbeeffac06552015-11-25 11:26:01 -08001550rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001551 const std::string& kind,
1552 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001553 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1554 "Plan SdpSemantics. Please use AddTransceiver "
1555 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001556 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001557 if (IsClosed()) {
1558 return nullptr;
1559 }
Steve Anton4171afb2017-11-20 10:20:22 -08001560
Seth Hampson5b4f0752018-04-02 16:31:36 -07001561 // Internally we need to have one stream with Plan B semantics, so we
1562 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001563 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001564 if (stream_id.empty()) {
1565 stream_ids.push_back(rtc::CreateRandomUuid());
1566 RTC_LOG(LS_INFO)
1567 << "No stream_id specified for sender. Generated stream ID: "
1568 << stream_ids[0];
1569 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001570 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001571 }
1572
Steve Anton4171afb2017-11-20 10:20:22 -08001573 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001574 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001575 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001576 auto* audio_sender = new AudioRtpSender(
1577 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001578 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001579 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001580 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001581 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001582 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001583 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001584 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001585 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001586 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001587 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001588 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001589 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001590 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001591 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001592 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001593 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001594
deadbeefe1f9d832016-01-14 15:35:42 -08001595 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001596}
1597
deadbeef70ab1a12015-09-28 16:53:55 -07001598std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1599 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001600 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001601 for (auto sender : GetSendersInternal()) {
1602 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001603 }
1604 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001605}
1606
Steve Anton4171afb2017-11-20 10:20:22 -08001607std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1608PeerConnection::GetSendersInternal() const {
1609 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1610 all_senders;
1611 for (auto transceiver : transceivers_) {
1612 auto senders = transceiver->internal()->senders();
1613 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1614 }
1615 return all_senders;
1616}
1617
deadbeef70ab1a12015-09-28 16:53:55 -07001618std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1619PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001620 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001621 for (const auto& receiver : GetReceiversInternal()) {
1622 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001623 }
1624 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001625}
1626
Steve Anton4171afb2017-11-20 10:20:22 -08001627std::vector<
1628 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1629PeerConnection::GetReceiversInternal() const {
1630 std::vector<
1631 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1632 all_receivers;
1633 for (auto transceiver : transceivers_) {
1634 auto receivers = transceiver->internal()->receivers();
1635 all_receivers.insert(all_receivers.end(), receivers.begin(),
1636 receivers.end());
1637 }
1638 return all_receivers;
1639}
1640
Steve Anton9158ef62017-11-27 13:01:52 -08001641std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1642PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001643 RTC_CHECK(IsUnifiedPlan())
1644 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001645 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1646 for (auto transceiver : transceivers_) {
1647 all_transceivers.push_back(transceiver);
1648 }
1649 return all_transceivers;
1650}
1651
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001652bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001653 MediaStreamTrackInterface* track,
1654 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001655 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001656 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001657 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001658 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001659 return false;
1660 }
1661
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001662 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001663 // The StatsCollector is used to tell if a track is valid because it may
1664 // remember tracks that the PeerConnection previously removed.
1665 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001666 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1667 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001668 return false;
1669 }
Steve Antonad182762018-09-05 20:22:40 +00001670 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1671 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001672 return true;
1673}
1674
hbos74e1a4f2016-09-15 23:33:01 -07001675void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001676 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001677 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001678 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001679 stats_collector_->GetStatsReport(callback);
1680}
1681
Henrik Boström1df1bf82018-03-20 13:24:20 +01001682void PeerConnection::GetStats(
1683 rtc::scoped_refptr<RtpSenderInterface> selector,
1684 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1685 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1686 RTC_DCHECK(callback);
1687 RTC_DCHECK(stats_collector_);
1688 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1689 if (selector) {
1690 for (const auto& proxy_transceiver : transceivers_) {
1691 for (const auto& proxy_sender :
1692 proxy_transceiver->internal()->senders()) {
1693 if (proxy_sender == selector) {
1694 internal_sender = proxy_sender->internal();
1695 break;
1696 }
1697 }
1698 if (internal_sender)
1699 break;
1700 }
1701 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001702 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001703 // belong to the PeerConnection (in Plan B, senders can be removed from the
1704 // PeerConnection). This means that "all the stats objects representing the
1705 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1706 // produces an empty stats report.
1707 stats_collector_->GetStatsReport(internal_sender, callback);
1708}
1709
1710void PeerConnection::GetStats(
1711 rtc::scoped_refptr<RtpReceiverInterface> selector,
1712 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1713 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1714 RTC_DCHECK(callback);
1715 RTC_DCHECK(stats_collector_);
1716 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1717 if (selector) {
1718 for (const auto& proxy_transceiver : transceivers_) {
1719 for (const auto& proxy_receiver :
1720 proxy_transceiver->internal()->receivers()) {
1721 if (proxy_receiver == selector) {
1722 internal_receiver = proxy_receiver->internal();
1723 break;
1724 }
1725 }
1726 if (internal_receiver)
1727 break;
1728 }
1729 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001730 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001731 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1732 // the PeerConnection). This means that "all the stats objects representing
1733 // the selector" is an empty set. Invoking GetStatsReport() with a null
1734 // selector produces an empty stats report.
1735 stats_collector_->GetStatsReport(internal_receiver, callback);
1736}
1737
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001738PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1739 return signaling_state_;
1740}
1741
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001742PeerConnectionInterface::IceConnectionState
1743PeerConnection::ice_connection_state() {
1744 return ice_connection_state_;
1745}
1746
Alex Loiko9289eda2018-11-23 16:18:59 +00001747PeerConnectionInterface::IceConnectionState
1748PeerConnection::standardized_ice_connection_state() {
1749 return standardized_ice_connection_state_;
1750}
1751
Jonas Olsson635474e2018-10-18 15:58:17 +02001752PeerConnectionInterface::PeerConnectionState
1753PeerConnection::peer_connection_state() {
1754 return connection_state_;
1755}
1756
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001757PeerConnectionInterface::IceGatheringState
1758PeerConnection::ice_gathering_state() {
1759 return ice_gathering_state_;
1760}
1761
Yves Gerey665174f2018-06-19 15:03:05 +02001762rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 const std::string& label,
1764 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001765 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001766
deadbeefab9b2d12015-10-14 11:33:11 -07001767 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001768
kwibergd1fe2812016-04-27 06:47:29 -07001769 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001770 if (config) {
1771 internal_config.reset(new InternalDataChannelInit(*config));
1772 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001773 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001774 InternalCreateDataChannel(label, internal_config.get()));
1775 if (!channel.get()) {
1776 return nullptr;
1777 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001778
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001779 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1780 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001781 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001782 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001783 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001784 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001785 return DataChannelProxy::Create(signaling_thread(), channel.get());
1786}
1787
1788void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001789 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001790 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001791
nisse7ce109a2017-01-31 00:57:56 -08001792 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001793 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001794 return;
1795 }
deadbeefab9b2d12015-10-14 11:33:11 -07001796
Steve Anton8d3444d2017-10-20 15:30:51 -07001797 if (IsClosed()) {
1798 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001799 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001800 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001801 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001802 return;
1803 }
1804
zhihuang1c378ed2017-08-17 14:10:50 -07001805 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001806 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001807 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001808 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001809 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001810 return;
1811 }
1812
Steve Anton22da89f2018-01-25 13:58:07 -08001813 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1814 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1815 if (IsUnifiedPlan()) {
1816 RTCError error = HandleLegacyOfferOptions(options);
1817 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001818 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001819 return;
1820 }
1821 }
1822
zhihuang1c378ed2017-08-17 14:10:50 -07001823 cricket::MediaSessionOptions session_options;
1824 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001825 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001826}
1827
Steve Anton22da89f2018-01-25 13:58:07 -08001828RTCError PeerConnection::HandleLegacyOfferOptions(
1829 const RTCOfferAnswerOptions& options) {
1830 RTC_DCHECK(IsUnifiedPlan());
1831
1832 if (options.offer_to_receive_audio == 0) {
1833 RemoveRecvDirectionFromReceivingTransceiversOfType(
1834 cricket::MEDIA_TYPE_AUDIO);
1835 } else if (options.offer_to_receive_audio == 1) {
1836 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1837 } else if (options.offer_to_receive_audio > 1) {
1838 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1839 "offer_to_receive_audio > 1 is not supported.");
1840 }
1841
1842 if (options.offer_to_receive_video == 0) {
1843 RemoveRecvDirectionFromReceivingTransceiversOfType(
1844 cricket::MEDIA_TYPE_VIDEO);
1845 } else if (options.offer_to_receive_video == 1) {
1846 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1847 } else if (options.offer_to_receive_video > 1) {
1848 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1849 "offer_to_receive_video > 1 is not supported.");
1850 }
1851
1852 return RTCError::OK();
1853}
1854
1855void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1856 cricket::MediaType media_type) {
1857 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001858 RtpTransceiverDirection new_direction =
1859 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1860 if (new_direction != transceiver->direction()) {
1861 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1862 << " transceiver (MID="
1863 << transceiver->mid().value_or("<not set>") << ") from "
1864 << RtpTransceiverDirectionToString(
1865 transceiver->direction())
1866 << " to "
1867 << RtpTransceiverDirectionToString(new_direction)
1868 << " since CreateOffer specified offer_to_receive=0";
1869 transceiver->internal()->set_direction(new_direction);
1870 }
Steve Anton22da89f2018-01-25 13:58:07 -08001871 }
1872}
1873
1874void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1875 cricket::MediaType media_type) {
1876 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001877 RTC_LOG(LS_INFO)
1878 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1879 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001880 RtpTransceiverInit init;
1881 init.direction = RtpTransceiverDirection::kRecvOnly;
1882 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1883 }
1884}
1885
1886std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1887PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1888 std::vector<
1889 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1890 receiving_transceivers;
1891 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001892 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001893 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1894 receiving_transceivers.push_back(transceiver);
1895 }
1896 }
1897 return receiving_transceivers;
1898}
1899
htaa2a49d92016-03-04 02:51:39 -08001900void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1901 const RTCOfferAnswerOptions& options) {
1902 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001903 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001904 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001905 return;
1906 }
1907
Steve Antondffead82018-02-06 10:31:29 -08001908 if (!(signaling_state_ == kHaveRemoteOffer ||
1909 signaling_state_ == kHaveLocalPrAnswer)) {
1910 std::string error =
1911 "PeerConnection cannot create an answer in a state other than "
1912 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001913 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001914 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001915 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001916 return;
1917 }
1918
Steve Antondffead82018-02-06 10:31:29 -08001919 // The remote description should be set if we're in the right state.
1920 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001921
Steve Anton22da89f2018-01-25 13:58:07 -08001922 if (IsUnifiedPlan()) {
1923 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1924 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1925 "supported with Unified Plan semantics. Use the "
1926 "RtpTransceiver API instead.";
1927 }
1928 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1929 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1930 "supported with Unified Plan semantics. Use the "
1931 "RtpTransceiver API instead.";
1932 }
1933 }
1934
htaa2a49d92016-03-04 02:51:39 -08001935 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001936 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001937
Steve Antond25da372017-11-06 14:50:29 -08001938 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001939}
1940
1941void PeerConnection::SetLocalDescription(
1942 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001943 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001944 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001945
Steve Anton80dd7b52018-02-16 17:08:42 -08001946 // The SetLocalDescription contract is that we take ownership of the session
1947 // description regardless of the outcome, so wrap it in a unique_ptr right
1948 // away. Ideally, SetLocalDescription's signature will be changed to take the
1949 // description as a unique_ptr argument to formalize this agreement.
1950 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1951
nisse7ce109a2017-01-31 00:57:56 -08001952 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001953 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001954 return;
1955 }
Steve Anton8a006912017-12-04 15:25:56 -08001956
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001958 PostSetSessionDescriptionFailure(
1959 observer,
1960 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001961 return;
1962 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001963
Steve Anton80dd7b52018-02-16 17:08:42 -08001964 // If a session error has occurred the PeerConnection is in a possibly
1965 // inconsistent state so fail right away.
1966 if (session_error() != SessionError::kNone) {
1967 std::string error_message = GetSessionErrorMsg();
1968 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001969 PostSetSessionDescriptionFailure(
1970 observer,
1971 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001972 return;
1973 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001974
Steve Anton80dd7b52018-02-16 17:08:42 -08001975 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1976 if (!error.ok()) {
1977 std::string error_message = GetSetDescriptionErrorMessage(
1978 cricket::CS_LOCAL, desc->GetType(), error);
1979 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001980 PostSetSessionDescriptionFailure(
1981 observer,
1982 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001983 return;
1984 }
1985
1986 // Grab the description type before moving ownership to ApplyLocalDescription,
1987 // which may destroy it before returning.
1988 const SdpType type = desc->GetType();
1989
1990 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001991 // |desc| may be destroyed at this point.
1992
1993 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001994 // If ApplyLocalDescription fails, the PeerConnection could be in an
1995 // inconsistent state, so act conservatively here and set the session error
1996 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1997 SetSessionError(SessionError::kContent, error.message());
1998 std::string error_message =
1999 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2000 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002001 PostSetSessionDescriptionFailure(
2002 observer,
2003 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002004 return;
2005 }
Steve Anton8a006912017-12-04 15:25:56 -08002006 RTC_DCHECK(local_description());
2007
2008 PostSetSessionDescriptionSuccess(observer);
2009
Steve Antonad182762018-09-05 20:22:40 +00002010 // MaybeStartGathering needs to be called after posting
2011 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2012 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002013 transport_controller_->MaybeStartGathering();
2014
Steve Antona3a92c22017-12-07 10:27:41 -08002015 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002016 // TODO(deadbeef): We already had to hop to the network thread for
2017 // MaybeStartGathering...
2018 network_thread()->Invoke<void>(
2019 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2020 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002021 // Make UMA notes about what was agreed to.
2022 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002023 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002024 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002025}
2026
2027RTCError PeerConnection::ApplyLocalDescription(
2028 std::unique_ptr<SessionDescriptionInterface> desc) {
2029 RTC_DCHECK_RUN_ON(signaling_thread());
2030 RTC_DCHECK(desc);
2031
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002032 // Update stats here so that we have the most recent stats for tracks and
2033 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002034 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002035
Steve Antondcc3c022017-12-22 16:02:54 -08002036 // Take a reference to the old local description since it's used below to
2037 // compare against the new local description. When setting the new local
2038 // description, grab ownership of the replaced session description in case it
2039 // is the same as |old_local_description|, to keep it alive for the duration
2040 // of the method.
2041 const SessionDescriptionInterface* old_local_description =
2042 local_description();
2043 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002044 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002045 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002046 replaced_local_description = pending_local_description_
2047 ? std::move(pending_local_description_)
2048 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002049 current_local_description_ = std::move(desc);
2050 pending_local_description_ = nullptr;
2051 current_remote_description_ = std::move(pending_remote_description_);
2052 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002053 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002054 pending_local_description_ = std::move(desc);
2055 }
2056 // The session description to apply now must be accessed by
2057 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002058 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002059
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002060 if (!is_caller_) {
2061 if (remote_description()) {
2062 // Remote description was applied first, so this PC is the callee.
2063 is_caller_ = false;
2064 } else {
2065 // Local description is applied first, so this PC is the caller.
2066 is_caller_ = true;
2067 }
2068 }
2069
Zhi Huange830e682018-03-30 10:48:35 -07002070 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2071 if (!error.ok()) {
2072 return error;
2073 }
2074
Steve Antondcc3c022017-12-22 16:02:54 -08002075 if (IsUnifiedPlan()) {
2076 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002077 cricket::CS_LOCAL, *local_description(), old_local_description,
2078 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002079 if (!error.ok()) {
2080 return error;
2081 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002082 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2083 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002084 for (auto transceiver : transceivers_) {
2085 const ContentInfo* content =
2086 FindMediaSectionForTransceiver(transceiver, local_description());
2087 if (!content) {
2088 continue;
2089 }
2090 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002091 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2092 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002093 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002094 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2095 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2096 // "recvonly", process the removal of a remote track for the media
2097 // description, given transceiver, removeList, and muteTracks.
2098 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2099 (transceiver->internal()->fired_direction() &&
2100 RtpTransceiverDirectionHasRecv(
2101 *transceiver->internal()->fired_direction()))) {
2102 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2103 &removed_streams);
2104 }
2105 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2106 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002107 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002108 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002109 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002110 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002111 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002112 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002113 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002114 }
2115 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002116 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002117 }
2118 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002119 // Media channels will be created only when offer is set. These may use new
2120 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002121 if (type == SdpType::kOffer) {
2122 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2123 // description is applied. Restore back to old description.
2124 RTCError error = CreateChannels(*local_description()->description());
2125 if (!error.ok()) {
2126 return error;
2127 }
2128 }
Steve Antondcc3c022017-12-22 16:02:54 -08002129 // Remove unused channels if MediaContentDescription is rejected.
2130 RemoveUnusedChannels(local_description()->description());
2131 }
Steve Anton8a006912017-12-04 15:25:56 -08002132
Zhi Huange830e682018-03-30 10:48:35 -07002133 error = UpdateSessionState(type, cricket::CS_LOCAL,
2134 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002135 if (!error.ok()) {
2136 return error;
2137 }
Steve Antondcc3c022017-12-22 16:02:54 -08002138
Steve Anton8a006912017-12-04 15:25:56 -08002139 if (remote_description()) {
2140 // Now that we have a local description, we can push down remote candidates.
2141 UseCandidatesInSessionDescription(remote_description());
2142 }
2143
2144 pending_ice_restarts_.clear();
2145 if (session_error() != SessionError::kNone) {
2146 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2147 }
2148
deadbeefab9b2d12015-10-14 11:33:11 -07002149 // If setting the description decided our SSL role, allocate any necessary
2150 // SCTP sids.
2151 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002152 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002153 AllocateSctpSids(role);
2154 }
2155
Steve Antond3679212018-01-17 17:41:02 -08002156 if (IsUnifiedPlan()) {
2157 for (auto transceiver : transceivers_) {
2158 const ContentInfo* content =
2159 FindMediaSectionForTransceiver(transceiver, local_description());
2160 if (!content) {
2161 continue;
2162 }
Steve Anton74255ff2018-01-24 18:32:57 -08002163 const auto& streams = content->media_description()->streams();
2164 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002165 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002166 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002167 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002168 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002169 } else {
2170 // 0 is a special value meaning "this sender has no associated send
2171 // stream". Need to call this so the sender won't attempt to configure
2172 // a no longer existing stream and run into DCHECKs in the lower
2173 // layers.
2174 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002175 }
2176 }
2177 } else {
2178 // Plan B semantics.
2179
Steve Antondcc3c022017-12-22 16:02:54 -08002180 // Update state and SSRC of local MediaStreams and DataChannels based on the
2181 // local session description.
2182 const cricket::ContentInfo* audio_content =
2183 GetFirstAudioContent(local_description()->description());
2184 if (audio_content) {
2185 if (audio_content->rejected) {
2186 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2187 } else {
2188 const cricket::AudioContentDescription* audio_desc =
2189 audio_content->media_description()->as_audio();
2190 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2191 }
deadbeeffaac4972015-11-12 15:33:07 -08002192 }
deadbeefab9b2d12015-10-14 11:33:11 -07002193
Steve Antondcc3c022017-12-22 16:02:54 -08002194 const cricket::ContentInfo* video_content =
2195 GetFirstVideoContent(local_description()->description());
2196 if (video_content) {
2197 if (video_content->rejected) {
2198 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2199 } else {
2200 const cricket::VideoContentDescription* video_desc =
2201 video_content->media_description()->as_video();
2202 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2203 }
deadbeeffaac4972015-11-12 15:33:07 -08002204 }
deadbeefab9b2d12015-10-14 11:33:11 -07002205 }
2206
2207 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002208 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002209 if (data_content) {
2210 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002211 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002212 if (rtc::starts_with(data_desc->protocol().data(),
2213 cricket::kMediaProtocolRtpPrefix)) {
2214 UpdateLocalRtpDataChannels(data_desc->streams());
2215 }
2216 }
2217
Steve Anton8a006912017-12-04 15:25:56 -08002218 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219}
2220
2221void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002222 SetSessionDescriptionObserver* observer,
2223 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002224 SetRemoteDescription(
2225 std::unique_ptr<SessionDescriptionInterface>(desc),
2226 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2227 new SetRemoteDescriptionObserverAdapter(this, observer)));
2228}
2229
2230void PeerConnection::SetRemoteDescription(
2231 std::unique_ptr<SessionDescriptionInterface> desc,
2232 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002233 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002234
nisse7ce109a2017-01-31 00:57:56 -08002235 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002236 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002237 return;
2238 }
Steve Anton8a006912017-12-04 15:25:56 -08002239
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002240 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002241 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002242 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 return;
2244 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002245
Steve Anton80dd7b52018-02-16 17:08:42 -08002246 // If a session error has occurred the PeerConnection is in a possibly
2247 // inconsistent state so fail right away.
2248 if (session_error() != SessionError::kNone) {
2249 std::string error_message = GetSessionErrorMsg();
2250 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2251 observer->OnSetRemoteDescriptionComplete(
2252 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2253 return;
2254 }
Steve Anton71439a62018-02-15 11:53:06 -08002255
Steve Antonba42e992018-04-09 14:10:01 -07002256 if (desc->GetType() == SdpType::kOffer) {
2257 // Report to UMA the format of the received offer.
2258 ReportSdpFormatReceived(*desc);
2259 }
2260
Steve Anton80dd7b52018-02-16 17:08:42 -08002261 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002262 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002263 std::string error_message = GetSetDescriptionErrorMessage(
2264 cricket::CS_REMOTE, desc->GetType(), error);
2265 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002266 observer->OnSetRemoteDescriptionComplete(
2267 RTCError(error.type(), std::move(error_message)));
2268 return;
2269 }
Steve Anton71439a62018-02-15 11:53:06 -08002270
Steve Anton80dd7b52018-02-16 17:08:42 -08002271 // Grab the description type before moving ownership to
2272 // ApplyRemoteDescription, which may destroy it before returning.
2273 const SdpType type = desc->GetType();
2274
2275 error = ApplyRemoteDescription(std::move(desc));
2276 // |desc| may be destroyed at this point.
2277
2278 if (!error.ok()) {
2279 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2280 // inconsistent state, so act conservatively here and set the session error
2281 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2282 SetSessionError(SessionError::kContent, error.message());
2283 std::string error_message =
2284 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2285 RTC_LOG(LS_ERROR) << error_message;
2286 observer->OnSetRemoteDescriptionComplete(
2287 RTCError(error.type(), std::move(error_message)));
2288 return;
2289 }
2290 RTC_DCHECK(remote_description());
2291
2292 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002293 // TODO(deadbeef): We already had to hop to the network thread for
2294 // MaybeStartGathering...
2295 network_thread()->Invoke<void>(
2296 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2297 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002298 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002299 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002300 }
2301
2302 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002303 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002304}
2305
2306RTCError PeerConnection::ApplyRemoteDescription(
2307 std::unique_ptr<SessionDescriptionInterface> desc) {
2308 RTC_DCHECK_RUN_ON(signaling_thread());
2309 RTC_DCHECK(desc);
2310
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002311 // Update stats here so that we have the most recent stats for tracks and
2312 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002313 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002314
Steve Antondcc3c022017-12-22 16:02:54 -08002315 // Take a reference to the old remote description since it's used below to
2316 // compare against the new remote description. When setting the new remote
2317 // description, grab ownership of the replaced session description in case it
2318 // is the same as |old_remote_description|, to keep it alive for the duration
2319 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002320 const SessionDescriptionInterface* old_remote_description =
2321 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002322 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002323 SdpType type = desc->GetType();
2324 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002325 replaced_remote_description = pending_remote_description_
2326 ? std::move(pending_remote_description_)
2327 : std::move(current_remote_description_);
2328 current_remote_description_ = std::move(desc);
2329 pending_remote_description_ = nullptr;
2330 current_local_description_ = std::move(pending_local_description_);
2331 } else {
2332 replaced_remote_description = std::move(pending_remote_description_);
2333 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002334 }
Steve Anton8a006912017-12-04 15:25:56 -08002335 // The session description to apply now must be accessed by
2336 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002337 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002338
Zhi Huange830e682018-03-30 10:48:35 -07002339 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2340 if (!error.ok()) {
2341 return error;
2342 }
Steve Anton8a006912017-12-04 15:25:56 -08002343 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002344 if (IsUnifiedPlan()) {
2345 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002346 cricket::CS_REMOTE, *remote_description(), local_description(),
2347 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002348 if (!error.ok()) {
2349 return error;
2350 }
Steve Antondcc3c022017-12-22 16:02:54 -08002351 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002352 // Media channels will be created only when offer is set. These may use new
2353 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002354 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002355 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002356 // description is applied. Restore back to old description.
2357 RTCError error = CreateChannels(*remote_description()->description());
2358 if (!error.ok()) {
2359 return error;
2360 }
2361 }
Steve Antondcc3c022017-12-22 16:02:54 -08002362 // Remove unused channels if MediaContentDescription is rejected.
2363 RemoveUnusedChannels(remote_description()->description());
2364 }
Steve Anton8a006912017-12-04 15:25:56 -08002365
Zhi Huange830e682018-03-30 10:48:35 -07002366 // NOTE: Candidates allocation will be initiated only when
2367 // SetLocalDescription is called.
2368 error = UpdateSessionState(type, cricket::CS_REMOTE,
2369 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002370 if (!error.ok()) {
2371 return error;
2372 }
2373
2374 if (local_description() &&
2375 !UseCandidatesInSessionDescription(remote_description())) {
2376 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2377 }
2378
2379 if (old_remote_description) {
2380 for (const cricket::ContentInfo& content :
2381 old_remote_description->description()->contents()) {
2382 // Check if this new SessionDescription contains new ICE ufrag and
2383 // password that indicates the remote peer requests an ICE restart.
2384 // TODO(deadbeef): When we start storing both the current and pending
2385 // remote description, this should reset pending_ice_restarts and compare
2386 // against the current description.
2387 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2388 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002389 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002390 pending_ice_restarts_.insert(content.name);
2391 }
2392 } else {
2393 // We retain all received candidates only if ICE is not restarted.
2394 // When ICE is restarted, all previous candidates belong to an old
2395 // generation and should not be kept.
2396 // TODO(deadbeef): This goes against the W3C spec which says the remote
2397 // description should only contain candidates from the last set remote
2398 // description plus any candidates added since then. We should remove
2399 // this once we're sure it won't break anything.
2400 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2401 old_remote_description, content.name, mutable_remote_description());
2402 }
2403 }
2404 }
2405
2406 if (session_error() != SessionError::kNone) {
2407 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2408 }
2409
2410 // Set the the ICE connection state to connecting since the connection may
2411 // become writable with peer reflexive candidates before any remote candidate
2412 // is signaled.
2413 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2414 // is to have a new signal the indicates a change in checking state from the
2415 // transport and expose a new checking() member from transport that can be
2416 // read to determine the current checking state. The existing SignalConnecting
2417 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002418 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002419 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002420 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2421 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2422 }
2423
deadbeefab9b2d12015-10-14 11:33:11 -07002424 // If setting the description decided our SSL role, allocate any necessary
2425 // SCTP sids.
2426 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002427 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002428 AllocateSctpSids(role);
2429 }
2430
Steve Antondcc3c022017-12-22 16:02:54 -08002431 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002432 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002433 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002434 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002435 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002436 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002437 for (auto transceiver : transceivers_) {
2438 const ContentInfo* content =
2439 FindMediaSectionForTransceiver(transceiver, remote_description());
2440 if (!content) {
2441 continue;
2442 }
2443 const MediaContentDescription* media_desc = content->media_description();
2444 RtpTransceiverDirection local_direction =
2445 RtpTransceiverDirectionReversed(media_desc->direction());
2446 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2447 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2448 // transceiver's current direction is neither sendrecv nor recvonly,
2449 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002450 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002451 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002452 // The remote description has signaled the stream IDs.
2453 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002454 }
Steve Antondcc3c022017-12-22 16:02:54 -08002455 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002456 (!transceiver->fired_direction() ||
2457 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002458 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002459 << content->name << " (added to "
2460 << GetStreamIdsString(stream_ids) << ").";
2461
2462 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2463 for (const std::string& stream_id : stream_ids) {
2464 rtc::scoped_refptr<MediaStreamInterface> stream =
2465 remote_streams_->find(stream_id);
2466 if (!stream) {
2467 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2468 MediaStream::Create(stream_id));
2469 remote_streams_->AddStream(stream);
2470 added_streams.push_back(stream);
2471 }
2472 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002473 }
Henrik Boström5b147782018-12-04 11:25:05 +01002474 // Special case: "a=msid" missing, use random stream ID.
2475 if (media_streams.empty() &&
2476 !(remote_description()->description()->msid_signaling() &
2477 cricket::kMsidSignalingMediaSection)) {
2478 if (!missing_msid_default_stream_) {
2479 missing_msid_default_stream_ = MediaStreamProxy::Create(
2480 rtc::Thread::Current(),
2481 MediaStream::Create(rtc::CreateRandomUuid()));
2482 added_streams.push_back(missing_msid_default_stream_);
2483 }
2484 media_streams.push_back(missing_msid_default_stream_);
2485 }
Steve Anton3172c032018-05-03 15:30:18 -07002486 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002487 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2488 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002489 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002490 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002491 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002492 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2493 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2494 // removal of a remote track for the media description, given transceiver,
2495 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002496 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002497 (transceiver->fired_direction() &&
2498 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2499 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2500 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002501 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002502 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2503 transceiver->internal()->set_fired_direction(local_direction);
2504 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2505 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002506 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002507 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2508 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002509 transceiver->internal()->set_current_direction(local_direction);
2510 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002511 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2512 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002513 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002514 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2515 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002516 transceiver->Stop();
2517 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002518 if (!content->rejected &&
2519 RtpTransceiverDirectionHasRecv(local_direction)) {
2520 // Set ssrc to 0 in the case of an unsignalled ssrc.
2521 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002522 if (!media_desc->streams().empty() &&
2523 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002524 ssrc = media_desc->streams()[0].first_ssrc();
2525 }
2526 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002527 }
Steve Antondcc3c022017-12-22 16:02:54 -08002528 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002529 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002530 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002531 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002532 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002533 observer->OnTrack(transceiver);
2534 observer->OnAddTrack(transceiver->receiver(),
2535 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002536 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002537 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002538 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002539 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002540 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002541 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002542 }
2543 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002544 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002545 }
Steve Antondcc3c022017-12-22 16:02:54 -08002546 }
2547
Henrik Boströmfdb92012017-11-09 19:55:44 +01002548 const cricket::ContentInfo* audio_content =
2549 GetFirstAudioContent(remote_description()->description());
2550 const cricket::ContentInfo* video_content =
2551 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002552 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002553 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002554 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002555 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002556 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002557 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002558
2559 // Check if the descriptions include streams, just in case the peer supports
2560 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002561 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002562 (audio_desc && !audio_desc->streams().empty()) ||
2563 (video_desc && !video_desc->streams().empty())) {
2564 remote_peer_supports_msid_ = true;
2565 }
deadbeefab9b2d12015-10-14 11:33:11 -07002566
2567 // We wait to signal new streams until we finish processing the description,
2568 // since only at that point will new streams have all their tracks.
2569 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2570
Steve Antondcc3c022017-12-22 16:02:54 -08002571 if (!IsUnifiedPlan()) {
2572 // TODO(steveanton): When removing RTP senders/receivers in response to a
2573 // rejected media section, there is some cleanup logic that expects the
2574 // voice/ video channel to still be set. But in this method the voice/video
2575 // channel would have been destroyed by the SetRemoteDescription caller
2576 // above so the cleanup that relies on them fails to run. The RemoveSenders
2577 // calls should be moved to right before the DestroyChannel calls to fix
2578 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002579
Steve Antondcc3c022017-12-22 16:02:54 -08002580 // Find all audio rtp streams and create corresponding remote AudioTracks
2581 // and MediaStreams.
2582 if (audio_content) {
2583 if (audio_content->rejected) {
2584 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2585 } else {
2586 bool default_audio_track_needed =
2587 !remote_peer_supports_msid_ &&
2588 RtpTransceiverDirectionHasSend(audio_desc->direction());
2589 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2590 default_audio_track_needed, audio_desc->type(),
2591 new_streams);
2592 }
deadbeeffaac4972015-11-12 15:33:07 -08002593 }
deadbeefab9b2d12015-10-14 11:33:11 -07002594
Steve Antondcc3c022017-12-22 16:02:54 -08002595 // Find all video rtp streams and create corresponding remote VideoTracks
2596 // and MediaStreams.
2597 if (video_content) {
2598 if (video_content->rejected) {
2599 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2600 } else {
2601 bool default_video_track_needed =
2602 !remote_peer_supports_msid_ &&
2603 RtpTransceiverDirectionHasSend(video_desc->direction());
2604 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2605 default_video_track_needed, video_desc->type(),
2606 new_streams);
2607 }
deadbeeffaac4972015-11-12 15:33:07 -08002608 }
deadbeefab9b2d12015-10-14 11:33:11 -07002609
Steve Antondcc3c022017-12-22 16:02:54 -08002610 // Update the DataChannels with the information from the remote peer.
2611 if (data_desc) {
2612 if (rtc::starts_with(data_desc->protocol().data(),
2613 cricket::kMediaProtocolRtpPrefix)) {
2614 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2615 }
deadbeefab9b2d12015-10-14 11:33:11 -07002616 }
deadbeefab9b2d12015-10-14 11:33:11 -07002617
Steve Antondcc3c022017-12-22 16:02:54 -08002618 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002619 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002620 for (size_t i = 0; i < new_streams->count(); ++i) {
2621 MediaStreamInterface* new_stream = new_streams->at(i);
2622 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002623 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002624 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2625 }
deadbeefab9b2d12015-10-14 11:33:11 -07002626
Steve Antondcc3c022017-12-22 16:02:54 -08002627 UpdateEndedRemoteMediaStreams();
2628 }
deadbeefab9b2d12015-10-14 11:33:11 -07002629
Steve Anton8a006912017-12-04 15:25:56 -08002630 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002631}
2632
Steve Anton0f5400a2018-07-17 14:25:36 -07002633void PeerConnection::ProcessRemovalOfRemoteTrack(
2634 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2635 transceiver,
2636 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2637 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2638 RTC_DCHECK(transceiver->mid());
2639 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2640 << *transceiver->mid();
2641 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2642 transceiver->internal()->receiver_internal()->streams();
2643 // This will remove the remote track from the streams.
2644 transceiver->internal()->receiver_internal()->set_stream_ids({});
2645 remove_list->push_back(transceiver);
2646 // Remove any streams that no longer have tracks.
2647 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2648 // of streams, see if the stream was removed by checking if this was the
2649 // last receiver with that stream ID.
2650 for (auto stream : media_streams) {
2651 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2652 remote_streams_->RemoveStream(stream);
2653 removed_streams->push_back(stream);
2654 }
2655 }
2656}
2657
Steve Antondcc3c022017-12-22 16:02:54 -08002658RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2659 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002660 const SessionDescriptionInterface& new_session,
2661 const SessionDescriptionInterface* old_local_description,
2662 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002663 RTC_DCHECK(IsUnifiedPlan());
2664
Steve Anton7464fca2018-01-19 11:10:37 -08002665 const cricket::ContentGroup* bundle_group = nullptr;
2666 if (new_session.GetType() == SdpType::kOffer) {
2667 auto bundle_group_or_error =
2668 GetEarlyBundleGroup(*new_session.description());
2669 if (!bundle_group_or_error.ok()) {
2670 return bundle_group_or_error.MoveError();
2671 }
2672 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002673 }
Steve Antondcc3c022017-12-22 16:02:54 -08002674
Steve Antondcc3c022017-12-22 16:02:54 -08002675 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002676 for (size_t i = 0; i < new_contents.size(); ++i) {
2677 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002678 cricket::MediaType media_type = new_content.media_description()->type();
2679 seen_mids_.insert(new_content.name);
2680 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2681 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002682 const cricket::ContentInfo* old_local_content = nullptr;
2683 if (old_local_description &&
2684 i < old_local_description->description()->contents().size()) {
2685 old_local_content =
2686 &old_local_description->description()->contents()[i];
2687 }
2688 const cricket::ContentInfo* old_remote_content = nullptr;
2689 if (old_remote_description &&
2690 i < old_remote_description->description()->contents().size()) {
2691 old_remote_content =
2692 &old_remote_description->description()->contents()[i];
2693 }
Steve Antondcc3c022017-12-22 16:02:54 -08002694 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002695 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2696 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002697 if (!transceiver_or_error.ok()) {
2698 return transceiver_or_error.MoveError();
2699 }
2700 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002701 RTCError error =
2702 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2703 if (!error.ok()) {
2704 return error;
2705 }
2706 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002707 if (GetDataMid() && new_content.name != *GetDataMid()) {
2708 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002709 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2710 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002711 continue;
2712 }
2713 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2714 if (!error.ok()) {
2715 return error;
2716 }
Steve Antondcc3c022017-12-22 16:02:54 -08002717 } else {
2718 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2719 "Unknown section type.");
2720 }
2721 }
2722
2723 return RTCError::OK();
2724}
2725
2726RTCError PeerConnection::UpdateTransceiverChannel(
2727 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2728 transceiver,
2729 const cricket::ContentInfo& content,
2730 const cricket::ContentGroup* bundle_group) {
2731 RTC_DCHECK(IsUnifiedPlan());
2732 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002733 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002734 if (content.rejected) {
2735 if (channel) {
2736 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002737 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002738 }
2739 } else {
2740 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002741 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002742 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002743 } else {
Steve Anton69470252018-02-09 11:43:08 -08002744 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002745 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002746 }
2747 if (!channel) {
2748 LOG_AND_RETURN_ERROR(
2749 RTCErrorType::INTERNAL_ERROR,
2750 "Failed to create channel for mid=" + content.name);
2751 }
2752 transceiver->internal()->SetChannel(channel);
2753 }
2754 }
2755 return RTCError::OK();
2756}
2757
Steve Antonfa2260d2017-12-28 16:38:23 -08002758RTCError PeerConnection::UpdateDataChannel(
2759 cricket::ContentSource source,
2760 const cricket::ContentInfo& content,
2761 const cricket::ContentGroup* bundle_group) {
2762 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002763 // If data channels are disabled, ignore this media section. CreateAnswer
2764 // will take care of rejecting it.
2765 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002766 }
2767 if (content.rejected) {
2768 DestroyDataChannel();
2769 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002770 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002771 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002772 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2773 "Failed to create data channel.");
2774 }
2775 }
2776 if (source == cricket::CS_REMOTE) {
2777 const MediaContentDescription* data_desc = content.media_description();
2778 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2779 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2780 }
2781 }
2782 }
2783 return RTCError::OK();
2784}
2785
Steve Antondcc3c022017-12-22 16:02:54 -08002786RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2787PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002788 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002789 size_t mline_index,
2790 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002791 const ContentInfo* old_local_content,
2792 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002793 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002794 // If this is an offer then the m= section might be recycled. If the m=
2795 // section is being recycled (defined as: rejected in the current local or
2796 // remote description and not rejected in new description), dissociate the
2797 // currently associated RtpTransceiver by setting its mid property to null,
2798 // and discard the mapping between the transceiver and its m= section index.
2799 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2800 old_remote_content)) {
2801 // We want to dissociate the transceiver that has the rejected mid.
2802 const std::string& old_mid =
2803 (old_local_content && old_local_content->rejected)
2804 ? old_local_content->name
2805 : old_remote_content->name;
2806 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002807 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002808 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2809 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002810 old_transceiver->internal()->set_mid(absl::nullopt);
2811 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002812 }
2813 }
2814 const MediaContentDescription* media_desc = content.media_description();
2815 auto transceiver = GetAssociatedTransceiver(content.name);
2816 if (source == cricket::CS_LOCAL) {
2817 // Find the RtpTransceiver that corresponds to this m= section, using the
2818 // mapping between transceivers and m= section indices established when
2819 // creating the offer.
2820 if (!transceiver) {
2821 transceiver = GetTransceiverByMLineIndex(mline_index);
2822 }
2823 if (!transceiver) {
2824 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2825 "Unknown transceiver");
2826 }
2827 } else {
2828 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2829 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2830 // of the same type...
2831 if (!transceiver &&
2832 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2833 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2834 }
2835 // If no RtpTransceiver was found in the previous step, create one with a
2836 // recvonly direction.
2837 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002838 RTC_LOG(LS_INFO) << "Adding "
2839 << cricket::MediaTypeToString(media_desc->type())
2840 << " transceiver for MID=" << content.name
2841 << " at i=" << mline_index
2842 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002843 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002844 auto sender =
2845 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002846 std::string receiver_id;
2847 if (!media_desc->streams().empty()) {
2848 receiver_id = media_desc->streams()[0].id;
2849 } else {
2850 receiver_id = rtc::CreateRandomUuid();
2851 }
2852 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002853 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002854 transceiver->internal()->set_direction(
2855 RtpTransceiverDirection::kRecvOnly);
2856 }
2857 }
2858 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002859 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002860 LOG_AND_RETURN_ERROR(
2861 RTCErrorType::INVALID_PARAMETER,
2862 "Transceiver type does not match media description type.");
2863 }
2864 // Associate the found or created RtpTransceiver with the m= section by
2865 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2866 // section, and establish a mapping between the transceiver and the index of
2867 // the m= section.
2868 transceiver->internal()->set_mid(content.name);
2869 transceiver->internal()->set_mline_index(mline_index);
2870 return std::move(transceiver);
2871}
2872
2873rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2874PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2875 RTC_DCHECK(IsUnifiedPlan());
2876 for (auto transceiver : transceivers_) {
2877 if (transceiver->mid() == mid) {
2878 return transceiver;
2879 }
2880 }
2881 return nullptr;
2882}
2883
2884rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2885PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2886 RTC_DCHECK(IsUnifiedPlan());
2887 for (auto transceiver : transceivers_) {
2888 if (transceiver->internal()->mline_index() == mline_index) {
2889 return transceiver;
2890 }
2891 }
2892 return nullptr;
2893}
2894
2895rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2896PeerConnection::FindAvailableTransceiverToReceive(
2897 cricket::MediaType media_type) const {
2898 RTC_DCHECK(IsUnifiedPlan());
2899 // From JSEP section 5.10 (Applying a Remote Description):
2900 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2901 // the same type that were added to the PeerConnection by addTrack and are not
2902 // associated with any m= section and are not stopped, find the first such
2903 // RtpTransceiver.
2904 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002905 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002906 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2907 !transceiver->stopped()) {
2908 return transceiver;
2909 }
2910 }
2911 return nullptr;
2912}
2913
Steve Antoned10bd92017-12-05 10:52:59 -08002914const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2915 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2916 transceiver,
2917 const SessionDescriptionInterface* sdesc) const {
2918 RTC_DCHECK(transceiver);
2919 RTC_DCHECK(sdesc);
2920 if (IsUnifiedPlan()) {
2921 if (!transceiver->internal()->mid()) {
2922 // This transceiver is not associated with a media section yet.
2923 return nullptr;
2924 }
2925 return sdesc->description()->GetContentByName(
2926 *transceiver->internal()->mid());
2927 } else {
2928 // Plan B only allows at most one audio and one video section, so use the
2929 // first media section of that type.
2930 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002931 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002932 }
2933}
2934
deadbeef46c73892016-11-16 19:42:04 -08002935PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2936 return configuration_;
2937}
2938
deadbeef293e9262017-01-11 12:28:30 -08002939bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2940 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002941 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002942 if (IsClosed()) {
2943 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2944 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2945 }
2946
Qingsi Wanga2d60672018-04-11 16:57:45 -07002947 // According to JSEP, after setLocalDescription, changing the candidate pool
2948 // size is not allowed, and changing the set of ICE servers will not result
2949 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002950 if (local_description() && configuration.ice_candidate_pool_size !=
2951 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002952 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2953 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002954 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002955 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002956
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002957 if (local_description() &&
2958 configuration.use_media_transport != configuration_.use_media_transport) {
2959 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2960 "SetLocalDescription.";
2961 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2962 }
2963
2964 if (remote_description() &&
2965 configuration.use_media_transport != configuration_.use_media_transport) {
2966 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2967 "SetRemoteDescription.";
2968 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2969 }
2970
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002971 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002972 configuration.use_media_transport_for_data_channels !=
2973 configuration_.use_media_transport_for_data_channels) {
2974 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2975 "after calling SetLocalDescription.";
2976 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2977 }
2978
2979 if (remote_description() &&
2980 configuration.use_media_transport_for_data_channels !=
2981 configuration_.use_media_transport_for_data_channels) {
2982 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2983 "after calling SetRemoteDescription.";
2984 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2985 }
2986
2987 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002988 configuration.crypto_options != configuration_.crypto_options) {
2989 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2990 "SetLocalDescription.";
2991 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2992 }
2993
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08002994 if (configuration.use_media_transport_for_data_channels ||
2995 configuration.use_media_transport) {
2996 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
2997 << "Media transport requires MaxBundle policy.";
2998 }
2999
deadbeef293e9262017-01-11 12:28:30 -08003000 // The simplest (and most future-compatible) way to tell if the config was
3001 // modified in an invalid way is to copy each property we do support
3002 // modifying, then use operator==. There are far more properties we don't
3003 // support modifying than those we do, and more could be added.
3004 RTCConfiguration modified_config = configuration_;
3005 modified_config.servers = configuration.servers;
3006 modified_config.type = configuration.type;
3007 modified_config.ice_candidate_pool_size =
3008 configuration.ice_candidate_pool_size;
3009 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003010 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003011 modified_config.ice_check_interval_strong_connectivity =
3012 configuration.ice_check_interval_strong_connectivity;
3013 modified_config.ice_check_interval_weak_connectivity =
3014 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003015 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3016 modified_config.ice_unwritable_min_checks =
3017 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003018 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003019 modified_config.stun_candidate_keepalive_interval =
3020 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003021 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003022 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003023 modified_config.active_reset_srtp_params =
3024 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003025 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003026 modified_config.use_media_transport_for_data_channels =
3027 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003028 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003029 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003030 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3031 }
3032
Steve Anton038834f2017-07-14 15:59:59 -07003033 // Validate the modified configuration.
3034 RTCError validate_error = ValidateConfiguration(modified_config);
3035 if (!validate_error.ok()) {
3036 return SafeSetError(std::move(validate_error), error);
3037 }
3038
deadbeef293e9262017-01-11 12:28:30 -08003039 // Note that this isn't possible through chromium, since it's an unsigned
3040 // short in WebIDL.
3041 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003042 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003043 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3044 }
3045
3046 // Parse ICE servers before hopping to network thread.
3047 cricket::ServerAddresses stun_servers;
3048 std::vector<cricket::RelayServerConfig> turn_servers;
3049 RTCErrorType parse_error =
3050 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3051 if (parse_error != RTCErrorType::NONE) {
3052 return SafeSetError(parse_error, error);
3053 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003054 // Note if STUN or TURN servers were supplied.
3055 if (!stun_servers.empty()) {
3056 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3057 }
3058 if (!turn_servers.empty()) {
3059 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3060 }
deadbeef293e9262017-01-11 12:28:30 -08003061
3062 // In theory this shouldn't fail.
3063 if (!network_thread()->Invoke<bool>(
3064 RTC_FROM_HERE,
3065 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3066 stun_servers, turn_servers, modified_config.type,
3067 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003068 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003069 modified_config.turn_customizer,
3070 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003071 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003072 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3073 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003074
deadbeefd1a38b52016-12-10 13:15:33 -08003075 // As described in JSEP, calling setConfiguration with new ICE servers or
3076 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3077 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003078 if (modified_config.servers != configuration_.servers ||
3079 modified_config.type != configuration_.type ||
3080 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003081 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003082 }
skvladd1f5fda2017-02-03 16:54:05 -08003083
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003084 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003085 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003086 modified_config.use_media_transport ||
3087 modified_config.use_media_transport_for_data_channels
3088 ? factory_->media_transport_factory()
3089 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003090
Zhi Huangb57e1692018-06-12 11:41:11 -07003091 if (configuration_.active_reset_srtp_params !=
3092 modified_config.active_reset_srtp_params) {
3093 transport_controller_->SetActiveResetSrtpParams(
3094 modified_config.active_reset_srtp_params);
3095 }
3096
deadbeef293e9262017-01-11 12:28:30 -08003097 configuration_ = modified_config;
3098 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003099}
3100
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003101bool PeerConnection::AddIceCandidate(
3102 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003103 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003104 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003105 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003106 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003107 return false;
3108 }
Steve Antond25da372017-11-06 14:50:29 -08003109
3110 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003111 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003112 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003113 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003114 return false;
3115 }
3116
3117 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003118 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003119 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003120 return false;
3121 }
3122
3123 bool valid = false;
3124 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3125 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003126 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003127 return false;
3128 }
3129
3130 // Add this candidate to the remote session description.
3131 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003132 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003133 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003134 return false;
3135 }
3136
3137 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003138 bool result = UseCandidate(ice_candidate);
3139 if (result) {
3140 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3141 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3142 } else {
3143 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3144 }
3145 return result;
Steve Antond25da372017-11-06 14:50:29 -08003146 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003147 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003148 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003149 return true;
3150 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003151}
3152
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003153bool PeerConnection::RemoveIceCandidates(
3154 const std::vector<cricket::Candidate>& candidates) {
3155 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003156 if (IsClosed()) {
3157 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3158 return false;
3159 }
3160
Steve Antond25da372017-11-06 14:50:29 -08003161 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003162 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3163 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003164 return false;
3165 }
3166
3167 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003168 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003169 return false;
3170 }
3171
3172 size_t number_removed =
3173 mutable_remote_description()->RemoveCandidates(candidates);
3174 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003175 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003176 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003177 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003178 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003179 }
3180
3181 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003182 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3183 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003184 RTC_LOG(LS_ERROR)
3185 << "RemoveIceCandidates: Error when removing remote candidates: "
3186 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003187 }
3188 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003189}
3190
Niels Möller0c4f7be2018-05-07 14:01:37 +02003191RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003192 if (!worker_thread()->IsCurrent()) {
3193 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003194 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003195 }
3196
Niels Möller0c4f7be2018-05-07 14:01:37 +02003197 const bool has_min = bitrate.min_bitrate_bps.has_value();
3198 const bool has_start = bitrate.start_bitrate_bps.has_value();
3199 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003200 if (has_min && *bitrate.min_bitrate_bps < 0) {
3201 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3202 "min_bitrate_bps <= 0");
3203 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003204 if (has_start) {
3205 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003207 "start_bitrate_bps < min_bitrate_bps");
3208 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003209 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3210 "curent_bitrate_bps < 0");
3211 }
3212 }
3213 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003214 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003216 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003217 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3219 "max_bitrate_bps < min_bitrate_bps");
3220 } else if (*bitrate.max_bitrate_bps < 0) {
3221 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3222 "max_bitrate_bps < 0");
3223 }
3224 }
3225
zstein4b979802017-06-02 14:37:37 -07003226 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003227 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003228
3229 return RTCError::OK();
3230}
3231
Alex Narest78609d52017-10-20 10:37:47 +02003232void PeerConnection::SetBitrateAllocationStrategy(
3233 std::unique_ptr<rtc::BitrateAllocationStrategy>
3234 bitrate_allocation_strategy) {
3235 rtc::Thread* worker_thread = factory_->worker_thread();
3236 if (!worker_thread->IsCurrent()) {
3237 rtc::BitrateAllocationStrategy* strategy_raw =
3238 bitrate_allocation_strategy.release();
3239 auto functor = [this, strategy_raw]() {
3240 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003241 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003242 };
3243 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3244 return;
3245 }
3246 RTC_DCHECK(call_.get());
3247 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3248}
3249
henrika5f6bf242017-11-01 11:06:56 +01003250void PeerConnection::SetAudioPlayout(bool playout) {
3251 if (!worker_thread()->IsCurrent()) {
3252 worker_thread()->Invoke<void>(
3253 RTC_FROM_HERE,
3254 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3255 return;
3256 }
3257 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003258 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003259 audio_state->SetPlayout(playout);
3260}
3261
3262void PeerConnection::SetAudioRecording(bool recording) {
3263 if (!worker_thread()->IsCurrent()) {
3264 worker_thread()->Invoke<void>(
3265 RTC_FROM_HERE,
3266 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3267 return;
3268 }
3269 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003270 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003271 audio_state->SetRecording(recording);
3272}
3273
Steve Anton8c0f7a72017-10-03 10:03:10 -07003274std::unique_ptr<rtc::SSLCertificate>
3275PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003276 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3277 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003278 return nullptr;
3279 }
Steve Antonf25303e2018-10-16 15:23:31 -07003280 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003281}
3282
Zhi Huang70b820f2018-01-27 14:16:15 -08003283std::unique_ptr<rtc::SSLCertChain>
3284PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003285 auto audio_transceiver = GetFirstAudioTransceiver();
3286 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003287 return nullptr;
3288 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003289 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003290 audio_transceiver->internal()->channel()->transport_name());
3291}
3292
3293rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3294PeerConnection::GetFirstAudioTransceiver() const {
3295 for (auto transceiver : transceivers_) {
3296 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3297 return transceiver;
3298 }
3299 }
3300 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003301}
3302
ivoc14d5dbe2016-07-04 07:06:55 -07003303bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3304 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003305 // TODO(eladalon): It would be better to not allow negative values into PC.
3306 const size_t max_size = (max_size_bytes < 0)
3307 ? RtcEventLog::kUnlimitedOutput
3308 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003309 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3310 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3311 output_period_ms = 5000;
3312 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003313 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003314 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003315 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003316}
3317
Bjorn Tereliusde939432017-11-20 17:38:14 +01003318bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3319 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003320 // TODO(eladalon): In C++14, this can be done with a lambda.
3321 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003322 bool operator()() {
3323 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3324 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003325 PeerConnection* const pc;
3326 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003327 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003328 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003329 return worker_thread()->Invoke<bool>(
3330 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003331}
3332
3333void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003334 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003335 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3336}
3337
Harald Alvestrandad88c882018-11-28 16:47:46 +01003338rtc::scoped_refptr<DtlsTransportInterface>
3339PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3340 return transport_controller_->LookupDtlsTransportByMid(mid);
3341}
3342
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003343const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003344 return pending_local_description_ ? pending_local_description_.get()
3345 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003346}
3347
3348const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003349 return pending_remote_description_ ? pending_remote_description_.get()
3350 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003351}
3352
deadbeeffe4a8a42016-12-20 17:56:17 -08003353const SessionDescriptionInterface* PeerConnection::current_local_description()
3354 const {
Steve Anton75737c02017-11-06 10:37:17 -08003355 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003356}
3357
3358const SessionDescriptionInterface* PeerConnection::current_remote_description()
3359 const {
Steve Anton75737c02017-11-06 10:37:17 -08003360 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003361}
3362
3363const SessionDescriptionInterface* PeerConnection::pending_local_description()
3364 const {
Steve Anton75737c02017-11-06 10:37:17 -08003365 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003366}
3367
3368const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3369 const {
Steve Anton75737c02017-11-06 10:37:17 -08003370 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003371}
3372
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003373void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003374 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375 // Update stats here so that we have the most recent stats for tracks and
3376 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003377 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003378
Steve Anton75737c02017-11-06 10:37:17 -08003379 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003380 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003381
Steve Anton8af21862017-12-15 11:20:13 -08003382 for (auto transceiver : transceivers_) {
3383 transceiver->Stop();
3384 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003385
3386 // Ensure that all asynchronous stats requests are completed before destroying
3387 // the transport controller below.
3388 if (stats_collector_) {
3389 stats_collector_->WaitForPendingRequest();
3390 }
3391
3392 // Don't destroy BaseChannels until after stats has been cleaned up so that
3393 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003394 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003395
Qingsi Wang93a84392018-01-30 17:13:09 -08003396 // The event log is used in the transport controller, which must be outlived
3397 // by the former. CreateOffer by the peer connection is implemented
3398 // asynchronously and if the peer connection is closed without resetting the
3399 // WebRTC session description factory, the session description factory would
3400 // call the transport controller.
3401 webrtc_session_desc_factory_.reset();
3402 transport_controller_.reset();
3403
deadbeef42a42632017-03-10 15:18:00 -08003404 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003405 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3406 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003407
Steve Anton978b8762017-09-29 12:15:02 -07003408 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003409 call_.reset();
3410 // The event log must outlive call (and any other object that uses it).
3411 event_log_.reset();
3412 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003413 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003414 // The .h file says that observer can be discarded after close() returns.
3415 // Make sure this is true.
3416 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003417}
3418
Steve Antonad182762018-09-05 20:22:40 +00003419void PeerConnection::OnMessage(rtc::Message* msg) {
3420 switch (msg->message_id) {
3421 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3422 SetSessionDescriptionMsg* param =
3423 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3424 param->observer->OnSuccess();
3425 delete param;
3426 break;
3427 }
3428 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3429 SetSessionDescriptionMsg* param =
3430 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3431 param->observer->OnFailure(std::move(param->error));
3432 delete param;
3433 break;
3434 }
3435 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3436 CreateSessionDescriptionMsg* param =
3437 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3438 param->observer->OnFailure(std::move(param->error));
3439 delete param;
3440 break;
3441 }
3442 case MSG_GETSTATS: {
3443 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3444 StatsReports reports;
3445 stats_->GetStats(param->track, &reports);
3446 param->observer->OnComplete(reports);
3447 delete param;
3448 break;
3449 }
3450 case MSG_FREE_DATACHANNELS: {
3451 sctp_data_channels_to_free_.clear();
3452 break;
3453 }
3454 case MSG_REPORT_USAGE_PATTERN: {
3455 ReportUsagePattern();
3456 break;
3457 }
3458 default:
3459 RTC_NOTREACHED() << "Not implemented";
3460 break;
3461 }
3462}
3463
Steve Antonafb0bb72018-02-20 11:35:37 -08003464cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3465 RTC_DCHECK(!IsUnifiedPlan());
3466 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3467 GetAudioTransceiver()->internal()->channel());
3468 if (voice_channel) {
3469 return voice_channel->media_channel();
3470 } else {
3471 return nullptr;
3472 }
3473}
3474
3475cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3476 RTC_DCHECK(!IsUnifiedPlan());
3477 auto* video_channel = static_cast<cricket::VideoChannel*>(
3478 GetVideoTransceiver()->internal()->channel());
3479 if (video_channel) {
3480 return video_channel->media_channel();
3481 } else {
3482 return nullptr;
3483 }
3484}
3485
Steve Anton4171afb2017-11-20 10:20:22 -08003486void PeerConnection::CreateAudioReceiver(
3487 MediaStreamInterface* stream,
3488 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003489 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3490 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003491 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3492 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003493 auto* audio_receiver = new AudioRtpReceiver(
3494 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003495 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003496 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3497 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3498 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003499 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003500 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003501 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003502}
3503
Steve Anton4171afb2017-11-20 10:20:22 -08003504void PeerConnection::CreateVideoReceiver(
3505 MediaStreamInterface* stream,
3506 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003507 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3508 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003509 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3510 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003511 auto* video_receiver = new VideoRtpReceiver(
3512 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003513 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003514 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3515 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3516 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003517 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003518 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003519 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520}
3521
deadbeef70ab1a12015-09-28 16:53:55 -07003522// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3523// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003524rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003525 const RtpSenderInfo& remote_sender_info) {
3526 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3527 if (!receiver) {
3528 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3529 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003530 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003531 }
Steve Anton4171afb2017-11-20 10:20:22 -08003532 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3533 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3534 } else {
3535 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3536 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003537 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003538}
3539
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003540void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3541 MediaStreamInterface* stream) {
3542 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003543 RTC_DCHECK(track);
3544 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003545 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003546 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003547 // We already have a sender for this track, so just change the stream_id
3548 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003549 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003550 return;
3551 }
3552
3553 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003554 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003555 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003556 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003557 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003558 // If the sender has already been configured in SDP, we call SetSsrc,
3559 // which will connect the sender to the underlying transport. This can
3560 // occur if a local session description that contains the ID of the sender
3561 // is set before AddStream is called. It can also occur if the local
3562 // session description is not changed and RemoveStream is called, and
3563 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003564 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003565 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003566 if (sender_info) {
3567 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003568 }
3569}
3570
3571// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3572// indefinitely, when we have unified plan SDP.
3573void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3574 MediaStreamInterface* stream) {
3575 RTC_DCHECK(!IsClosed());
3576 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003577 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003578 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3579 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003580 return;
3581 }
Steve Anton4171afb2017-11-20 10:20:22 -08003582 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003583}
3584
3585void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3586 MediaStreamInterface* stream) {
3587 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003588 RTC_DCHECK(track);
3589 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003590 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003591 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003592 // We already have a sender for this track, so just change the stream_id
3593 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003594 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003595 return;
3596 }
3597
3598 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003599 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003600 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003601 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003602 GetVideoTransceiver()->internal()->AddSender(new_sender);
3603 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003604 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003605 if (sender_info) {
3606 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003607 }
3608}
3609
3610void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3611 MediaStreamInterface* stream) {
3612 RTC_DCHECK(!IsClosed());
3613 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003614 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003615 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3616 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003617 return;
3618 }
Steve Anton4171afb2017-11-20 10:20:22 -08003619 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003620}
3621
Steve Antonba818672017-11-06 10:21:57 -08003622void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003623 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003624 if (ice_connection_state_ == new_state) {
3625 return;
3626 }
3627
deadbeefcbecd352015-09-23 11:50:27 -07003628 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003629 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003630 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003631 return;
3632 }
Steve Antonba818672017-11-06 10:21:57 -08003633
Mirko Bonadei675513b2017-11-09 11:09:25 +01003634 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3635 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003636 RTC_DCHECK(ice_connection_state_ !=
3637 PeerConnectionInterface::kIceConnectionClosed);
3638
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003639 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003640 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003641}
3642
Alex Loiko9289eda2018-11-23 16:18:59 +00003643void PeerConnection::SetStandardizedIceConnectionState(
3644 PeerConnectionInterface::IceConnectionState new_state) {
3645 RTC_DCHECK(signaling_thread()->IsCurrent());
3646 if (standardized_ice_connection_state_ == new_state)
3647 return;
3648 if (IsClosed())
3649 return;
3650 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003651 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003652}
3653
Jonas Olsson635474e2018-10-18 15:58:17 +02003654void PeerConnection::SetConnectionState(
3655 PeerConnectionInterface::PeerConnectionState new_state) {
3656 RTC_DCHECK(signaling_thread()->IsCurrent());
3657 if (connection_state_ == new_state)
3658 return;
3659 if (IsClosed())
3660 return;
3661 connection_state_ = new_state;
3662 Observer()->OnConnectionChange(new_state);
3663}
3664
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003665void PeerConnection::OnIceGatheringChange(
3666 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003667 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003668 if (IsClosed()) {
3669 return;
3670 }
3671 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003672 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003673}
3674
jbauch81bf7b02017-03-25 08:31:12 -07003675void PeerConnection::OnIceCandidate(
3676 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003677 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003678 if (IsClosed()) {
3679 return;
3680 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003681 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003682 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3683 candidate->candidate().address().IsPrivateIP()) {
3684 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3685 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003686 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003687}
3688
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003689void PeerConnection::OnIceCandidatesRemoved(
3690 const std::vector<cricket::Candidate>& candidates) {
3691 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003692 if (IsClosed()) {
3693 return;
3694 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003695 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003696}
3697
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003698void PeerConnection::ChangeSignalingState(
3699 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003700 RTC_DCHECK(signaling_thread()->IsCurrent());
3701 if (signaling_state_ == signaling_state) {
3702 return;
3703 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003704 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3705 << GetSignalingStateString(signaling_state_)
3706 << " New state: "
3707 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003708 signaling_state_ = signaling_state;
3709 if (signaling_state == kClosed) {
3710 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003711 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003712 standardized_ice_connection_state_ =
3713 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003714 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3715 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003716 if (ice_gathering_state_ != kIceGatheringComplete) {
3717 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003718 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003719 }
3720 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003721 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003722}
3723
deadbeefeb459812015-12-15 19:24:43 -08003724void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3725 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003726 if (IsClosed()) {
3727 return;
3728 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003729 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003730 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003731}
3732
deadbeefeb459812015-12-15 19:24:43 -08003733void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3734 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003735 if (IsClosed()) {
3736 return;
3737 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003738 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003739 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003740}
3741
3742void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3743 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003744 if (IsClosed()) {
3745 return;
3746 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003747 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003748 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003749}
3750
3751void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3752 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003753 if (IsClosed()) {
3754 return;
3755 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003756 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003757 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003758}
3759
Henrik Boström31638672017-11-23 17:48:32 +01003760void PeerConnection::PostSetSessionDescriptionSuccess(
3761 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003762 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3763 signaling_thread()->Post(RTC_FROM_HERE, this,
3764 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003765}
3766
deadbeefab9b2d12015-10-14 11:33:11 -07003767void PeerConnection::PostSetSessionDescriptionFailure(
3768 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003769 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003770 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003771 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3772 msg->error = std::move(error);
3773 signaling_thread()->Post(RTC_FROM_HERE, this,
3774 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003775}
3776
3777void PeerConnection::PostCreateSessionDescriptionFailure(
3778 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003779 RTCError error) {
3780 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003781 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3782 msg->error = std::move(error);
3783 signaling_thread()->Post(RTC_FROM_HERE, this,
3784 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003785}
3786
zhihuang1c378ed2017-08-17 14:10:50 -07003787void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003788 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003789 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003790 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003791
Steve Antondcc3c022017-12-22 16:02:54 -08003792 if (IsUnifiedPlan()) {
3793 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3794 } else {
3795 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3796 }
3797
Steve Antonfa2260d2017-12-28 16:38:23 -08003798 // Intentionally unset the data channel type for RTP data channel with the
3799 // second condition. Otherwise the RTP data channels would be successfully
3800 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3801 // when building with chromium. We want to leave RTP data channels broken, so
3802 // people won't try to use them.
3803 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3804 session_options->data_channel_type = data_channel_type();
3805 }
3806
Steve Antondcc3c022017-12-22 16:02:54 -08003807 // Apply ICE restart flag and renomination flag.
3808 for (auto& options : session_options->media_description_options) {
3809 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3810 options.transport_options.enable_ice_renomination =
3811 configuration_.enable_ice_renomination;
3812 }
3813
3814 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003815 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003816 session_options->pooled_ice_credentials =
3817 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3818 RTC_FROM_HERE,
3819 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3820 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003821 session_options->offer_extmap_allow_mixed =
3822 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003823}
3824
3825void PeerConnection::GetOptionsForPlanBOffer(
3826 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3827 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003828 // Figure out transceiver directional preferences.
3829 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3830 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3831
3832 // By default, generate sendrecv/recvonly m= sections.
3833 bool recv_audio = true;
3834 bool recv_video = true;
3835
3836 // By default, only offer a new m= section if we have media to send with it.
3837 bool offer_new_audio_description = send_audio;
3838 bool offer_new_video_description = send_video;
3839 bool offer_new_data_description = HasDataChannels();
3840
3841 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003842 if (offer_answer_options.offer_to_receive_audio !=
3843 RTCOfferAnswerOptions::kUndefined) {
3844 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003845 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003846 offer_new_audio_description ||
3847 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003848 }
Steve Antondcc3c022017-12-22 16:02:54 -08003849 if (offer_answer_options.offer_to_receive_video !=
3850 RTCOfferAnswerOptions::kUndefined) {
3851 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003852 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003853 offer_new_video_description ||
3854 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003855 }
3856
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003857 absl::optional<size_t> audio_index;
3858 absl::optional<size_t> video_index;
3859 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003860 // If a current description exists, generate m= sections in the same order,
3861 // using the first audio/video/data section that appears and rejecting
3862 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003863 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003864 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003865 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003866 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3867 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3868 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003869 }
3870
zhihuang1c378ed2017-08-17 14:10:50 -07003871 // Add audio/video/data m= sections to the end if needed.
3872 if (!audio_index && offer_new_audio_description) {
3873 session_options->media_description_options.push_back(
3874 cricket::MediaDescriptionOptions(
3875 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003876 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3877 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003878 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003879 }
zhihuang1c378ed2017-08-17 14:10:50 -07003880 if (!video_index && offer_new_video_description) {
3881 session_options->media_description_options.push_back(
3882 cricket::MediaDescriptionOptions(
3883 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003884 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3885 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003886 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003887 }
zhihuang1c378ed2017-08-17 14:10:50 -07003888 if (!data_index && offer_new_data_description) {
3889 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003890 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003891 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003892 }
3893
3894 cricket::MediaDescriptionOptions* audio_media_description_options =
3895 !audio_index ? nullptr
3896 : &session_options->media_description_options[*audio_index];
3897 cricket::MediaDescriptionOptions* video_media_description_options =
3898 !video_index ? nullptr
3899 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003900
Steve Anton4171afb2017-11-20 10:20:22 -08003901 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003902 video_media_description_options,
3903 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003904}
3905
3906// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3907// and return a reference to it.
3908// Generated MIDs should be no more than 3 bytes long to take up less space in
3909// the RTP packet.
3910static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3911 RTC_DCHECK(used_mids);
3912 // We're boring: just generate MIDs 0, 1, 2, ...
3913 size_t i = 0;
3914 std::set<std::string>::iterator it;
3915 bool inserted;
3916 do {
3917 std::string mid = rtc::ToString(i++);
3918 auto insert_result = used_mids->insert(mid);
3919 it = insert_result.first;
3920 inserted = insert_result.second;
3921 } while (!inserted);
3922 return *it;
3923}
3924
3925static cricket::MediaDescriptionOptions
3926GetMediaDescriptionOptionsForTransceiver(
3927 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3928 transceiver,
3929 const std::string& mid) {
3930 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003931 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003932 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003933 // This behavior is specified in JSEP. The gist is that:
3934 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3935 // sendrecv.
3936 // 2. If the MSID is included, then it must be included in any subsequent
3937 // offer/answer exactly the same until the RtpTransceiver is stopped.
3938 if (!transceiver->stopped() &&
3939 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3940 transceiver->internal()->has_ever_been_used_to_send())) {
3941 cricket::SenderOptions sender_options;
3942 sender_options.track_id = transceiver->sender()->id();
3943 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003944 int num_send_encoding_layers =
3945 transceiver->sender()->init_send_encodings().size();
3946 sender_options.num_sim_layers =
3947 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003948 media_description_options.sender_options.push_back(sender_options);
3949 }
Steve Antondcc3c022017-12-22 16:02:54 -08003950 return media_description_options;
3951}
3952
Steve Anton5c72e712018-12-10 14:25:30 -08003953// Returns the ContentInfo at mline index |i|, or null if none exists.
3954static const ContentInfo* GetContentByIndex(
3955 const SessionDescriptionInterface* sdesc,
3956 size_t i) {
3957 if (!sdesc) {
3958 return nullptr;
3959 }
3960 const ContentInfos& contents = sdesc->description()->contents();
3961 return (i < contents.size() ? &contents[i] : nullptr);
3962}
3963
Steve Antondcc3c022017-12-22 16:02:54 -08003964void PeerConnection::GetOptionsForUnifiedPlanOffer(
3965 const RTCOfferAnswerOptions& offer_answer_options,
3966 cricket::MediaSessionOptions* session_options) {
3967 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3968 // Offers) and 5.2.2 (Subsequent Offers).
3969 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3970 const ContentInfos& local_contents =
3971 (local_description() ? local_description()->description()->contents()
3972 : ContentInfos());
3973 const ContentInfos& remote_contents =
3974 (remote_description() ? remote_description()->description()->contents()
3975 : ContentInfos());
3976 // The mline indices that can be recycled. New transceivers should reuse these
3977 // slots first.
3978 std::queue<size_t> recycleable_mline_indices;
3979 // Track the MIDs used in previous offer/answer exchanges and the current
3980 // offer so that new, unique MIDs are generated.
3981 std::set<std::string> used_mids = seen_mids_;
3982 // First, go through each media section that exists in either the local or
3983 // remote description and generate a media section in this offer for the
3984 // associated transceiver. If a media section can be recycled, generate a
3985 // default, rejected media section here that can be later overwritten.
3986 for (size_t i = 0;
3987 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3988 // Either |local_content| or |remote_content| is non-null.
3989 const ContentInfo* local_content =
3990 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08003991 const ContentInfo* current_local_content =
3992 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08003993 const ContentInfo* remote_content =
3994 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08003995 const ContentInfo* current_remote_content =
3996 GetContentByIndex(current_remote_description(), i);
3997 bool had_been_rejected =
3998 (current_local_content && current_local_content->rejected) ||
3999 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004000 const std::string& mid =
4001 (local_content ? local_content->name : remote_content->name);
4002 cricket::MediaType media_type =
4003 (local_content ? local_content->media_description()->type()
4004 : remote_content->media_description()->type());
4005 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4006 media_type == cricket::MEDIA_TYPE_VIDEO) {
4007 auto transceiver = GetAssociatedTransceiver(mid);
4008 RTC_CHECK(transceiver);
4009 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004010 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004011 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004012 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004013 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4014 RtpTransceiverDirection::kInactive,
4015 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004016 recycleable_mline_indices.push(i);
4017 } else {
4018 session_options->media_description_options.push_back(
4019 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4020 // CreateOffer shouldn't really cause any state changes in
4021 // PeerConnection, but we need a way to match new transceivers to new
4022 // media sections in SetLocalDescription and JSEP specifies this is done
4023 // by recording the index of the media section generated for the
4024 // transceiver in the offer.
4025 transceiver->internal()->set_mline_index(i);
4026 }
4027 } else {
4028 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004029 RTC_CHECK(GetDataMid());
4030 if (had_been_rejected || mid != *GetDataMid()) {
4031 session_options->media_description_options.push_back(
4032 GetMediaDescriptionOptionsForRejectedData(mid));
4033 } else {
4034 session_options->media_description_options.push_back(
4035 GetMediaDescriptionOptionsForActiveData(mid));
4036 }
Steve Antondcc3c022017-12-22 16:02:54 -08004037 }
4038 }
4039 // Next, look for transceivers that are newly added (that is, are not stopped
4040 // and not associated). Reuse media sections marked as recyclable first,
4041 // otherwise append to the end of the offer. New media sections should be
4042 // added in the order they were added to the PeerConnection.
4043 for (auto transceiver : transceivers_) {
4044 if (transceiver->mid() || transceiver->stopped()) {
4045 continue;
4046 }
4047 size_t mline_index;
4048 if (!recycleable_mline_indices.empty()) {
4049 mline_index = recycleable_mline_indices.front();
4050 recycleable_mline_indices.pop();
4051 session_options->media_description_options[mline_index] =
4052 GetMediaDescriptionOptionsForTransceiver(transceiver,
4053 AllocateMid(&used_mids));
4054 } else {
4055 mline_index = session_options->media_description_options.size();
4056 session_options->media_description_options.push_back(
4057 GetMediaDescriptionOptionsForTransceiver(transceiver,
4058 AllocateMid(&used_mids)));
4059 }
4060 // See comment above for why CreateOffer changes the transceiver's state.
4061 transceiver->internal()->set_mline_index(mline_index);
4062 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004063 // Lastly, add a m-section if we have local data channels and an m section
4064 // does not already exist.
4065 if (!GetDataMid() && HasDataChannels()) {
4066 session_options->media_description_options.push_back(
4067 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4068 }
Steve Antondcc3c022017-12-22 16:02:54 -08004069}
4070
4071void PeerConnection::GetOptionsForAnswer(
4072 const RTCOfferAnswerOptions& offer_answer_options,
4073 cricket::MediaSessionOptions* session_options) {
4074 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4075
4076 if (IsUnifiedPlan()) {
4077 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4078 } else {
4079 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4080 }
4081
Steve Antonfa2260d2017-12-28 16:38:23 -08004082 // Intentionally unset the data channel type for RTP data channel. Otherwise
4083 // the RTP data channels would be successfully negotiated by default and the
4084 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4085 // We want to leave RTP data channels broken, so people won't try to use them.
4086 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4087 session_options->data_channel_type = data_channel_type();
4088 }
4089
Steve Antondcc3c022017-12-22 16:02:54 -08004090 // Apply ICE renomination flag.
4091 for (auto& options : session_options->media_description_options) {
4092 options.transport_options.enable_ice_renomination =
4093 configuration_.enable_ice_renomination;
4094 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004095
4096 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004097 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004098 session_options->pooled_ice_credentials =
4099 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4100 RTC_FROM_HERE,
4101 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4102 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004103}
4104
Steve Antondcc3c022017-12-22 16:02:54 -08004105void PeerConnection::GetOptionsForPlanBAnswer(
4106 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004107 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004108 // Figure out transceiver directional preferences.
4109 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4110 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4111
4112 // By default, generate sendrecv/recvonly m= sections. The direction is also
4113 // restricted by the direction in the offer.
4114 bool recv_audio = true;
4115 bool recv_video = true;
4116
4117 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004118 if (offer_answer_options.offer_to_receive_audio !=
4119 RTCOfferAnswerOptions::kUndefined) {
4120 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004121 }
Steve Antondcc3c022017-12-22 16:02:54 -08004122 if (offer_answer_options.offer_to_receive_video !=
4123 RTCOfferAnswerOptions::kUndefined) {
4124 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004125 }
4126
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004127 absl::optional<size_t> audio_index;
4128 absl::optional<size_t> video_index;
4129 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004130
4131 // Generate m= sections that match those in the offer.
4132 // Note that mediasession.cc will handle intersection our preferred
4133 // direction with the offered direction.
4134 GenerateMediaDescriptionOptions(
4135 remote_description(),
4136 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4137 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4138 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004139
4140 cricket::MediaDescriptionOptions* audio_media_description_options =
4141 !audio_index ? nullptr
4142 : &session_options->media_description_options[*audio_index];
4143 cricket::MediaDescriptionOptions* video_media_description_options =
4144 !video_index ? nullptr
4145 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004146
Steve Anton4171afb2017-11-20 10:20:22 -08004147 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004148 video_media_description_options,
4149 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004150}
zhihuangaf388472016-11-02 16:49:48 -07004151
Steve Antondcc3c022017-12-22 16:02:54 -08004152void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4153 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4154 cricket::MediaSessionOptions* session_options) {
4155 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4156 // Answers) and 5.3.2 (Subsequent Answers).
4157 RTC_DCHECK(remote_description());
4158 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4159 for (const ContentInfo& content :
4160 remote_description()->description()->contents()) {
4161 cricket::MediaType media_type = content.media_description()->type();
4162 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4163 media_type == cricket::MEDIA_TYPE_VIDEO) {
4164 auto transceiver = GetAssociatedTransceiver(content.name);
4165 RTC_CHECK(transceiver);
4166 session_options->media_description_options.push_back(
4167 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4168 } else {
4169 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004170 // Reject all data sections if data channels are disabled.
4171 // Reject a data section if it has already been rejected.
4172 // Reject all data sections except for the first one.
4173 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4174 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004175 session_options->media_description_options.push_back(
4176 GetMediaDescriptionOptionsForRejectedData(content.name));
4177 } else {
4178 session_options->media_description_options.push_back(
4179 GetMediaDescriptionOptionsForActiveData(content.name));
4180 }
Steve Antondcc3c022017-12-22 16:02:54 -08004181 }
4182 }
htaa2a49d92016-03-04 02:51:39 -08004183}
4184
zhihuang1c378ed2017-08-17 14:10:50 -07004185void PeerConnection::GenerateMediaDescriptionOptions(
4186 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004187 RtpTransceiverDirection audio_direction,
4188 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004189 absl::optional<size_t>* audio_index,
4190 absl::optional<size_t>* video_index,
4191 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004192 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004193 for (const cricket::ContentInfo& content :
4194 session_desc->description()->contents()) {
4195 if (IsAudioContent(&content)) {
4196 // If we already have an audio m= section, reject this extra one.
4197 if (*audio_index) {
4198 session_options->media_description_options.push_back(
4199 cricket::MediaDescriptionOptions(
4200 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004201 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004202 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004203 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004204 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004205 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4206 content.name, audio_direction,
4207 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004208 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004209 }
4210 } else if (IsVideoContent(&content)) {
4211 // If we already have an video m= section, reject this extra one.
4212 if (*video_index) {
4213 session_options->media_description_options.push_back(
4214 cricket::MediaDescriptionOptions(
4215 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004216 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004217 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004218 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004219 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004220 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4221 content.name, video_direction,
4222 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004223 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004224 }
4225 } else {
4226 RTC_DCHECK(IsDataContent(&content));
4227 // If we already have an data m= section, reject this extra one.
4228 if (*data_index) {
4229 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004230 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004231 } else {
4232 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004233 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004234 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004235 }
4236 }
htaa2a49d92016-03-04 02:51:39 -08004237 }
deadbeefab9b2d12015-10-14 11:33:11 -07004238}
4239
Steve Antonfa2260d2017-12-28 16:38:23 -08004240cricket::MediaDescriptionOptions
4241PeerConnection::GetMediaDescriptionOptionsForActiveData(
4242 const std::string& mid) const {
4243 // Direction for data sections is meaningless, but legacy endpoints might
4244 // expect sendrecv.
4245 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4246 RtpTransceiverDirection::kSendRecv,
4247 /*stopped=*/false);
4248 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4249 return options;
4250}
4251
4252cricket::MediaDescriptionOptions
4253PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4254 const std::string& mid) const {
4255 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4256 RtpTransceiverDirection::kInactive,
4257 /*stopped=*/true);
4258 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4259 return options;
4260}
4261
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004262absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004263 switch (data_channel_type_) {
4264 case cricket::DCT_RTP:
4265 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004266 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004267 }
4268 return rtp_data_channel_->content_name();
4269 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004270 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004271 case cricket::DCT_MEDIA_TRANSPORT:
4272 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004273 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004274 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004275 }
4276}
4277
Steve Anton4171afb2017-11-20 10:20:22 -08004278void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4279 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4280 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004281 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004282}
4283
Steve Anton4171afb2017-11-20 10:20:22 -08004284void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004285 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004286 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004287 cricket::MediaType media_type,
4288 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004289 RTC_DCHECK(!IsUnifiedPlan());
4290
Steve Anton4171afb2017-11-20 10:20:22 -08004291 std::vector<RtpSenderInfo>* current_senders =
4292 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004293
Steve Anton4171afb2017-11-20 10:20:22 -08004294 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004295 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004296 for (auto sender_it = current_senders->begin();
4297 sender_it != current_senders->end();
4298 /* incremented manually */) {
4299 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004300 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004301 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004302 std::string params_stream_id;
4303 if (params) {
4304 params_stream_id =
4305 (!params->first_stream_id().empty() ? params->first_stream_id()
4306 : kDefaultStreamId);
4307 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004308 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004309 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004310 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004311 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004312 sender_exists) {
4313 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004314 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004315 OnRemoteSenderRemoved(info, media_type);
4316 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004317 }
4318 }
4319
Steve Anton4171afb2017-11-20 10:20:22 -08004320 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004321 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004322 if (!params.has_ssrcs()) {
4323 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4324 // sender, this means it is coming from a Unified Plan endpoint,so we just
4325 // create a default.
4326 default_sender_needed = true;
4327 break;
4328 }
4329
Seth Hampson845e8782018-03-02 11:34:10 -08004330 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004331 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004332 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4333 // not supported in Plan B, we just take the first here and create the
4334 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004335 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004336 (!params.first_stream_id().empty() ? params.first_stream_id()
4337 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004338 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004339 uint32_t ssrc = params.first_ssrc();
4340
4341 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004342 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004343 if (!stream) {
4344 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004345 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004346 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004347 remote_streams_->AddStream(stream);
4348 new_streams->AddStream(stream);
4349 }
4350
Steve Anton4171afb2017-11-20 10:20:22 -08004351 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004352 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004353 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004354 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004355 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004356 }
4357 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004358
Steve Anton4171afb2017-11-20 10:20:22 -08004359 // Add default sender if necessary.
4360 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004361 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004362 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004363 if (!default_stream) {
4364 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004365 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004366 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004367 remote_streams_->AddStream(default_stream);
4368 new_streams->AddStream(default_stream);
4369 }
Steve Anton4171afb2017-11-20 10:20:22 -08004370 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4371 ? kDefaultAudioSenderId
4372 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004373 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004374 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004375 if (!default_sender_info) {
4376 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004377 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004378 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004379 }
4380 }
deadbeefab9b2d12015-10-14 11:33:11 -07004381}
4382
Steve Anton4171afb2017-11-20 10:20:22 -08004383void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4384 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004385 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4386 << " receiver for track_id=" << sender_info.sender_id
4387 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004388
Steve Anton3d954a62018-04-02 11:27:23 -07004389 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004390 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004391 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004392 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004393 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004394 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004395 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004396 }
4397}
4398
Steve Anton4171afb2017-11-20 10:20:22 -08004399void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4400 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004401 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4402 << " receiver for track_id=" << sender_info.sender_id
4403 << " and stream_id=" << sender_info.stream_id;
4404
Seth Hampson845e8782018-03-02 11:34:10 -08004405 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004406
Henrik Boström933d8b02017-10-10 10:05:16 -07004407 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004408 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004409 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4410 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004411 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004412 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004413 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004414 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004415 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004416 }
4417 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004418 // Stopping or destroying a VideoRtpReceiver will end the
4419 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004420 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004421 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004422 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004423 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004424 // There's no guarantee the track is still available, e.g. the track may
4425 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004426 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004427 }
4428 } else {
nisseede5da42017-01-12 05:15:36 -08004429 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004430 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004431 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004432 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004433 }
deadbeefab9b2d12015-10-14 11:33:11 -07004434}
4435
4436void PeerConnection::UpdateEndedRemoteMediaStreams() {
4437 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4438 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4439 MediaStreamInterface* stream = remote_streams_->at(i);
4440 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4441 streams_to_remove.push_back(stream);
4442 }
4443 }
4444
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004445 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004446 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004447 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004448 }
4449}
4450
Steve Anton4171afb2017-11-20 10:20:22 -08004451void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004452 const std::vector<cricket::StreamParams>& streams,
4453 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004454 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004455
Seth Hampson845e8782018-03-02 11:34:10 -08004456 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004457 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004458 for (auto sender_it = current_senders->begin();
4459 sender_it != current_senders->end();
4460 /* incremented manually */) {
4461 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004462 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004463 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4464 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004465 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004466 OnLocalSenderRemoved(info, media_type);
4467 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004468 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004469 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004470 }
4471 }
4472
Steve Anton4171afb2017-11-20 10:20:22 -08004473 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004474 for (const cricket::StreamParams& params : streams) {
4475 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004476 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004477 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004478 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004479 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004480 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004481 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004482 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004483 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004484 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004485 }
4486 }
4487}
4488
Steve Anton4171afb2017-11-20 10:20:22 -08004489void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4490 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004491 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004492 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004493 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004494 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4495 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004496 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004497 return;
4498 }
4499
deadbeeffac06552015-11-25 11:26:01 -08004500 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004501 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004502 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004503 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004504 }
deadbeeffac06552015-11-25 11:26:01 -08004505
Seth Hampson5b4f0752018-04-02 16:31:36 -07004506 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004507 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004508}
4509
Steve Anton4171afb2017-11-20 10:20:22 -08004510void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4511 cricket::MediaType media_type) {
4512 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004513 if (!sender) {
4514 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004515 // SessionDescriptions has been renegotiated.
4516 return;
4517 }
deadbeeffac06552015-11-25 11:26:01 -08004518
4519 // A sender has been removed from the SessionDescription but it's still
4520 // associated with the PeerConnection. This only occurs if the SDP doesn't
4521 // match with the calls to CreateSender, AddStream and RemoveStream.
4522 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004523 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004524 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004525 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004526 }
deadbeeffac06552015-11-25 11:26:01 -08004527
Steve Anton4171afb2017-11-20 10:20:22 -08004528 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004529}
4530
4531void PeerConnection::UpdateLocalRtpDataChannels(
4532 const cricket::StreamParamsVec& streams) {
4533 std::vector<std::string> existing_channels;
4534
4535 // Find new and active data channels.
4536 for (const cricket::StreamParams& params : streams) {
4537 // |it->sync_label| is actually the data channel label. The reason is that
4538 // we use the same naming of data channels as we do for
4539 // MediaStreams and Tracks.
4540 // For MediaStreams, the sync_label is the MediaStream label and the
4541 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004542 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004543 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004544 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004545 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004546 continue;
4547 }
4548 // Set the SSRC the data channel should use for sending.
4549 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4550 existing_channels.push_back(data_channel_it->first);
4551 }
4552
4553 UpdateClosingRtpDataChannels(existing_channels, true);
4554}
4555
4556void PeerConnection::UpdateRemoteRtpDataChannels(
4557 const cricket::StreamParamsVec& streams) {
4558 std::vector<std::string> existing_channels;
4559
4560 // Find new and active data channels.
4561 for (const cricket::StreamParams& params : streams) {
4562 // The data channel label is either the mslabel or the SSRC if the mslabel
4563 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004564 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004565 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004566 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004567 auto data_channel_it = rtp_data_channels_.find(label);
4568 if (data_channel_it == rtp_data_channels_.end()) {
4569 // This is a new data channel.
4570 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4571 } else {
4572 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4573 }
4574 existing_channels.push_back(label);
4575 }
4576
4577 UpdateClosingRtpDataChannels(existing_channels, false);
4578}
4579
4580void PeerConnection::UpdateClosingRtpDataChannels(
4581 const std::vector<std::string>& active_channels,
4582 bool is_local_update) {
4583 auto it = rtp_data_channels_.begin();
4584 while (it != rtp_data_channels_.end()) {
4585 DataChannel* data_channel = it->second;
4586 if (std::find(active_channels.begin(), active_channels.end(),
4587 data_channel->label()) != active_channels.end()) {
4588 ++it;
4589 continue;
4590 }
4591
4592 if (is_local_update) {
4593 data_channel->SetSendSsrc(0);
4594 } else {
4595 data_channel->RemotePeerRequestClose();
4596 }
4597
4598 if (data_channel->state() == DataChannel::kClosed) {
4599 rtp_data_channels_.erase(it);
4600 it = rtp_data_channels_.begin();
4601 } else {
4602 ++it;
4603 }
4604 }
4605}
4606
4607void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4608 uint32_t remote_ssrc) {
4609 rtc::scoped_refptr<DataChannel> channel(
4610 InternalCreateDataChannel(label, nullptr));
4611 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004612 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004613 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004614 return;
4615 }
4616 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004617 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4618 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004619 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004620}
4621
4622rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4623 const std::string& label,
4624 const InternalDataChannelInit* config) {
4625 if (IsClosed()) {
4626 return nullptr;
4627 }
Steve Anton75737c02017-11-06 10:37:17 -08004628 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004629 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004630 << "InternalCreateDataChannel: Data is not supported in this call.";
4631 return nullptr;
4632 }
4633 InternalDataChannelInit new_config =
4634 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004635 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004636 if (new_config.id < 0) {
4637 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004638 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004639 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004640 RTC_LOG(LS_ERROR)
4641 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004642 return nullptr;
4643 }
4644 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004645 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004646 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004647 return nullptr;
4648 }
4649 }
4650
Steve Anton75737c02017-11-06 10:37:17 -08004651 rtc::scoped_refptr<DataChannel> channel(
4652 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004653 if (!channel) {
4654 sid_allocator_.ReleaseSid(new_config.id);
4655 return nullptr;
4656 }
4657
4658 if (channel->data_channel_type() == cricket::DCT_RTP) {
4659 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004660 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4661 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004662 return nullptr;
4663 }
4664 rtp_data_channels_[channel->label()] = channel;
4665 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004666 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004667 sctp_data_channels_.push_back(channel);
4668 channel->SignalClosed.connect(this,
4669 &PeerConnection::OnSctpDataChannelClosed);
4670 }
4671
Steve Anton2d8609c2018-01-23 16:38:46 -08004672 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004673 return channel;
4674}
4675
4676bool PeerConnection::HasDataChannels() const {
4677 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4678}
4679
4680void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4681 for (const auto& channel : sctp_data_channels_) {
4682 if (channel->id() < 0) {
4683 int sid;
4684 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004685 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004686 continue;
4687 }
4688 channel->SetSctpSid(sid);
4689 }
4690 }
4691}
4692
4693void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004694 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004695 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4696 ++it) {
4697 if (it->get() == channel) {
4698 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004699 // After the closing procedure is done, it's safe to use this ID for
4700 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004701 sid_allocator_.ReleaseSid(channel->id());
4702 }
deadbeefbd292462015-12-14 18:15:29 -08004703 // Since this method is triggered by a signal from the DataChannel,
4704 // we can't free it directly here; we need to free it asynchronously.
4705 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004706 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004707 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4708 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004709 return;
4710 }
4711 }
4712}
4713
deadbeefab9b2d12015-10-14 11:33:11 -07004714void PeerConnection::OnDataChannelDestroyed() {
4715 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4716 // DataChannel may callback to us and try to modify the list.
4717 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4718 temp_rtp_dcs.swap(rtp_data_channels_);
4719 for (const auto& kv : temp_rtp_dcs) {
4720 kv.second->OnTransportChannelDestroyed();
4721 }
4722
4723 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4724 temp_sctp_dcs.swap(sctp_data_channels_);
4725 for (const auto& channel : temp_sctp_dcs) {
4726 channel->OnTransportChannelDestroyed();
4727 }
4728}
4729
4730void PeerConnection::OnDataChannelOpenMessage(
4731 const std::string& label,
4732 const InternalDataChannelInit& config) {
4733 rtc::scoped_refptr<DataChannel> channel(
4734 InternalCreateDataChannel(label, &config));
4735 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004736 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004737 return;
4738 }
4739
deadbeefa601f5c2016-06-06 14:27:39 -07004740 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4741 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004742 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004743 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004744}
4745
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004746bool PeerConnection::HandleOpenMessage_s(
4747 const cricket::ReceiveDataParams& params,
4748 const rtc::CopyOnWriteBuffer& buffer) {
4749 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4750 // Received OPEN message; parse and signal that a new data channel should
4751 // be created.
4752 std::string label;
4753 InternalDataChannelInit config;
4754 config.id = params.ssrc;
4755 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4756 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4757 << params.ssrc;
4758 return true;
4759 }
4760 config.open_handshake_role = InternalDataChannelInit::kAcker;
4761 OnDataChannelOpenMessage(label, config);
4762 return true;
4763 }
4764 return false;
4765}
4766
Steve Anton4171afb2017-11-20 10:20:22 -08004767rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4768PeerConnection::GetAudioTransceiver() const {
4769 // This method only works with Plan B SDP, where there is a single
4770 // audio/video transceiver.
4771 RTC_DCHECK(!IsUnifiedPlan());
4772 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004773 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004774 return transceiver;
4775 }
4776 }
4777 RTC_NOTREACHED();
4778 return nullptr;
4779}
4780
4781rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4782PeerConnection::GetVideoTransceiver() const {
4783 // This method only works with Plan B SDP, where there is a single
4784 // audio/video transceiver.
4785 RTC_DCHECK(!IsUnifiedPlan());
4786 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004787 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004788 return transceiver;
4789 }
4790 }
4791 RTC_NOTREACHED();
4792 return nullptr;
4793}
4794
4795// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4796// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004797bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004798 switch (type) {
4799 case cricket::MEDIA_TYPE_AUDIO:
4800 return !GetAudioTransceiver()->internal()->senders().empty();
4801 case cricket::MEDIA_TYPE_VIDEO:
4802 return !GetVideoTransceiver()->internal()->senders().empty();
4803 case cricket::MEDIA_TYPE_DATA:
4804 return false;
4805 }
4806 RTC_NOTREACHED();
4807 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004808}
4809
Steve Anton4171afb2017-11-20 10:20:22 -08004810rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4811PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4812 for (auto transceiver : transceivers_) {
4813 for (auto sender : transceiver->internal()->senders()) {
4814 if (sender->track() == track) {
4815 return sender;
4816 }
4817 }
4818 }
4819 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004820}
4821
Steve Anton4171afb2017-11-20 10:20:22 -08004822rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4823PeerConnection::FindSenderById(const std::string& sender_id) const {
4824 for (auto transceiver : transceivers_) {
4825 for (auto sender : transceiver->internal()->senders()) {
4826 if (sender->id() == sender_id) {
4827 return sender;
4828 }
4829 }
4830 }
4831 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004832}
4833
Steve Anton4171afb2017-11-20 10:20:22 -08004834rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4835PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4836 for (auto transceiver : transceivers_) {
4837 for (auto receiver : transceiver->internal()->receivers()) {
4838 if (receiver->id() == receiver_id) {
4839 return receiver;
4840 }
4841 }
4842 }
4843 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004844}
4845
Steve Anton4171afb2017-11-20 10:20:22 -08004846std::vector<PeerConnection::RtpSenderInfo>*
4847PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4848 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4849 media_type == cricket::MEDIA_TYPE_VIDEO);
4850 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4851 ? &remote_audio_sender_infos_
4852 : &remote_video_sender_infos_;
4853}
4854
4855std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004856 cricket::MediaType media_type) {
4857 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4858 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004859 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4860 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004861}
4862
Steve Anton4171afb2017-11-20 10:20:22 -08004863const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4864 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004865 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004866 const std::string sender_id) const {
4867 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004868 if (sender_info.stream_id == stream_id &&
4869 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004870 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004871 }
4872 }
4873 return nullptr;
4874}
4875
4876DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4877 for (const auto& channel : sctp_data_channels_) {
4878 if (channel->id() == sid) {
4879 return channel;
4880 }
4881 }
4882 return nullptr;
4883}
4884
deadbeef91dd5672016-05-18 16:55:30 -07004885bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004886 const cricket::ServerAddresses& stun_servers,
4887 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004888 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004889 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004890 // To handle both internal and externally created port allocator, we will
4891 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004892 port_allocator_flags_ = port_allocator_->flags();
4893 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4894 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4895 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004896 // If the disable-IPv6 flag was specified, we'll not override it
4897 // by experiment.
4898 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004899 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004900 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4901 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004902 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004903 }
4904
zhihuangb09b3f92017-03-07 14:40:51 -08004905 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004906 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004907 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004908 }
4909
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004910 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004911 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004912 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004913 }
4914
honghaiz60347052016-05-31 18:29:12 -07004915 if (configuration.candidate_network_policy ==
4916 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004917 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004918 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004919 }
4920
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004921 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004922 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004923 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4924 }
4925
Qingsi Wanga2d60672018-04-11 16:57:45 -07004926 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004927 // No step delay is used while allocating ports.
4928 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4929 port_allocator_->set_candidate_filter(
4930 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004931 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004932
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004933 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004934 for (auto& turn_server : turn_servers_copy) {
4935 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004936 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004937 // Call this last since it may create pooled allocator sessions using the
4938 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004939 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004940 stun_servers, std::move(turn_servers_copy),
4941 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4942 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004943 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004944 return true;
4945}
4946
deadbeef91dd5672016-05-18 16:55:30 -07004947bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004948 const cricket::ServerAddresses& stun_servers,
4949 const std::vector<cricket::RelayServerConfig>& turn_servers,
4950 IceTransportsType type,
4951 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004952 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004953 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004954 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004955 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004956 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004957 // According to JSEP, after setLocalDescription, changing the candidate pool
4958 // size is not allowed, and changing the set of ICE servers will not result
4959 // in new candidates being gathered.
4960 if (local_description()) {
4961 port_allocator_->FreezeCandidatePool();
4962 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004963 // Add the custom tls turn servers if they exist.
4964 auto turn_servers_copy = turn_servers;
4965 for (auto& turn_server : turn_servers_copy) {
4966 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4967 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004968 // Call this last since it may create pooled allocator sessions using the
4969 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004970 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004971 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4972 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004973}
4974
Steve Antonba818672017-11-06 10:21:57 -08004975cricket::ChannelManager* PeerConnection::channel_manager() const {
4976 return factory_->channel_manager();
4977}
4978
Elad Alon99c3fe52017-10-13 16:29:40 +02004979bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004980 std::unique_ptr<RtcEventLogOutput> output,
4981 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004982 if (!event_log_) {
4983 return false;
4984 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004985 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004986}
4987
4988void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004989 if (event_log_) {
4990 event_log_->StopLogging();
4991 }
ivoc14d5dbe2016-07-04 07:06:55 -07004992}
nisseeaabdf62017-05-05 02:23:02 -07004993
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004994cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08004995 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004996 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004997 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08004998 if (channel && channel->content_name() == content_name) {
4999 return channel;
5000 }
Steve Anton75737c02017-11-06 10:37:17 -08005001 }
5002 if (rtp_data_channel() &&
5003 rtp_data_channel()->content_name() == content_name) {
5004 return rtp_data_channel();
5005 }
5006 return nullptr;
5007}
5008
5009bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005010 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005011 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005012 RTC_LOG(LS_INFO)
5013 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005014 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005015 return false;
5016 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005017 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005019 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005020 return false;
5021 }
5022
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005023 absl::optional<rtc::SSLRole> dtls_role;
5024 if (sctp_mid_) {
5025 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5026 } else if (is_caller_) {
5027 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5028 }
Zhi Huange830e682018-03-30 10:48:35 -07005029 if (dtls_role) {
5030 *role = *dtls_role;
5031 return true;
5032 }
5033 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005034}
5035
5036bool PeerConnection::GetSslRole(const std::string& content_name,
5037 rtc::SSLRole* role) {
5038 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005039 RTC_LOG(LS_INFO)
5040 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005041 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005042 return false;
5043 }
5044
Zhi Huange830e682018-03-30 10:48:35 -07005045 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5046 if (dtls_role) {
5047 *role = *dtls_role;
5048 return true;
5049 }
5050 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005051}
5052
Steve Antonf8470812017-12-04 10:46:21 -08005053void PeerConnection::SetSessionError(SessionError error,
5054 const std::string& error_desc) {
5055 RTC_DCHECK_RUN_ON(signaling_thread());
5056 if (error != session_error_) {
5057 session_error_ = error;
5058 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005059 }
5060}
5061
Zhi Huange830e682018-03-30 10:48:35 -07005062RTCError PeerConnection::UpdateSessionState(
5063 SdpType type,
5064 cricket::ContentSource source,
5065 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005066 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005067
5068 // If there's already a pending error then no state transition should happen.
5069 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005070 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005071
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005072 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005073 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005074 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005075 }
5076
5077 // Update the signaling state according to the specified state machine (see
5078 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005079 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005080 ChangeSignalingState(source == cricket::CS_LOCAL
5081 ? PeerConnectionInterface::kHaveLocalOffer
5082 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005083 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005084 ChangeSignalingState(source == cricket::CS_LOCAL
5085 ? PeerConnectionInterface::kHaveLocalPrAnswer
5086 : PeerConnectionInterface::kHaveRemotePrAnswer);
5087 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005088 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005089 ChangeSignalingState(PeerConnectionInterface::kStable);
5090 }
5091
5092 // Update internal objects according to the session description's media
5093 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005094 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005095 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005096 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005097 }
5098
Steve Anton8a006912017-12-04 15:25:56 -08005099 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005100}
5101
Steve Anton8a006912017-12-04 15:25:56 -08005102RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005103 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005104 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005105 const SessionDescriptionInterface* sdesc =
5106 (source == cricket::CS_LOCAL ? local_description()
5107 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005108 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005109
5110 // Push down the new SDP media section for each audio/video transceiver.
5111 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005112 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005113 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005114 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005115 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005116 continue;
5117 }
5118 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005119 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005120 if (!content_desc) {
5121 continue;
5122 }
5123 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005124 bool success = (source == cricket::CS_LOCAL)
5125 ? channel->SetLocalContent(content_desc, type, &error)
5126 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005127 if (!success) {
5128 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5129 }
5130 }
5131
5132 // If using the RtpDataChannel, push down the new SDP section for it too.
5133 if (rtp_data_channel_) {
5134 const ContentInfo* data_content =
5135 cricket::GetFirstDataContent(sdesc->description());
5136 if (data_content && !data_content->rejected) {
5137 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005138 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005139 if (data_desc) {
5140 std::string error;
5141 bool success =
5142 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005143 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005144 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005145 if (!success) {
5146 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5147 std::move(error));
5148 }
Steve Anton75737c02017-11-06 10:37:17 -08005149 }
5150 }
5151 }
Steve Antoned10bd92017-12-05 10:52:59 -08005152
Steve Anton75737c02017-11-06 10:37:17 -08005153 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5154 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5155 if (sctp_transport_ && local_description() && remote_description() &&
5156 cricket::GetFirstDataContent(local_description()->description()) &&
5157 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005158 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005159 RTC_FROM_HERE,
5160 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005161 if (!success) {
5162 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5163 "Failed to push down SCTP parameters.");
5164 }
Steve Anton75737c02017-11-06 10:37:17 -08005165 }
Steve Antoned10bd92017-12-05 10:52:59 -08005166
Steve Anton8a006912017-12-04 15:25:56 -08005167 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005168}
5169
5170bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5171 RTC_DCHECK(network_thread()->IsCurrent());
5172 RTC_DCHECK(local_description());
5173 RTC_DCHECK(remote_description());
5174 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5175 // When we support "max-message-size", that would also be pushed down here.
5176 return sctp_transport_->Start(
5177 GetSctpPort(local_description()->description()),
5178 GetSctpPort(remote_description()->description()));
5179}
5180
Steve Anton8a006912017-12-04 15:25:56 -08005181RTCError PeerConnection::PushdownTransportDescription(
5182 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005183 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005184 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005185
Zhi Huange830e682018-03-30 10:48:35 -07005186 if (source == cricket::CS_LOCAL) {
5187 const SessionDescriptionInterface* sdesc = local_description();
5188 RTC_DCHECK(sdesc);
5189 return transport_controller_->SetLocalDescription(type,
5190 sdesc->description());
5191 } else {
5192 const SessionDescriptionInterface* sdesc = remote_description();
5193 RTC_DCHECK(sdesc);
5194 return transport_controller_->SetRemoteDescription(type,
5195 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005196 }
Steve Anton75737c02017-11-06 10:37:17 -08005197}
5198
5199bool PeerConnection::GetTransportDescription(
5200 const SessionDescription* description,
5201 const std::string& content_name,
5202 cricket::TransportDescription* tdesc) {
5203 if (!description || !tdesc) {
5204 return false;
5205 }
5206 const TransportInfo* transport_info =
5207 description->GetTransportInfoByName(content_name);
5208 if (!transport_info) {
5209 return false;
5210 }
5211 *tdesc = transport_info->description;
5212 return true;
5213}
5214
Steve Anton75737c02017-11-06 10:37:17 -08005215cricket::IceConfig PeerConnection::ParseIceConfig(
5216 const PeerConnectionInterface::RTCConfiguration& config) const {
5217 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005218 switch (config.continual_gathering_policy) {
5219 case PeerConnectionInterface::GATHER_ONCE:
5220 gathering_policy = cricket::GATHER_ONCE;
5221 break;
5222 case PeerConnectionInterface::GATHER_CONTINUALLY:
5223 gathering_policy = cricket::GATHER_CONTINUALLY;
5224 break;
5225 default:
5226 RTC_NOTREACHED();
5227 gathering_policy = cricket::GATHER_ONCE;
5228 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005229
Steve Anton75737c02017-11-06 10:37:17 -08005230 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005231 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5232 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005233 ice_config.prioritize_most_likely_candidate_pairs =
5234 config.prioritize_most_likely_ice_candidate_pairs;
5235 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005236 RTCConfigurationToIceConfigOptionalInt(
5237 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005238 ice_config.continual_gathering_policy = gathering_policy;
5239 ice_config.presume_writable_when_fully_relayed =
5240 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005241 ice_config.ice_check_interval_strong_connectivity =
5242 config.ice_check_interval_strong_connectivity;
5243 ice_config.ice_check_interval_weak_connectivity =
5244 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005245 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005246 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5247 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005248 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005249 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005250 ice_config.regather_all_networks_interval_range =
5251 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005252 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005253 return ice_config;
5254}
5255
Steve Antona41959e2018-11-28 11:15:33 -08005256static absl::string_view GetTrackIdBySsrc(
5257 const SessionDescriptionInterface* session_description,
5258 uint32_t ssrc) {
5259 if (!session_description) {
5260 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005261 }
Steve Antona41959e2018-11-28 11:15:33 -08005262 for (const cricket::ContentInfo& content :
5263 session_description->description()->contents()) {
5264 const cricket::MediaContentDescription& media =
5265 *content.media_description();
5266 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5267 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5268 const cricket::StreamParams* stream_params =
5269 cricket::GetStreamBySsrc(media.streams(), ssrc);
5270 if (stream_params) {
5271 return stream_params->id;
5272 }
5273 }
5274 }
5275 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005276}
5277
Steve Antona41959e2018-11-28 11:15:33 -08005278absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5279 return GetTrackIdBySsrc(local_description(), ssrc);
5280}
5281
5282absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5283 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005284}
5285
5286bool PeerConnection::SendData(const cricket::SendDataParams& params,
5287 const rtc::CopyOnWriteBuffer& payload,
5288 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005289 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5290 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5291 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005292 return false;
5293 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005294 if (media_transport_) {
5295 SendDataParams send_params;
5296 send_params.type = ToWebrtcDataMessageType(params.type);
5297 send_params.ordered = params.ordered;
5298 if (params.max_rtx_count >= 0) {
5299 send_params.max_rtx_count = params.max_rtx_count;
5300 } else if (params.max_rtx_ms >= 0) {
5301 send_params.max_rtx_ms = params.max_rtx_ms;
5302 }
5303 return media_transport_->SendData(params.sid, send_params, payload).ok();
5304 }
Steve Anton75737c02017-11-06 10:37:17 -08005305 return rtp_data_channel_
5306 ? rtp_data_channel_->SendData(params, payload, result)
5307 : network_thread()->Invoke<bool>(
5308 RTC_FROM_HERE,
5309 Bind(&cricket::SctpTransportInternal::SendData,
5310 sctp_transport_.get(), params, payload, result));
5311}
5312
5313bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005314 RTC_DCHECK_RUN_ON(signaling_thread());
5315 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005316 // Don't log an error here, because DataChannels are expected to call
5317 // ConnectDataChannel in this state. It's the only way to initially tell
5318 // whether or not the underlying transport is ready.
5319 return false;
5320 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005321 if (media_transport_) {
5322 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5323 &DataChannel::OnChannelReady);
5324 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5325 &DataChannel::OnDataReceived);
5326 SignalMediaTransportChannelClosing_s.connect(
5327 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5328 SignalMediaTransportChannelClosed_s.connect(
5329 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5330 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005331 rtp_data_channel_->SignalReadyToSendData.connect(
5332 webrtc_data_channel, &DataChannel::OnChannelReady);
5333 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5334 &DataChannel::OnDataReceived);
5335 } else {
5336 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5337 &DataChannel::OnChannelReady);
5338 SignalSctpDataReceived.connect(webrtc_data_channel,
5339 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005340 SignalSctpClosingProcedureStartedRemotely.connect(
5341 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5342 SignalSctpClosingProcedureComplete.connect(
5343 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005344 }
5345 return true;
5346}
5347
5348void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005349 RTC_DCHECK_RUN_ON(signaling_thread());
5350 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005351 RTC_LOG(LS_ERROR)
5352 << "DisconnectDataChannel called when rtp_data_channel_ and "
5353 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005354 return;
5355 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005356 if (media_transport_) {
5357 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5358 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5359 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5360 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5361 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005362 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5363 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5364 } else {
5365 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5366 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005367 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5368 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005369 }
5370}
5371
5372void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005373 if (media_transport_) {
5374 // No-op. Media transport does not need to add streams.
5375 return;
5376 }
Steve Anton75737c02017-11-06 10:37:17 -08005377 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005378 RTC_LOG(LS_ERROR)
5379 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005380 return;
5381 }
5382 network_thread()->Invoke<void>(
5383 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5384 sctp_transport_.get(), sid));
5385}
5386
5387void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005388 if (media_transport_) {
5389 media_transport_->CloseChannel(sid);
5390 return;
5391 }
Steve Anton75737c02017-11-06 10:37:17 -08005392 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005393 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005394 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005395 return;
5396 }
5397 network_thread()->Invoke<void>(
5398 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5399 sctp_transport_.get(), sid));
5400}
5401
5402bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005403 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005404 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005405 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005406 sctp_ready_to_send_data_;
5407}
5408
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005409void PeerConnection::OnDataReceived(int channel_id,
5410 DataMessageType type,
5411 const rtc::CopyOnWriteBuffer& buffer) {
5412 cricket::ReceiveDataParams params;
5413 params.sid = channel_id;
5414 params.type = ToCricketDataMessageType(type);
5415 media_transport_invoker_->AsyncInvoke<void>(
5416 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5417 RTC_DCHECK_RUN_ON(signaling_thread());
5418 if (!HandleOpenMessage_s(params, buffer)) {
5419 SignalMediaTransportReceivedData_s(params, buffer);
5420 }
5421 });
5422}
5423
5424void PeerConnection::OnChannelClosing(int channel_id) {
5425 media_transport_invoker_->AsyncInvoke<void>(
5426 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5427 RTC_DCHECK_RUN_ON(signaling_thread());
5428 SignalMediaTransportChannelClosing_s(channel_id);
5429 });
5430}
5431
5432void PeerConnection::OnChannelClosed(int channel_id) {
5433 media_transport_invoker_->AsyncInvoke<void>(
5434 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5435 RTC_DCHECK_RUN_ON(signaling_thread());
5436 SignalMediaTransportChannelClosed_s(channel_id);
5437 });
5438}
5439
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005440absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005441 if (sctp_mid_ && transport_controller_) {
5442 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5443 if (dtls_transport) {
5444 return dtls_transport->transport_name();
5445 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005446 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005447 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005448 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005449}
5450
Qingsi Wang72a43a12018-02-20 16:03:18 -08005451cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5452 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005453 network_thread()->Invoke<void>(
5454 RTC_FROM_HERE,
5455 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5456 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005457 return candidate_states_list;
5458}
5459
Steve Anton5dfde182018-02-06 10:34:40 -08005460std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5461 const {
5462 std::map<std::string, std::string> transport_names_by_mid;
5463 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005464 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005465 if (channel) {
5466 transport_names_by_mid[channel->content_name()] =
5467 channel->transport_name();
5468 }
Steve Anton75737c02017-11-06 10:37:17 -08005469 }
Steve Anton5dfde182018-02-06 10:34:40 -08005470 if (rtp_data_channel_) {
5471 transport_names_by_mid[rtp_data_channel_->content_name()] =
5472 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005473 }
5474 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005475 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005476 RTC_DCHECK(transport_name);
5477 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005478 }
Steve Anton5dfde182018-02-06 10:34:40 -08005479 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005480}
5481
Steve Anton5dfde182018-02-06 10:34:40 -08005482std::map<std::string, cricket::TransportStats>
5483PeerConnection::GetTransportStatsByNames(
5484 const std::set<std::string>& transport_names) {
5485 if (!network_thread()->IsCurrent()) {
5486 return network_thread()
5487 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5488 RTC_FROM_HERE,
5489 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005490 }
Steve Anton5dfde182018-02-06 10:34:40 -08005491 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5492 for (const std::string& transport_name : transport_names) {
5493 cricket::TransportStats transport_stats;
5494 bool success =
5495 transport_controller_->GetStats(transport_name, &transport_stats);
5496 if (success) {
5497 transport_stats_by_name[transport_name] = std::move(transport_stats);
5498 } else {
5499 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5500 << transport_name;
5501 }
5502 }
5503 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005504}
5505
5506bool PeerConnection::GetLocalCertificate(
5507 const std::string& transport_name,
5508 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005509 if (!certificate) {
5510 return false;
5511 }
5512 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5513 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005514}
5515
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005516std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005517 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005518 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005519}
5520
5521cricket::DataChannelType PeerConnection::data_channel_type() const {
5522 return data_channel_type_;
5523}
5524
5525bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5526 return pending_ice_restarts_.find(content_name) !=
5527 pending_ice_restarts_.end();
5528}
5529
Steve Anton75737c02017-11-06 10:37:17 -08005530bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5531 return transport_controller_->NeedsIceRestart(content_name);
5532}
5533
5534void PeerConnection::OnCertificateReady(
5535 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5536 transport_controller_->SetLocalCertificate(certificate);
5537}
5538
5539void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005540 SetSessionError(SessionError::kTransport,
5541 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005542}
5543
Alex Loiko9289eda2018-11-23 16:18:59 +00005544void PeerConnection::OnTransportControllerConnectionState(
5545 cricket::IceConnectionState state) {
5546 switch (state) {
5547 case cricket::kIceConnectionConnecting:
5548 // If the current state is Connected or Completed, then there were
5549 // writable channels but now there are not, so the next state must
5550 // be Disconnected.
5551 // kIceConnectionConnecting is currently used as the default,
5552 // un-connected state by the TransportController, so its only use is
5553 // detecting disconnections.
5554 if (ice_connection_state_ ==
5555 PeerConnectionInterface::kIceConnectionConnected ||
5556 ice_connection_state_ ==
5557 PeerConnectionInterface::kIceConnectionCompleted) {
5558 SetIceConnectionState(
5559 PeerConnectionInterface::kIceConnectionDisconnected);
5560 }
5561 break;
5562 case cricket::kIceConnectionFailed:
5563 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5564 break;
5565 case cricket::kIceConnectionConnected:
5566 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5567 "all transports are writable.";
5568 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5569 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5570 break;
5571 case cricket::kIceConnectionCompleted:
5572 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5573 "all transports are complete.";
5574 if (ice_connection_state_ !=
5575 PeerConnectionInterface::kIceConnectionConnected) {
5576 // If jumping directly from "checking" to "connected",
5577 // signal "connected" first.
5578 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5579 }
5580 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5581 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5582 ReportTransportStats();
5583 break;
5584 default:
5585 RTC_NOTREACHED();
5586 }
5587}
5588
Steve Anton75737c02017-11-06 10:37:17 -08005589void PeerConnection::OnTransportControllerCandidatesGathered(
5590 const std::string& transport_name,
5591 const cricket::Candidates& candidates) {
5592 RTC_DCHECK(signaling_thread()->IsCurrent());
5593 int sdp_mline_index;
5594 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005595 RTC_LOG(LS_ERROR)
5596 << "OnTransportControllerCandidatesGathered: content name "
5597 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005598 return;
5599 }
5600
5601 for (cricket::Candidates::const_iterator citer = candidates.begin();
5602 citer != candidates.end(); ++citer) {
5603 // Use transport_name as the candidate media id.
5604 std::unique_ptr<JsepIceCandidate> candidate(
5605 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5606 if (local_description()) {
5607 mutable_local_description()->AddCandidate(candidate.get());
5608 }
5609 OnIceCandidate(std::move(candidate));
5610 }
5611}
5612
5613void PeerConnection::OnTransportControllerCandidatesRemoved(
5614 const std::vector<cricket::Candidate>& candidates) {
5615 RTC_DCHECK(signaling_thread()->IsCurrent());
5616 // Sanity check.
5617 for (const cricket::Candidate& candidate : candidates) {
5618 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005619 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005620 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005621 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005622 return;
5623 }
5624 }
5625
5626 if (local_description()) {
5627 mutable_local_description()->RemoveCandidates(candidates);
5628 }
5629 OnIceCandidatesRemoved(candidates);
5630}
5631
5632void PeerConnection::OnTransportControllerDtlsHandshakeError(
5633 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005634 RTC_HISTOGRAM_ENUMERATION(
5635 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5636 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005637}
5638
Steve Antoned10bd92017-12-05 10:52:59 -08005639void PeerConnection::EnableSending() {
5640 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005641 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005642 if (channel && !channel->enabled()) {
5643 channel->Enable(true);
5644 }
Steve Anton75737c02017-11-06 10:37:17 -08005645 }
5646
Steve Anton4171afb2017-11-20 10:20:22 -08005647 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005648 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005649 }
Steve Anton75737c02017-11-06 10:37:17 -08005650}
5651
5652// Returns the media index for a local ice candidate given the content name.
5653bool PeerConnection::GetLocalCandidateMediaIndex(
5654 const std::string& content_name,
5655 int* sdp_mline_index) {
5656 if (!local_description() || !sdp_mline_index) {
5657 return false;
5658 }
5659
5660 bool content_found = false;
5661 const ContentInfos& contents = local_description()->description()->contents();
5662 for (size_t index = 0; index < contents.size(); ++index) {
5663 if (contents[index].name == content_name) {
5664 *sdp_mline_index = static_cast<int>(index);
5665 content_found = true;
5666 break;
5667 }
5668 }
5669 return content_found;
5670}
5671
5672bool PeerConnection::UseCandidatesInSessionDescription(
5673 const SessionDescriptionInterface* remote_desc) {
5674 if (!remote_desc) {
5675 return true;
5676 }
5677 bool ret = true;
5678
5679 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5680 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5681 for (size_t n = 0; n < candidates->count(); ++n) {
5682 const IceCandidateInterface* candidate = candidates->at(n);
5683 bool valid = false;
5684 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5685 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005686 RTC_LOG(LS_INFO)
5687 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005688 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005689 }
5690 continue;
5691 }
5692 ret = UseCandidate(candidate);
5693 if (!ret) {
5694 break;
5695 }
5696 }
5697 }
5698 return ret;
5699}
5700
5701bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5702 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5703 size_t remote_content_size =
5704 remote_description()->description()->contents().size();
5705 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005706 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005707 return false;
5708 }
5709
5710 cricket::ContentInfo content =
5711 remote_description()->description()->contents()[mediacontent_index];
5712 std::vector<cricket::Candidate> candidates;
5713 candidates.push_back(candidate->candidate());
5714 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005715 RTCError error =
5716 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005717 if (error.ok()) {
5718 // Candidates successfully submitted for checking.
5719 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5720 ice_connection_state_ ==
5721 PeerConnectionInterface::kIceConnectionDisconnected) {
5722 // If state is New, then the session has just gotten its first remote ICE
5723 // candidates, so go to Checking.
5724 // If state is Disconnected, the session is re-using old candidates or
5725 // receiving additional ones, so go to Checking.
5726 // If state is Connected, stay Connected.
5727 // TODO(bemasc): If state is Connected, and the new candidates are for a
5728 // newly added transport, then the state actually _should_ move to
5729 // checking. Add a way to distinguish that case.
5730 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5731 }
5732 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005733 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005734 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005735 }
5736 return true;
5737}
5738
5739void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005740 // Destroy video channel first since it may have a pointer to the
5741 // voice channel.
5742 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005743 if (!video_info || video_info->rejected) {
5744 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005745 }
5746
Steve Anton6fec8802017-12-04 10:37:29 -08005747 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5748 if (!audio_info || audio_info->rejected) {
5749 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
5751
5752 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5753 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005754 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005755 }
5756}
5757
Steve Antondcc3c022017-12-22 16:02:54 -08005758RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5759 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005760 const cricket::ContentGroup* bundle_group = nullptr;
5761 if (configuration_.bundle_policy ==
5762 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005763 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005764 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005765 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5766 "max-bundle configured but session description "
5767 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005768 }
5769 }
Steve Antondcc3c022017-12-22 16:02:54 -08005770 return std::move(bundle_group);
5771}
5772
5773RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005774 // Creating the media channels. Transports should already have been created
5775 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005776 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005777 if (voice && !voice->rejected &&
5778 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005779 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005780 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005781 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5782 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005783 }
5784 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5785 }
5786
Steve Antondcc3c022017-12-22 16:02:54 -08005787 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005788 if (video && !video->rejected &&
5789 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005790 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005791 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005792 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5793 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005794 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005795 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005796 }
5797
Steve Antondcc3c022017-12-22 16:02:54 -08005798 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005799 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005800 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005801 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005802 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5803 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005804 }
5805 }
5806
Steve Anton8a006912017-12-04 15:25:56 -08005807 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005808}
5809
Steve Anton4171afb2017-11-20 10:20:22 -08005810// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005811cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005812 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005813 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005814 MediaTransportInterface* media_transport = nullptr;
5815 if (configuration_.use_media_transport) {
5816 media_transport = GetMediaTransport(mid);
5817 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005818
Steve Anton75737c02017-11-06 10:37:17 -08005819 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005820 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005821 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5822 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005823 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005824 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005825 }
Steve Anton75737c02017-11-06 10:37:17 -08005826 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5827 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005828 voice_channel->SignalSentPacket.connect(this,
5829 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005830 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005831
Steve Antoneda6ccd2017-12-04 10:21:55 -08005832 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005833}
5834
Steve Anton4171afb2017-11-20 10:20:22 -08005835// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005836cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005837 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005838 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5839
5840 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005841 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005842 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005843 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5844 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005845 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005846 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005847 }
Steve Anton75737c02017-11-06 10:37:17 -08005848 video_channel->SignalDtlsSrtpSetupFailure.connect(
5849 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005850 video_channel->SignalSentPacket.connect(this,
5851 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005852 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005853
Steve Antoneda6ccd2017-12-04 10:21:55 -08005854 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005855}
5856
Zhi Huange830e682018-03-30 10:48:35 -07005857bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005858 switch (data_channel_type_) {
5859 case cricket::DCT_MEDIA_TRANSPORT:
5860 if (network_thread()->Invoke<bool>(
5861 RTC_FROM_HERE,
5862 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5863 this, mid))) {
5864 for (const auto& channel : sctp_data_channels_) {
5865 channel->OnTransportChannelCreated();
5866 }
5867 return true;
5868 }
Steve Anton75737c02017-11-06 10:37:17 -08005869 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005870 case cricket::DCT_SCTP:
5871 if (!sctp_factory_) {
5872 RTC_LOG(LS_ERROR)
5873 << "Trying to create SCTP transport, but didn't compile with "
5874 "SCTP support (HAVE_SCTP)";
5875 return false;
5876 }
5877 if (!network_thread()->Invoke<bool>(
5878 RTC_FROM_HERE,
5879 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5880 return false;
5881 }
5882 for (const auto& channel : sctp_data_channels_) {
5883 channel->OnTransportChannelCreated();
5884 }
5885 return true;
5886 case cricket::DCT_RTP:
5887 default:
5888 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5889 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5890 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5891 SrtpRequired(), GetCryptoOptions());
5892 if (!rtp_data_channel_) {
5893 return false;
5894 }
5895 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5896 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5897 rtp_data_channel_->SignalSentPacket.connect(
5898 this, &PeerConnection::OnSentPacket_w);
5899 rtp_data_channel_->SetRtpTransport(rtp_transport);
5900 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005901 }
5902
Steve Anton75737c02017-11-06 10:37:17 -08005903 return true;
5904}
5905
5906Call::Stats PeerConnection::GetCallStats() {
5907 if (!worker_thread()->IsCurrent()) {
5908 return worker_thread()->Invoke<Call::Stats>(
5909 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5910 }
5911 if (call_) {
5912 return call_->GetStats();
5913 } else {
5914 return Call::Stats();
5915 }
5916}
5917
Zhi Huange830e682018-03-30 10:48:35 -07005918bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005919 RTC_DCHECK(network_thread()->IsCurrent());
5920 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005921 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005922 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005923 RTC_DCHECK(dtls_transport);
5924 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005925 RTC_DCHECK(sctp_transport_);
5926 sctp_invoker_.reset(new rtc::AsyncInvoker());
5927 sctp_transport_->SignalReadyToSendData.connect(
5928 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5929 sctp_transport_->SignalDataReceived.connect(
5930 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005931 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5932 // another thread. Would be nice if there was a helper class similar to
5933 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5934 // code.
5935 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5936 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5937 sctp_transport_->SignalClosingProcedureComplete.connect(
5938 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005939 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005940 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005941 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005942}
5943
5944void PeerConnection::DestroySctpTransport_n() {
5945 RTC_DCHECK(network_thread()->IsCurrent());
5946 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005947 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005948 sctp_invoker_.reset(nullptr);
5949 sctp_ready_to_send_data_ = false;
5950}
5951
5952void PeerConnection::OnSctpTransportReadyToSendData_n() {
5953 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5954 RTC_DCHECK(network_thread()->IsCurrent());
5955 // Note: Cannot use rtc::Bind here because it will grab a reference to
5956 // PeerConnection and potentially cause PeerConnection to live longer than
5957 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5958 // be destroyed before PeerConnection is destroyed, and at that point all
5959 // pending tasks will be cleared.
5960 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5961 OnSctpTransportReadyToSendData_s(true);
5962 });
5963}
5964
5965void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5966 RTC_DCHECK(signaling_thread()->IsCurrent());
5967 sctp_ready_to_send_data_ = ready;
5968 SignalSctpReadyToSendData(ready);
5969}
5970
5971void PeerConnection::OnSctpTransportDataReceived_n(
5972 const cricket::ReceiveDataParams& params,
5973 const rtc::CopyOnWriteBuffer& payload) {
5974 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5975 RTC_DCHECK(network_thread()->IsCurrent());
5976 // Note: Cannot use rtc::Bind here because it will grab a reference to
5977 // PeerConnection and potentially cause PeerConnection to live longer than
5978 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5979 // be destroyed before PeerConnection is destroyed, and at that point all
5980 // pending tasks will be cleared.
5981 sctp_invoker_->AsyncInvoke<void>(
5982 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5983 OnSctpTransportDataReceived_s(params, payload);
5984 });
5985}
5986
5987void PeerConnection::OnSctpTransportDataReceived_s(
5988 const cricket::ReceiveDataParams& params,
5989 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005990 RTC_DCHECK_RUN_ON(signaling_thread());
5991 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005992 SignalSctpDataReceived(params, payload);
5993 }
5994}
5995
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005996void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005997 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5998 RTC_DCHECK(network_thread()->IsCurrent());
5999 sctp_invoker_->AsyncInvoke<void>(
6000 RTC_FROM_HERE, signaling_thread(),
6001 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006002 &SignalSctpClosingProcedureStartedRemotely, sid));
6003}
6004
6005void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6006 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6007 RTC_DCHECK(network_thread()->IsCurrent());
6008 sctp_invoker_->AsyncInvoke<void>(
6009 RTC_FROM_HERE, signaling_thread(),
6010 rtc::Bind(&sigslot::signal1<int>::operator(),
6011 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006012}
6013
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006014bool PeerConnection::SetupMediaTransportForDataChannels_n(
6015 const std::string& mid) {
6016 media_transport_ = transport_controller_->GetMediaTransport(mid);
6017 if (!media_transport_) {
6018 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6019 return false;
6020 }
6021
6022 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6023 media_transport_->SetDataSink(this);
6024 media_transport_data_mid_ = mid;
6025 transport_controller_->SignalMediaTransportStateChanged.connect(
6026 this, &PeerConnection::OnMediaTransportStateChanged_n);
6027 // Check the initial state right away, in case transport is already writable.
6028 OnMediaTransportStateChanged_n();
6029 return true;
6030}
6031
6032void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6033 if (!media_transport_) {
6034 return;
6035 }
6036 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6037 media_transport_data_mid_.reset();
6038 media_transport_->SetDataSink(nullptr);
6039 media_transport_invoker_ = nullptr;
6040 media_transport_ = nullptr;
6041}
6042
6043void PeerConnection::OnMediaTransportStateChanged_n() {
6044 if (!media_transport_data_mid_ ||
6045 transport_controller_->GetMediaTransportState(
6046 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6047 return;
6048 }
6049 media_transport_invoker_->AsyncInvoke<void>(
6050 RTC_FROM_HERE, signaling_thread(), [this] {
6051 RTC_DCHECK_RUN_ON(signaling_thread());
6052 media_transport_ready_to_send_data_ = true;
6053 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6054 });
6055}
6056
Steve Anton75737c02017-11-06 10:37:17 -08006057// Returns false if bundle is enabled and rtcp_mux is disabled.
6058bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6059 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6060 if (!bundle_enabled)
6061 return true;
6062
6063 const cricket::ContentGroup* bundle_group =
6064 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6065 RTC_DCHECK(bundle_group != NULL);
6066
6067 const cricket::ContentInfos& contents = desc->contents();
6068 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6069 citer != contents.end(); ++citer) {
6070 const cricket::ContentInfo* content = (&*citer);
6071 RTC_DCHECK(content != NULL);
6072 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006073 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006074 if (!HasRtcpMuxEnabled(content))
6075 return false;
6076 }
6077 }
6078 // RTCP-MUX is enabled in all the contents.
6079 return true;
6080}
6081
6082bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006083 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006084}
6085
Steve Anton8a006912017-12-04 15:25:56 -08006086RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006087 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006088 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006089 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006090 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006091 }
6092
6093 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006094 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006095 }
6096
Steve Anton3828c062017-12-06 10:34:51 -08006097 SdpType type = sdesc->GetType();
6098 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6099 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006100 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006101 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006102 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006103 }
6104
6105 // Verify crypto settings.
6106 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006107 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6108 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006109 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006110 if (!crypto_error.ok()) {
6111 return crypto_error;
6112 }
Steve Anton75737c02017-11-06 10:37:17 -08006113 }
6114
6115 // Verify ice-ufrag and ice-pwd.
6116 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006117 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6118 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006119 }
6120
6121 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006122 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6123 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006124 }
6125
6126 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6127 // m-lines that do not rtcp-mux enabled.
6128
6129 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006130 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006131 // With an answer we want to compare the new answer session description with
6132 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006133 const cricket::SessionDescription* offer_desc =
6134 (source == cricket::CS_LOCAL) ? remote_description()->description()
6135 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006136 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6137 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6138 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006139 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6140 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006141 }
6142 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006143 // The re-offers should respect the order of m= sections in current
6144 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006145 // With a re-offer, either the current local or current remote descriptions
6146 // could be the most up to date, so we would like to check against both of
6147 // them if they exist. It could be the case that one of them has a 0 port
6148 // for a media section, but the other does not. This is important to check
6149 // against in the case that we are recycling an m= section.
6150 const cricket::SessionDescription* current_desc = nullptr;
6151 const cricket::SessionDescription* secondary_current_desc = nullptr;
6152 if (local_description()) {
6153 current_desc = local_description()->description();
6154 if (remote_description()) {
6155 secondary_current_desc = remote_description()->description();
6156 }
6157 } else if (remote_description()) {
6158 current_desc = remote_description()->description();
6159 }
Steve Anton75737c02017-11-06 10:37:17 -08006160 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006161 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6162 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006163 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6164 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006165 }
6166 }
6167
Steve Antonba42e992018-04-09 14:10:01 -07006168 if (IsUnifiedPlan()) {
6169 // Ensure that each audio and video media section has at most one
6170 // "StreamParams". This will return an error if receiving a session
6171 // description from a "Plan B" endpoint which adds multiple tracks of the
6172 // same type. With Unified Plan, there can only be at most one track per
6173 // media section.
6174 for (const ContentInfo& content : sdesc->description()->contents()) {
6175 const MediaContentDescription& desc = *content.description;
6176 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6177 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6178 desc.streams().size() > 1u) {
6179 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6180 "Media section has more than one track specified "
6181 "with a=ssrc lines which is not supported with "
6182 "Unified Plan.");
6183 }
6184 }
6185 }
6186
Steve Anton8a006912017-12-04 15:25:56 -08006187 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006188}
6189
Steve Anton3828c062017-12-06 10:34:51 -08006190bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006191 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006192 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006193 return (state == PeerConnectionInterface::kStable) ||
6194 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006195 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006196 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006197 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6198 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6199 }
6200}
6201
Steve Anton3828c062017-12-06 10:34:51 -08006202bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006203 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006204 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006205 return (state == PeerConnectionInterface::kStable) ||
6206 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006207 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006208 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006209 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6210 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6211 }
6212}
6213
Steve Antonf8470812017-12-04 10:46:21 -08006214const char* PeerConnection::SessionErrorToString(SessionError error) const {
6215 switch (error) {
6216 case SessionError::kNone:
6217 return "ERROR_NONE";
6218 case SessionError::kContent:
6219 return "ERROR_CONTENT";
6220 case SessionError::kTransport:
6221 return "ERROR_TRANSPORT";
6222 }
6223 RTC_NOTREACHED();
6224 return "";
6225}
6226
Steve Anton75737c02017-11-06 10:37:17 -08006227std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006228 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006229 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6230 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006231 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006232}
6233
Steve Anton8e20f172018-03-06 10:55:04 -08006234void PeerConnection::ReportSdpFormatReceived(
6235 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006236 int num_audio_mlines = 0;
6237 int num_video_mlines = 0;
6238 int num_audio_tracks = 0;
6239 int num_video_tracks = 0;
6240 for (const ContentInfo& content : remote_offer.description()->contents()) {
6241 cricket::MediaType media_type = content.media_description()->type();
6242 int num_tracks = std::max(
6243 1, static_cast<int>(content.media_description()->streams().size()));
6244 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6245 num_audio_mlines += 1;
6246 num_audio_tracks += num_tracks;
6247 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6248 num_video_mlines += 1;
6249 num_video_tracks += num_tracks;
6250 }
6251 }
6252 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6253 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6254 format = kSdpFormatReceivedComplexUnifiedPlan;
6255 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6256 format = kSdpFormatReceivedComplexPlanB;
6257 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6258 format = kSdpFormatReceivedSimple;
6259 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006260 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6261 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006262}
6263
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006264void PeerConnection::NoteUsageEvent(UsageEvent event) {
6265 RTC_DCHECK_RUN_ON(signaling_thread());
6266 usage_event_accumulator_ |= static_cast<int>(event);
6267}
6268
6269void PeerConnection::ReportUsagePattern() const {
6270 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006271 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6272 usage_event_accumulator_,
6273 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006274 const int bad_bits =
6275 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6276 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6277 const int good_bits =
6278 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6279 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6280 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6281 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6282 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006283 // If called after close(), we can't report, because observer may have
6284 // been deallocated, and therefore pointer is null. Write to log instead.
6285 if (observer_) {
6286 Observer()->OnInterestingUsage(usage_event_accumulator_);
6287 } else {
6288 RTC_LOG(LS_INFO) << "Interesting usage signature "
6289 << usage_event_accumulator_
6290 << " observed after observer shutdown";
6291 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006292 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006293}
6294
Steve Anton0ffaaa22018-02-23 10:31:30 -08006295void PeerConnection::ReportNegotiatedSdpSemantics(
6296 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006297 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006298 switch (answer.description()->msid_signaling()) {
6299 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006300 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006301 break;
6302 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006303 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006304 break;
6305 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006306 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006307 break;
6308 case cricket::kMsidSignalingMediaSection |
6309 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006310 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006311 break;
6312 default:
6313 RTC_NOTREACHED();
6314 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006315 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6316 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006317}
6318
Steve Anton75737c02017-11-06 10:37:17 -08006319// We need to check the local/remote description for the Transport instead of
6320// the session, because a new Transport added during renegotiation may have
6321// them unset while the session has them set from the previous negotiation.
6322// Not doing so may trigger the auto generation of transport description and
6323// mess up DTLS identity information, ICE credential, etc.
6324bool PeerConnection::ReadyToUseRemoteCandidate(
6325 const IceCandidateInterface* candidate,
6326 const SessionDescriptionInterface* remote_desc,
6327 bool* valid) {
6328 *valid = true;
6329
6330 const SessionDescriptionInterface* current_remote_desc =
6331 remote_desc ? remote_desc : remote_description();
6332
6333 if (!current_remote_desc) {
6334 return false;
6335 }
6336
6337 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6338 size_t remote_content_size =
6339 current_remote_desc->description()->contents().size();
6340 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006341 RTC_LOG(LS_ERROR)
6342 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6343 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006344
6345 *valid = false;
6346 return false;
6347 }
6348
6349 cricket::ContentInfo content =
6350 current_remote_desc->description()->contents()[mediacontent_index];
6351
6352 const std::string transport_name = GetTransportName(content.name);
6353 if (transport_name.empty()) {
6354 return false;
6355 }
Zhi Huange830e682018-03-30 10:48:35 -07006356 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006357}
6358
6359bool PeerConnection::SrtpRequired() const {
6360 return dtls_enabled_ ||
6361 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6362}
6363
6364void PeerConnection::OnTransportControllerGatheringState(
6365 cricket::IceGatheringState state) {
6366 RTC_DCHECK(signaling_thread()->IsCurrent());
6367 if (state == cricket::kIceGatheringGathering) {
6368 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6369 } else if (state == cricket::kIceGatheringComplete) {
6370 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6371 }
6372}
6373
6374void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006375 std::map<std::string, std::set<cricket::MediaType>>
6376 media_types_by_transport_name;
6377 for (auto transceiver : transceivers_) {
6378 if (transceiver->internal()->channel()) {
6379 const std::string& transport_name =
6380 transceiver->internal()->channel()->transport_name();
6381 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006382 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006383 }
Steve Anton75737c02017-11-06 10:37:17 -08006384 }
6385 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006386 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6387 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006388 }
Zhi Huange830e682018-03-30 10:48:35 -07006389
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006390 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006391 if (transport_name) {
6392 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006393 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006394 }
Zhi Huange830e682018-03-30 10:48:35 -07006395
Steve Antonc7b964c2018-02-01 14:39:45 -08006396 for (const auto& entry : media_types_by_transport_name) {
6397 const std::string& transport_name = entry.first;
6398 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006399 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006400 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006401 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006402 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006403 }
6404 }
6405}
6406// Walk through the ConnectionInfos to gather best connection usage
6407// for IPv4 and IPv6.
6408void PeerConnection::ReportBestConnectionState(
6409 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006410 for (const cricket::TransportChannelStats& channel_stats :
6411 stats.channel_stats) {
6412 for (const cricket::ConnectionInfo& connection_info :
6413 channel_stats.connection_infos) {
6414 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006415 continue;
6416 }
6417
Steve Antonc7b964c2018-02-01 14:39:45 -08006418 const cricket::Candidate& local = connection_info.local_candidate;
6419 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006420
6421 // Increment the counter for IceCandidatePairType.
6422 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6423 (local.type() == RELAY_PORT_TYPE &&
6424 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006425 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6426 GetIceCandidatePairCounter(local, remote),
6427 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006428 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006429 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6430 GetIceCandidatePairCounter(local, remote),
6431 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006432 } else {
6433 RTC_CHECK(0);
6434 }
Steve Anton75737c02017-11-06 10:37:17 -08006435
6436 // Increment the counter for IP type.
6437 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006438 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6439 kBestConnections_IPv4,
6440 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006441 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006442 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6443 kBestConnections_IPv6,
6444 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006445 } else {
6446 RTC_CHECK(0);
6447 }
6448
6449 return;
6450 }
6451 }
6452}
6453
6454void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006455 const cricket::TransportStats& stats,
6456 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006457 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6458 return;
6459 }
6460
6461 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6462 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6463 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6464 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6465 return;
6466 }
6467
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006468 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6469 for (cricket::MediaType media_type : media_types) {
6470 switch (media_type) {
6471 case cricket::MEDIA_TYPE_AUDIO:
6472 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6473 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6474 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6475 break;
6476 case cricket::MEDIA_TYPE_VIDEO:
6477 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6478 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6479 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6480 break;
6481 case cricket::MEDIA_TYPE_DATA:
6482 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6483 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6484 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6485 break;
6486 default:
6487 RTC_NOTREACHED();
6488 continue;
6489 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006490 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006491 }
6492
6493 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6494 for (cricket::MediaType media_type : media_types) {
6495 switch (media_type) {
6496 case cricket::MEDIA_TYPE_AUDIO:
6497 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6498 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6499 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6500 break;
6501 case cricket::MEDIA_TYPE_VIDEO:
6502 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6503 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6504 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6505 break;
6506 case cricket::MEDIA_TYPE_DATA:
6507 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6508 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6509 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6510 break;
6511 default:
6512 RTC_NOTREACHED();
6513 continue;
6514 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006515 }
Steve Anton75737c02017-11-06 10:37:17 -08006516 }
6517}
6518
6519void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6520 RTC_DCHECK(worker_thread()->IsCurrent());
6521 RTC_DCHECK(call_);
6522 call_->OnSentPacket(sent_packet);
6523}
6524
6525const std::string PeerConnection::GetTransportName(
6526 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006527 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006528 if (channel) {
6529 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006530 }
Steve Anton6fec8802017-12-04 10:37:29 -08006531 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006532 RTC_DCHECK(sctp_mid_);
6533 if (content_name == *sctp_mid_) {
6534 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006535 }
6536 }
6537 // Return an empty string if failed to retrieve the transport name.
6538 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006539}
6540
Steve Anton6fec8802017-12-04 10:37:29 -08006541void PeerConnection::DestroyTransceiverChannel(
6542 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6543 transceiver) {
6544 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006545
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006546 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006547 if (channel) {
6548 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006549 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006550 }
6551}
6552
6553void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006554 if (rtp_data_channel_) {
6555 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006556 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006557 rtp_data_channel_ = nullptr;
6558 }
6559
6560 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6561 // grab a reference to this PeerConnection. If this is called from the
6562 // PeerConnection destructor, the RefCountedObject vtable will have already
6563 // been destroyed (since it is a subclass of PeerConnection) and using
6564 // rtc::Bind will cause "Pure virtual function called" error to appear.
6565
6566 if (sctp_transport_) {
6567 OnDataChannelDestroyed();
6568 network_thread()->Invoke<void>(RTC_FROM_HERE,
6569 [this] { DestroySctpTransport_n(); });
6570 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006571
6572 if (media_transport_) {
6573 OnDataChannelDestroyed();
6574 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6575 RTC_DCHECK_RUN_ON(network_thread());
6576 TeardownMediaTransportForDataChannels_n();
6577 });
6578 }
Steve Anton6fec8802017-12-04 10:37:29 -08006579}
6580
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006581void PeerConnection::DestroyChannelInterface(
6582 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006583 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006584 switch (channel->media_type()) {
6585 case cricket::MEDIA_TYPE_AUDIO:
6586 channel_manager()->DestroyVoiceChannel(
6587 static_cast<cricket::VoiceChannel*>(channel));
6588 break;
6589 case cricket::MEDIA_TYPE_VIDEO:
6590 channel_manager()->DestroyVideoChannel(
6591 static_cast<cricket::VideoChannel*>(channel));
6592 break;
6593 case cricket::MEDIA_TYPE_DATA:
6594 channel_manager()->DestroyRtpDataChannel(
6595 static_cast<cricket::RtpDataChannel*>(channel));
6596 break;
6597 default:
6598 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6599 break;
6600 }
Zhi Huange830e682018-03-30 10:48:35 -07006601}
Steve Anton6fec8802017-12-04 10:37:29 -08006602
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006603bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006604 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006605 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006606 cricket::DtlsTransportInternal* dtls_transport,
6607 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006608 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006609 auto base_channel = GetChannel(mid);
6610 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006611 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006612 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006613 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006614 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006615 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006616
6617 call_->MediaTransportChange(media_transport);
6618
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006619 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006620}
6621
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006622PeerConnectionObserver* PeerConnection::Observer() const {
6623 // In earlier production code, the pointer was not cleared on close,
6624 // which might have led to undefined behavior if the observer was not
6625 // deallocated, or strange crashes if it was.
6626 // We use CHECK in order to catch such behavior if it exists.
6627 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6628 RTC_CHECK(observer_);
6629 return observer_;
6630}
6631
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006632CryptoOptions PeerConnection::GetCryptoOptions() {
6633 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6634 // after it has been removed.
6635 return configuration_.crypto_options.has_value()
6636 ? *configuration_.crypto_options
6637 : factory_->options().crypto_options;
6638}
6639
Harald Alvestrand89061872018-01-02 14:08:34 +01006640void PeerConnection::ClearStatsCache() {
6641 if (stats_collector_) {
6642 stats_collector_->ClearCachedStatsReport();
6643 }
6644}
6645
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006646void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006647 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6648 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006649}
6650
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006651} // namespace webrtc