blob: a6b47c16deba381e57abfbf1230118165fb158a1 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 10:37:17 -0800342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800389}
390
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100417
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100424 }
425}
426
Harald Alvestrand76829d72018-07-18 23:24:36 +0200427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 10:37:17 -0800432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800443 continue;
444 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800479 }
480 }
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 continue;
494 }
Steve Anton8a006912017-12-04 15:25:56 -0800495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800515 return false;
516 }
517 }
518 return true;
519}
520
521bool GetTrackIdBySsrc(const SessionDescription* session_description,
522 uint32_t ssrc,
523 std::string* track_id) {
524 RTC_DCHECK(track_id != NULL);
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::AudioContentDescription* audio_desc =
527 cricket::GetFirstAudioContentDescription(session_description);
528 if (audio_desc) {
529 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535
Steve Antonb1c1de12017-12-21 15:14:30 -0800536 const cricket::VideoContentDescription* video_desc =
537 cricket::GetFirstVideoContentDescription(session_description);
538 if (video_desc) {
539 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800540 if (found) {
541 *track_id = found->id;
542 return true;
543 }
544 }
545 return false;
546}
547
548// Get the SCTP port out of a SessionDescription.
549// Return -1 if not found.
550int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800551 const cricket::DataContentDescription* data_desc =
552 GetFirstDataContentDescription(session_description);
553 RTC_DCHECK(data_desc);
554 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800555 return -1;
556 }
Steve Anton75737c02017-11-06 10:37:17 -0800557 std::string value;
558 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
559 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800560 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800561 if (!codec.Matches(match_pattern)) {
562 continue;
563 }
564 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
565 return rtc::FromString<int>(value);
566 }
567 }
568 return -1;
569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800634cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
635 switch (type) {
636 case DataMessageType::kText:
637 return cricket::DMT_TEXT;
638 case DataMessageType::kBinary:
639 return cricket::DMT_BINARY;
640 case DataMessageType::kControl:
641 return cricket::DMT_CONTROL;
642 default:
643 return cricket::DMT_NONE;
644 }
645 return cricket::DMT_NONE;
646}
647
648DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
649 switch (type) {
650 case cricket::DMT_TEXT:
651 return DataMessageType::kText;
652 case cricket::DMT_BINARY:
653 return DataMessageType::kBinary;
654 case cricket::DMT_CONTROL:
655 return DataMessageType::kControl;
656 case cricket::DMT_NONE:
657 default:
658 RTC_NOTREACHED();
659 }
660 return DataMessageType::kControl;
661}
662
Steve Anton75737c02017-11-06 10:37:17 -0800663} // namespace
664
Henrik Boström31638672017-11-23 17:48:32 +0100665// Upon completion, posts a task to execute the callback of the
666// SetSessionDescriptionObserver asynchronously on the same thread. At this
667// point, the state of the peer connection might no longer reflect the effects
668// of the SetRemoteDescription operation, as the peer connection could have been
669// modified during the post.
670// TODO(hbos): Remove this class once we remove the version of
671// PeerConnectionInterface::SetRemoteDescription() that takes a
672// SetSessionDescriptionObserver as an argument.
673class PeerConnection::SetRemoteDescriptionObserverAdapter
674 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
675 public:
676 SetRemoteDescriptionObserverAdapter(
677 rtc::scoped_refptr<PeerConnection> pc,
678 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
679 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
680
681 // SetRemoteDescriptionObserverInterface implementation.
682 void OnSetRemoteDescriptionComplete(RTCError error) override {
683 if (error.ok())
684 pc_->PostSetSessionDescriptionSuccess(wrapper_);
685 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100686 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100687 }
688
689 private:
690 rtc::scoped_refptr<PeerConnection> pc_;
691 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
692};
693
deadbeef293e9262017-01-11 12:28:30 -0800694bool PeerConnectionInterface::RTCConfiguration::operator==(
695 const PeerConnectionInterface::RTCConfiguration& o) const {
696 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800698 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000699 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800701 BundlePolicy bundle_policy;
702 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700703 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
704 int ice_candidate_pool_size;
705 bool disable_ipv6;
706 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700707 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100708 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700709 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200710 absl::optional<int> screencast_min_bitrate;
711 absl::optional<bool> combined_audio_video_bwe;
712 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800713 TcpCandidatePolicy tcp_candidate_policy;
714 CandidateNetworkPolicy candidate_network_policy;
715 int audio_jitter_buffer_max_packets;
716 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100717 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800718 int ice_connection_receiving_timeout;
719 int ice_backup_candidate_pair_ping_interval;
720 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800721 bool prioritize_most_likely_ice_candidate_pairs;
722 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800723 bool prune_turn_ports;
724 bool presume_writable_when_fully_relayed;
725 bool enable_ice_renomination;
726 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200727 absl::optional<int> ice_check_interval_strong_connectivity;
728 absl::optional<int> ice_check_interval_weak_connectivity;
729 absl::optional<int> ice_check_min_interval;
730 absl::optional<int> ice_unwritable_timeout;
731 absl::optional<int> ice_unwritable_min_checks;
732 absl::optional<int> stun_candidate_keepalive_interval;
733 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200734 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800735 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200736 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700737 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700738 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700739 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700740 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100741 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800742 };
743 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
744 "Did you add something to RTCConfiguration and forget to "
745 "update operator==?");
746 return type == o.type && servers == o.servers &&
747 bundle_policy == o.bundle_policy &&
748 rtcp_mux_policy == o.rtcp_mux_policy &&
749 tcp_candidate_policy == o.tcp_candidate_policy &&
750 candidate_network_policy == o.candidate_network_policy &&
751 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
752 audio_jitter_buffer_fast_accelerate ==
753 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100754 audio_jitter_buffer_min_delay_ms ==
755 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800756 ice_connection_receiving_timeout ==
757 o.ice_connection_receiving_timeout &&
758 ice_backup_candidate_pair_ping_interval ==
759 o.ice_backup_candidate_pair_ping_interval &&
760 continual_gathering_policy == o.continual_gathering_policy &&
761 certificates == o.certificates &&
762 prioritize_most_likely_ice_candidate_pairs ==
763 o.prioritize_most_likely_ice_candidate_pairs &&
764 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800765 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700766 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100767 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800768 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800769 screencast_min_bitrate == o.screencast_min_bitrate &&
770 combined_audio_video_bwe == o.combined_audio_video_bwe &&
771 enable_dtls_srtp == o.enable_dtls_srtp &&
772 ice_candidate_pool_size == o.ice_candidate_pool_size &&
773 prune_turn_ports == o.prune_turn_ports &&
774 presume_writable_when_fully_relayed ==
775 o.presume_writable_when_fully_relayed &&
776 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800777 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800778 ice_check_interval_strong_connectivity ==
779 o.ice_check_interval_strong_connectivity &&
780 ice_check_interval_weak_connectivity ==
781 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700782 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700783 ice_unwritable_timeout == o.ice_unwritable_timeout &&
784 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800785 stun_candidate_keepalive_interval ==
786 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200787 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800788 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800789 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700790 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700791 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700792 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700793 use_media_transport_for_data_channels ==
794 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100795 crypto_options == o.crypto_options &&
796 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800797}
798
799bool PeerConnectionInterface::RTCConfiguration::operator!=(
800 const PeerConnectionInterface::RTCConfiguration& o) const {
801 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800802}
803
zhihuang8f65cdf2016-05-06 18:40:30 -0700804// Generate a RTCP CNAME when a PeerConnection is created.
805std::string GenerateRtcpCname() {
806 std::string cname;
807 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100808 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800809 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700810 }
811 return cname;
812}
813
zhihuang1c378ed2017-08-17 14:10:50 -0700814bool ValidateOfferAnswerOptions(
815 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
816 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
817 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700818}
819
zhihuang1c378ed2017-08-17 14:10:50 -0700820// From |rtc_options|, fill parts of |session_options| shared by all generated
821// m= sections (in other words, nothing that involves a map/array).
822void ExtractSharedMediaSessionOptions(
823 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
824 cricket::MediaSessionOptions* session_options) {
825 session_options->vad_enabled = rtc_options.voice_activity_detection;
826 session_options->bundle_enabled = rtc_options.use_rtp_mux;
827}
zhihuanga77e6bb2017-08-14 18:17:48 -0700828
zhihuang38ede132017-06-15 12:52:32 -0700829PeerConnection::PeerConnection(PeerConnectionFactory* factory,
830 std::unique_ptr<RtcEventLog> event_log,
831 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700833 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700834 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700835 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700836 remote_streams_(StreamCollection::Create()),
837 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000838
839PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100840 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800841 RTC_DCHECK_RUN_ON(signaling_thread());
842
Steve Anton8af21862017-12-15 11:20:13 -0800843 // Need to stop transceivers before destroying the stats collector because
844 // AudioRtpSender has a reference to the StatsCollector it will update when
845 // stopping.
846 for (auto transceiver : transceivers_) {
847 transceiver->Stop();
848 }
Steve Anton4171afb2017-11-20 10:20:22 -0800849
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700850 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800851 if (stats_collector_) {
852 stats_collector_->WaitForPendingRequest();
853 stats_collector_ = nullptr;
854 }
Steve Anton75737c02017-11-06 10:37:17 -0800855
Steve Anton8af21862017-12-15 11:20:13 -0800856 // Don't destroy BaseChannels until after stats has been cleaned up so that
857 // the last stats request can still read from the channels.
858 DestroyAllChannels();
859
Mirko Bonadei675513b2017-11-09 11:09:25 +0100860 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800861
862 webrtc_session_desc_factory_.reset();
863 sctp_invoker_.reset();
864 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800865 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800866 transport_controller_.reset();
867
deadbeef91dd5672016-05-18 16:55:30 -0700868 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700869 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700870 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700871 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700872 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700873 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800874 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700875 event_log_.reset();
876 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877}
878
Steve Anton8af21862017-12-15 11:20:13 -0800879void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800880 // Destroy video channels first since they may have a pointer to a voice
881 // channel.
882 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800883 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800884 DestroyTransceiverChannel(transceiver);
885 }
886 }
887 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800888 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800889 DestroyTransceiverChannel(transceiver);
890 }
891 }
892 DestroyDataChannel();
893}
894
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000895bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000896 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100898 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700899
900 RTCError config_error = ValidateConfiguration(configuration);
901 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100902 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700903 return false;
904 }
905
Benjamin Wrightcab58882018-05-02 15:12:47 -0700906 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100907 RTC_LOG(LS_ERROR)
908 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100909 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800910 return false;
911 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200912
Benjamin Wrightcab58882018-05-02 15:12:47 -0700913 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800914 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100915 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100916 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800917 return false;
918 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700919
Benjamin Wrightcab58882018-05-02 15:12:47 -0700920 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700921 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700922 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700923 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800924
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200925 cricket::ServerAddresses stun_servers;
926 std::vector<cricket::RelayServerConfig> turn_servers;
927
928 RTCErrorType parse_error =
929 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
930 if (parse_error != RTCErrorType::NONE) {
931 return false;
932 }
933
deadbeef91dd5672016-05-18 16:55:30 -0700934 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700935 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700936 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200937 RTC_FROM_HERE,
938 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
939 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940 return false;
941 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200942 // If initialization was successful, note if STUN or TURN servers
943 // were supplied.
944 if (!stun_servers.empty()) {
945 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
946 }
947 if (!turn_servers.empty()) {
948 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
949 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700951 // Send information about IPv4/IPv6 status.
952 PeerConnectionAddressFamilyCounter address_family;
953 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
954 address_family = kPeerConnection_IPv6;
955 } else {
956 address_family = kPeerConnection_IPv4;
957 }
958 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
959 kPeerConnectionAddressFamilyCounter_Max);
960
Zhi Huange830e682018-03-30 10:48:35 -0700961 const PeerConnectionFactoryInterface::Options& options = factory_->options();
962
Steve Anton75737c02017-11-06 10:37:17 -0800963 // RFC 3264: The numeric value of the session id and version in the
964 // o line MUST be representable with a "64 bit signed integer".
965 // Due to this constraint session id |session_id_| is max limited to
966 // LLONG_MAX.
967 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700968 JsepTransportController::Config config;
969 config.redetermine_role_on_ice_restart =
970 configuration.redetermine_role_on_ice_restart;
971 config.ssl_max_version = factory_->options().ssl_max_version;
972 config.disable_encryption = options.disable_encryption;
973 config.bundle_policy = configuration.bundle_policy;
974 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700975 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
976 // stub.
977 config.crypto_options = configuration.crypto_options.has_value()
978 ? *configuration.crypto_options
979 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700980 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700981 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700982#if defined(ENABLE_EXTERNAL_AUTH)
983 config.enable_external_auth = true;
984#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700985 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700986
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700987 if (configuration.use_media_transport ||
988 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700989 if (!factory_->media_transport_factory()) {
990 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700991 << "PeerConnecton is initialized with use_media_transport = true or "
992 << "use_media_transport_for_data_channels = true "
993 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700994 return false;
995 }
996
997 config.media_transport_factory = factory_->media_transport_factory();
998 }
999
Zhi Huange830e682018-03-30 10:48:35 -07001000 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001001 signaling_thread(), network_thread(), port_allocator_.get(),
1002 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001003 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001004 this, &PeerConnection::OnTransportControllerConnectionState);
1005 transport_controller_->SignalStandardizedIceConnectionState.connect(
1006 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001007 transport_controller_->SignalConnectionState.connect(
1008 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001009 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001010 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001011 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001012 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001013 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001014 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1015 transport_controller_->SignalDtlsHandshakeError.connect(
1016 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1017
1018 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001019
deadbeefab9b2d12015-10-14 11:33:11 -07001020 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001021 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022
Steve Antonba818672017-11-06 10:21:57 -08001023 configuration_ = configuration;
1024
Steve Anton75737c02017-11-06 10:37:17 -08001025 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1026 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1027 if (!configuration.certificates.empty()) {
1028 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1029 // just picking the first one. The decision should be made based on the DTLS
1030 // handshake. The DTLS negotiations need to know about all certificates.
1031 certificate = configuration.certificates[0];
1032 }
1033
Steve Antond25da372017-11-06 14:50:29 -08001034 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001035
1036 if (options.disable_encryption) {
1037 dtls_enabled_ = false;
1038 } else {
1039 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001040 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001041 // |configuration| can override the default |dtls_enabled_| value.
1042 if (configuration.enable_dtls_srtp) {
1043 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1044 }
1045 }
1046
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001047 if (configuration.use_media_transport_for_data_channels) {
1048 if (configuration.enable_rtp_data_channel) {
1049 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1050 "use_media_transport_for_data_channels are "
1051 "incompatible and cannot both be set to true";
1052 return false;
1053 }
1054 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1055 } else if (configuration.enable_rtp_data_channel) {
1056 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1057 // set. It takes precendence over the disable_sctp_data_channels
1058 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001059 data_channel_type_ = cricket::DCT_RTP;
1060 } else {
1061 // DTLS has to be enabled to use SCTP.
1062 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1063 data_channel_type_ = cricket::DCT_SCTP;
1064 }
1065 }
1066
1067 video_options_.screencast_min_bitrate_kbps =
1068 configuration.screencast_min_bitrate;
1069 audio_options_.combined_audio_video_bwe =
1070 configuration.combined_audio_video_bwe;
1071
1072 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001073 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001074
1075 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001076 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001077
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001078 audio_options_.audio_jitter_buffer_min_delay_ms =
1079 configuration.audio_jitter_buffer_min_delay_ms;
1080
Steve Anton75737c02017-11-06 10:37:17 -08001081 // Whether the certificate generator/certificate is null or not determines
1082 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1083 // the right instructions by clearing the variables if needed.
1084 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001085 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001086 certificate = nullptr;
1087 } else if (certificate) {
1088 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001089 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001090 }
1091
1092 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1093 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001094 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001095 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1096 this, &PeerConnection::OnCertificateReady);
1097
1098 if (options.disable_encryption) {
1099 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1100 }
1101
1102 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001103 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104
Steve Anton4171afb2017-11-20 10:20:22 -08001105 // Add default audio/video transceivers for Plan B SDP.
1106 if (!IsUnifiedPlan()) {
1107 transceivers_.push_back(
1108 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1109 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1110 transceivers_.push_back(
1111 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1112 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1113 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001114 int delay_ms =
1115 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001116 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1117 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001118 return true;
1119}
1120
Steve Anton038834f2017-07-14 15:59:59 -07001121RTCError PeerConnection::ValidateConfiguration(
1122 const RTCConfiguration& config) const {
1123 if (config.ice_regather_interval_range &&
1124 config.continual_gathering_policy == GATHER_ONCE) {
1125 return RTCError(RTCErrorType::INVALID_PARAMETER,
1126 "ice_regather_interval_range specified but continual "
1127 "gathering policy is GATHER_ONCE");
1128 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001129 auto result =
1130 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1131 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001132}
1133
Yves Gerey665174f2018-06-19 15:03:05 +02001134rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001135 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1136 "Plan SdpSemantics. Please use GetSenders "
1137 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001138 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001139}
1140
Yves Gerey665174f2018-06-19 15:03:05 +02001141rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001142 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1143 "Plan SdpSemantics. Please use GetReceivers "
1144 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001145 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146}
1147
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001148bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001149 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1150 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001151 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001152 if (IsClosed()) {
1153 return false;
1154 }
deadbeefab9b2d12015-10-14 11:33:11 -07001155 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156 return false;
1157 }
deadbeefab9b2d12015-10-14 11:33:11 -07001158
1159 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001160 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1161 observer->SignalAudioTrackAdded.connect(this,
1162 &PeerConnection::OnAudioTrackAdded);
1163 observer->SignalAudioTrackRemoved.connect(
1164 this, &PeerConnection::OnAudioTrackRemoved);
1165 observer->SignalVideoTrackAdded.connect(this,
1166 &PeerConnection::OnVideoTrackAdded);
1167 observer->SignalVideoTrackRemoved.connect(
1168 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001169 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001170
deadbeefab9b2d12015-10-14 11:33:11 -07001171 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001172 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001173 }
1174 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001175 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001176 }
1177
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001178 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001179 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001180 return true;
1181}
1182
1183void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001184 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1185 "Plan SdpSemantics. Please use RemoveTrack "
1186 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001187 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001188 if (!IsClosed()) {
1189 for (const auto& track : local_stream->GetAudioTracks()) {
1190 RemoveAudioTrack(track.get(), local_stream);
1191 }
1192 for (const auto& track : local_stream->GetVideoTracks()) {
1193 RemoveVideoTrack(track.get(), local_stream);
1194 }
deadbeefab9b2d12015-10-14 11:33:11 -07001195 }
deadbeefab9b2d12015-10-14 11:33:11 -07001196 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001197 stream_observers_.erase(
1198 std::remove_if(
1199 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001200 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001201 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001202 }),
1203 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001204
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001205 if (IsClosed()) {
1206 return;
1207 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001208 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209}
1210
Steve Anton2d6c76a2018-01-05 17:10:52 -08001211RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001212 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001213 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001214 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001215 if (!track) {
1216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1217 }
1218 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1219 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1221 "Track has invalid kind: " + track->kind());
1222 }
Steve Antonf9381f02017-12-14 10:23:57 -08001223 if (IsClosed()) {
1224 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1225 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001226 }
Steve Anton4171afb2017-11-20 10:20:22 -08001227 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001228 LOG_AND_RETURN_ERROR(
1229 RTCErrorType::INVALID_PARAMETER,
1230 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001231 }
Steve Antonf9381f02017-12-14 10:23:57 -08001232 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001233 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1234 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001235 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001236 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001237 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001238 }
1239 return sender_or_error;
1240}
deadbeefe1f9d832016-01-14 15:35:42 -08001241
Steve Antonf9381f02017-12-14 10:23:57 -08001242RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1243PeerConnection::AddTrackPlanB(
1244 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001245 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001246 if (stream_ids.size() > 1u) {
1247 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1248 "AddTrack with more than one stream is not "
1249 "supported with Plan B semantics.");
1250 }
1251 std::vector<std::string> adjusted_stream_ids = stream_ids;
1252 if (adjusted_stream_ids.empty()) {
1253 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1254 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001255 cricket::MediaType media_type =
1256 (track->kind() == MediaStreamTrackInterface::kAudioKind
1257 ? cricket::MEDIA_TYPE_AUDIO
1258 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001259 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001260 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001261 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001262 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001263 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001264 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001265 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001266 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001267 if (sender_info) {
1268 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001269 }
Steve Antonf9381f02017-12-14 10:23:57 -08001270 } else {
1271 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001272 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001273 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001274 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001275 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001276 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001277 if (sender_info) {
1278 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001279 }
deadbeefe1f9d832016-01-14 15:35:42 -08001280 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001281 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001282}
deadbeefe1f9d832016-01-14 15:35:42 -08001283
Steve Antonf9381f02017-12-14 10:23:57 -08001284RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1285PeerConnection::AddTrackUnifiedPlan(
1286 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001287 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001288 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1289 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001290 RTC_LOG(LS_INFO) << "Reusing an existing "
1291 << cricket::MediaTypeToString(transceiver->media_type())
1292 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001293 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001294 transceiver->internal()->set_direction(
1295 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001296 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001297 transceiver->internal()->set_direction(
1298 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001299 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001300 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001301 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001302 } else {
1303 cricket::MediaType media_type =
1304 (track->kind() == MediaStreamTrackInterface::kAudioKind
1305 ? cricket::MEDIA_TYPE_AUDIO
1306 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001307 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1308 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001309 std::string sender_id = track->id();
1310 // Avoid creating a sender with an existing ID by generating a random ID.
1311 // This can happen if this is the second time AddTrack has created a sender
1312 // for this track.
1313 if (FindSenderById(sender_id)) {
1314 sender_id = rtc::CreateRandomUuid();
1315 }
Florent Castelli892acf02018-10-01 22:47:20 +02001316 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001317 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1318 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001319 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001320 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001321 }
Steve Antonf9381f02017-12-14 10:23:57 -08001322 return transceiver->sender();
1323}
1324
1325rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1326PeerConnection::FindFirstTransceiverForAddedTrack(
1327 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1328 RTC_DCHECK(track);
1329 for (auto transceiver : transceivers_) {
1330 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001331 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001332 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001333 !transceiver->internal()->has_ever_been_used_to_send() &&
1334 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001335 return transceiver;
1336 }
1337 }
1338 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001339}
1340
1341bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1342 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001343 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001344}
1345
Steve Anton24db5732018-07-23 10:27:33 -07001346RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001347 rtc::scoped_refptr<RtpSenderInterface> sender) {
1348 if (!sender) {
1349 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1350 }
deadbeefe1f9d832016-01-14 15:35:42 -08001351 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001352 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1353 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001354 }
Steve Antonf9381f02017-12-14 10:23:57 -08001355 if (IsUnifiedPlan()) {
1356 auto transceiver = FindTransceiverBySender(sender);
1357 if (!transceiver || !sender->track()) {
1358 return RTCError::OK();
1359 }
1360 sender->SetTrack(nullptr);
1361 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001362 transceiver->internal()->set_direction(
1363 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001364 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001365 transceiver->internal()->set_direction(
1366 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001367 }
Steve Anton4171afb2017-11-20 10:20:22 -08001368 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001369 bool removed;
1370 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1371 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1372 } else {
1373 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1374 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1375 }
1376 if (!removed) {
1377 LOG_AND_RETURN_ERROR(
1378 RTCErrorType::INVALID_PARAMETER,
1379 "Couldn't find sender " + sender->id() + " to remove.");
1380 }
Steve Anton4171afb2017-11-20 10:20:22 -08001381 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001382 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001383 return RTCError::OK();
1384}
1385
1386rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1387PeerConnection::FindTransceiverBySender(
1388 rtc::scoped_refptr<RtpSenderInterface> sender) {
1389 for (auto transceiver : transceivers_) {
1390 if (transceiver->sender() == sender) {
1391 return transceiver;
1392 }
1393 }
1394 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001395}
1396
Steve Anton9158ef62017-11-27 13:01:52 -08001397RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1398PeerConnection::AddTransceiver(
1399 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1400 return AddTransceiver(track, RtpTransceiverInit());
1401}
1402
1403RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1404PeerConnection::AddTransceiver(
1405 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1406 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001407 RTC_CHECK(IsUnifiedPlan())
1408 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001409 if (!track) {
1410 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1411 }
1412 cricket::MediaType media_type;
1413 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1414 media_type = cricket::MEDIA_TYPE_AUDIO;
1415 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1416 media_type = cricket::MEDIA_TYPE_VIDEO;
1417 } else {
1418 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1419 "Track kind is not audio or video");
1420 }
1421 return AddTransceiver(media_type, track, init);
1422}
1423
1424RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1425PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1426 return AddTransceiver(media_type, RtpTransceiverInit());
1427}
1428
1429RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1430PeerConnection::AddTransceiver(cricket::MediaType media_type,
1431 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001432 RTC_CHECK(IsUnifiedPlan())
1433 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001434 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1435 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1436 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1437 "media type is not audio or video");
1438 }
1439 return AddTransceiver(media_type, nullptr, init);
1440}
1441
1442RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1443PeerConnection::AddTransceiver(
1444 cricket::MediaType media_type,
1445 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001446 const RtpTransceiverInit& init,
1447 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001448 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1449 media_type == cricket::MEDIA_TYPE_VIDEO));
1450 if (track) {
1451 RTC_DCHECK_EQ(media_type,
1452 (track->kind() == MediaStreamTrackInterface::kAudioKind
1453 ? cricket::MEDIA_TYPE_AUDIO
1454 : cricket::MEDIA_TYPE_VIDEO));
1455 }
1456
1457 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001458 if (init.send_encodings.size() > 1) {
1459 LOG_AND_RETURN_ERROR(
1460 RTCErrorType::UNSUPPORTED_PARAMETER,
1461 "Attempted to create an encoder with more than 1 encoding parameter.");
1462 }
1463
1464 for (const auto& encoding : init.send_encodings) {
1465 if (encoding.ssrc.has_value()) {
1466 LOG_AND_RETURN_ERROR(
1467 RTCErrorType::UNSUPPORTED_PARAMETER,
1468 "Attempted to set an unimplemented parameter of RtpParameters.");
1469 }
1470 }
1471
1472 RtpParameters parameters;
1473 parameters.encodings = init.send_encodings;
1474 if (UnimplementedRtpParameterHasValue(parameters)) {
1475 LOG_AND_RETURN_ERROR(
1476 RTCErrorType::UNSUPPORTED_PARAMETER,
1477 "Attempted to set an unimplemented parameter of RtpParameters.");
1478 }
Steve Anton9158ef62017-11-27 13:01:52 -08001479
Steve Anton3d954a62018-04-02 11:27:23 -07001480 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1481 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001482 // Set the sender ID equal to the track ID if the track is specified unless
1483 // that sender ID is already in use.
1484 std::string sender_id =
1485 (track && !FindSenderById(track->id()) ? track->id()
1486 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001487 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1488 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001489 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1490 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1491 transceiver->internal()->set_direction(init.direction);
1492
Steve Anton22da89f2018-01-25 13:58:07 -08001493 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001494 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001495 }
Steve Antonf9381f02017-12-14 10:23:57 -08001496
1497 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1498}
1499
Steve Anton02ee47c2018-01-10 16:26:06 -08001500rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1501PeerConnection::CreateSender(
1502 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001503 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001504 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001505 const std::vector<std::string>& stream_ids,
1506 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001507 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001508 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1509 RTC_DCHECK(!track ||
1510 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1511 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1512 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001513 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001514 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001515 } else {
1516 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1517 RTC_DCHECK(!track ||
1518 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1519 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001520 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001521 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001522 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001523 bool set_track_succeeded = sender->SetTrack(track);
1524 RTC_DCHECK(set_track_succeeded);
1525 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001526 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001527 return sender;
1528}
1529
1530rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1531PeerConnection::CreateReceiver(cricket::MediaType media_type,
1532 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001533 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1534 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001535 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001536 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001537 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1538 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001539 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001540 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001541 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001542 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001543 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1544 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001545 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001546 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001547 return receiver;
1548}
1549
1550rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1551PeerConnection::CreateAndAddTransceiver(
1552 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1553 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1554 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001555 // Ensure that the new sender does not have an ID that is already in use by
1556 // another sender.
1557 // Allow receiver IDs to conflict since those come from remote SDP (which
1558 // could be invalid, but should not cause a crash).
1559 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001560 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1561 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001562 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001563 transceiver->internal()->SignalNegotiationNeeded.connect(
1564 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001565 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001566}
1567
Steve Anton52d86772018-02-20 15:48:12 -08001568void PeerConnection::OnNegotiationNeeded() {
1569 RTC_DCHECK_RUN_ON(signaling_thread());
1570 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001571 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001572}
1573
deadbeeffac06552015-11-25 11:26:01 -08001574rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001575 const std::string& kind,
1576 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001577 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1578 "Plan SdpSemantics. Please use AddTransceiver "
1579 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001580 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001581 if (IsClosed()) {
1582 return nullptr;
1583 }
Steve Anton4171afb2017-11-20 10:20:22 -08001584
Seth Hampson5b4f0752018-04-02 16:31:36 -07001585 // Internally we need to have one stream with Plan B semantics, so we
1586 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001587 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001588 if (stream_id.empty()) {
1589 stream_ids.push_back(rtc::CreateRandomUuid());
1590 RTC_LOG(LS_INFO)
1591 << "No stream_id specified for sender. Generated stream ID: "
1592 << stream_ids[0];
1593 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001594 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001595 }
1596
Steve Anton4171afb2017-11-20 10:20:22 -08001597 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001598 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001599 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001600 auto* audio_sender = new AudioRtpSender(
1601 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001602 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001603 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001604 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001605 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001606 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001607 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001608 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001609 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001610 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001611 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001612 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001613 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001614 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001615 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001616 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001617 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001618
deadbeefe1f9d832016-01-14 15:35:42 -08001619 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001620}
1621
deadbeef70ab1a12015-09-28 16:53:55 -07001622std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1623 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001624 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001625 for (auto sender : GetSendersInternal()) {
1626 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001627 }
1628 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001629}
1630
Steve Anton4171afb2017-11-20 10:20:22 -08001631std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1632PeerConnection::GetSendersInternal() const {
1633 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1634 all_senders;
1635 for (auto transceiver : transceivers_) {
1636 auto senders = transceiver->internal()->senders();
1637 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1638 }
1639 return all_senders;
1640}
1641
deadbeef70ab1a12015-09-28 16:53:55 -07001642std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1643PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001644 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001645 for (const auto& receiver : GetReceiversInternal()) {
1646 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001647 }
1648 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001649}
1650
Steve Anton4171afb2017-11-20 10:20:22 -08001651std::vector<
1652 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1653PeerConnection::GetReceiversInternal() const {
1654 std::vector<
1655 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1656 all_receivers;
1657 for (auto transceiver : transceivers_) {
1658 auto receivers = transceiver->internal()->receivers();
1659 all_receivers.insert(all_receivers.end(), receivers.begin(),
1660 receivers.end());
1661 }
1662 return all_receivers;
1663}
1664
Steve Anton9158ef62017-11-27 13:01:52 -08001665std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1666PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001667 RTC_CHECK(IsUnifiedPlan())
1668 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001669 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1670 for (auto transceiver : transceivers_) {
1671 all_transceivers.push_back(transceiver);
1672 }
1673 return all_transceivers;
1674}
1675
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001676bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001677 MediaStreamTrackInterface* track,
1678 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001679 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001680 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001681 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001682 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001683 return false;
1684 }
1685
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001686 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001687 // The StatsCollector is used to tell if a track is valid because it may
1688 // remember tracks that the PeerConnection previously removed.
1689 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001690 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1691 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001692 return false;
1693 }
Steve Antonad182762018-09-05 20:22:40 +00001694 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1695 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001696 return true;
1697}
1698
hbos74e1a4f2016-09-15 23:33:01 -07001699void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001700 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001701 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001702 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001703 stats_collector_->GetStatsReport(callback);
1704}
1705
Henrik Boström1df1bf82018-03-20 13:24:20 +01001706void PeerConnection::GetStats(
1707 rtc::scoped_refptr<RtpSenderInterface> selector,
1708 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1709 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1710 RTC_DCHECK(callback);
1711 RTC_DCHECK(stats_collector_);
1712 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1713 if (selector) {
1714 for (const auto& proxy_transceiver : transceivers_) {
1715 for (const auto& proxy_sender :
1716 proxy_transceiver->internal()->senders()) {
1717 if (proxy_sender == selector) {
1718 internal_sender = proxy_sender->internal();
1719 break;
1720 }
1721 }
1722 if (internal_sender)
1723 break;
1724 }
1725 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001726 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001727 // belong to the PeerConnection (in Plan B, senders can be removed from the
1728 // PeerConnection). This means that "all the stats objects representing the
1729 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1730 // produces an empty stats report.
1731 stats_collector_->GetStatsReport(internal_sender, callback);
1732}
1733
1734void PeerConnection::GetStats(
1735 rtc::scoped_refptr<RtpReceiverInterface> selector,
1736 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1737 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1738 RTC_DCHECK(callback);
1739 RTC_DCHECK(stats_collector_);
1740 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1741 if (selector) {
1742 for (const auto& proxy_transceiver : transceivers_) {
1743 for (const auto& proxy_receiver :
1744 proxy_transceiver->internal()->receivers()) {
1745 if (proxy_receiver == selector) {
1746 internal_receiver = proxy_receiver->internal();
1747 break;
1748 }
1749 }
1750 if (internal_receiver)
1751 break;
1752 }
1753 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001754 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001755 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1756 // the PeerConnection). This means that "all the stats objects representing
1757 // the selector" is an empty set. Invoking GetStatsReport() with a null
1758 // selector produces an empty stats report.
1759 stats_collector_->GetStatsReport(internal_receiver, callback);
1760}
1761
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001762PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1763 return signaling_state_;
1764}
1765
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001766PeerConnectionInterface::IceConnectionState
1767PeerConnection::ice_connection_state() {
1768 return ice_connection_state_;
1769}
1770
Alex Loiko9289eda2018-11-23 16:18:59 +00001771PeerConnectionInterface::IceConnectionState
1772PeerConnection::standardized_ice_connection_state() {
1773 return standardized_ice_connection_state_;
1774}
1775
Jonas Olsson635474e2018-10-18 15:58:17 +02001776PeerConnectionInterface::PeerConnectionState
1777PeerConnection::peer_connection_state() {
1778 return connection_state_;
1779}
1780
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781PeerConnectionInterface::IceGatheringState
1782PeerConnection::ice_gathering_state() {
1783 return ice_gathering_state_;
1784}
1785
Yves Gerey665174f2018-06-19 15:03:05 +02001786rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001787 const std::string& label,
1788 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001789 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001790
deadbeefab9b2d12015-10-14 11:33:11 -07001791 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001792
kwibergd1fe2812016-04-27 06:47:29 -07001793 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001794 if (config) {
1795 internal_config.reset(new InternalDataChannelInit(*config));
1796 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001797 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001798 InternalCreateDataChannel(label, internal_config.get()));
1799 if (!channel.get()) {
1800 return nullptr;
1801 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001802
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001803 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1804 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001805 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001806 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001807 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001808 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001809 return DataChannelProxy::Create(signaling_thread(), channel.get());
1810}
1811
1812void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001813 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001814 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001815
nisse7ce109a2017-01-31 00:57:56 -08001816 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001817 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001818 return;
1819 }
deadbeefab9b2d12015-10-14 11:33:11 -07001820
Steve Anton8d3444d2017-10-20 15:30:51 -07001821 if (IsClosed()) {
1822 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001823 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001824 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001825 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001826 return;
1827 }
1828
zhihuang1c378ed2017-08-17 14:10:50 -07001829 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001830 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001831 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001832 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001833 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001834 return;
1835 }
1836
Steve Anton22da89f2018-01-25 13:58:07 -08001837 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1838 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1839 if (IsUnifiedPlan()) {
1840 RTCError error = HandleLegacyOfferOptions(options);
1841 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001842 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001843 return;
1844 }
1845 }
1846
zhihuang1c378ed2017-08-17 14:10:50 -07001847 cricket::MediaSessionOptions session_options;
1848 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001849 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001850}
1851
Steve Anton22da89f2018-01-25 13:58:07 -08001852RTCError PeerConnection::HandleLegacyOfferOptions(
1853 const RTCOfferAnswerOptions& options) {
1854 RTC_DCHECK(IsUnifiedPlan());
1855
1856 if (options.offer_to_receive_audio == 0) {
1857 RemoveRecvDirectionFromReceivingTransceiversOfType(
1858 cricket::MEDIA_TYPE_AUDIO);
1859 } else if (options.offer_to_receive_audio == 1) {
1860 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1861 } else if (options.offer_to_receive_audio > 1) {
1862 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1863 "offer_to_receive_audio > 1 is not supported.");
1864 }
1865
1866 if (options.offer_to_receive_video == 0) {
1867 RemoveRecvDirectionFromReceivingTransceiversOfType(
1868 cricket::MEDIA_TYPE_VIDEO);
1869 } else if (options.offer_to_receive_video == 1) {
1870 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1871 } else if (options.offer_to_receive_video > 1) {
1872 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1873 "offer_to_receive_video > 1 is not supported.");
1874 }
1875
1876 return RTCError::OK();
1877}
1878
1879void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1880 cricket::MediaType media_type) {
1881 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001882 RtpTransceiverDirection new_direction =
1883 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1884 if (new_direction != transceiver->direction()) {
1885 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1886 << " transceiver (MID="
1887 << transceiver->mid().value_or("<not set>") << ") from "
1888 << RtpTransceiverDirectionToString(
1889 transceiver->direction())
1890 << " to "
1891 << RtpTransceiverDirectionToString(new_direction)
1892 << " since CreateOffer specified offer_to_receive=0";
1893 transceiver->internal()->set_direction(new_direction);
1894 }
Steve Anton22da89f2018-01-25 13:58:07 -08001895 }
1896}
1897
1898void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1899 cricket::MediaType media_type) {
1900 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001901 RTC_LOG(LS_INFO)
1902 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1903 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001904 RtpTransceiverInit init;
1905 init.direction = RtpTransceiverDirection::kRecvOnly;
1906 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1907 }
1908}
1909
1910std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1911PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1912 std::vector<
1913 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1914 receiving_transceivers;
1915 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001916 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001917 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1918 receiving_transceivers.push_back(transceiver);
1919 }
1920 }
1921 return receiving_transceivers;
1922}
1923
htaa2a49d92016-03-04 02:51:39 -08001924void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1925 const RTCOfferAnswerOptions& options) {
1926 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001927 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001928 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001929 return;
1930 }
1931
Steve Antondffead82018-02-06 10:31:29 -08001932 if (!(signaling_state_ == kHaveRemoteOffer ||
1933 signaling_state_ == kHaveLocalPrAnswer)) {
1934 std::string error =
1935 "PeerConnection cannot create an answer in a state other than "
1936 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001937 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001938 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001939 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001940 return;
1941 }
1942
Steve Antondffead82018-02-06 10:31:29 -08001943 // The remote description should be set if we're in the right state.
1944 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001945
Steve Anton22da89f2018-01-25 13:58:07 -08001946 if (IsUnifiedPlan()) {
1947 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1948 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1949 "supported with Unified Plan semantics. Use the "
1950 "RtpTransceiver API instead.";
1951 }
1952 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1953 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1954 "supported with Unified Plan semantics. Use the "
1955 "RtpTransceiver API instead.";
1956 }
1957 }
1958
htaa2a49d92016-03-04 02:51:39 -08001959 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001960 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001961
Steve Antond25da372017-11-06 14:50:29 -08001962 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001963}
1964
1965void PeerConnection::SetLocalDescription(
1966 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001967 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001968 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001969
Steve Anton80dd7b52018-02-16 17:08:42 -08001970 // The SetLocalDescription contract is that we take ownership of the session
1971 // description regardless of the outcome, so wrap it in a unique_ptr right
1972 // away. Ideally, SetLocalDescription's signature will be changed to take the
1973 // description as a unique_ptr argument to formalize this agreement.
1974 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1975
nisse7ce109a2017-01-31 00:57:56 -08001976 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001977 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001978 return;
1979 }
Steve Anton8a006912017-12-04 15:25:56 -08001980
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001981 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001982 PostSetSessionDescriptionFailure(
1983 observer,
1984 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001985 return;
1986 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001987
Steve Anton80dd7b52018-02-16 17:08:42 -08001988 // If a session error has occurred the PeerConnection is in a possibly
1989 // inconsistent state so fail right away.
1990 if (session_error() != SessionError::kNone) {
1991 std::string error_message = GetSessionErrorMsg();
1992 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001993 PostSetSessionDescriptionFailure(
1994 observer,
1995 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001996 return;
1997 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001998
Steve Anton80dd7b52018-02-16 17:08:42 -08001999 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2000 if (!error.ok()) {
2001 std::string error_message = GetSetDescriptionErrorMessage(
2002 cricket::CS_LOCAL, desc->GetType(), error);
2003 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002004 PostSetSessionDescriptionFailure(
2005 observer,
2006 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002007 return;
2008 }
2009
2010 // Grab the description type before moving ownership to ApplyLocalDescription,
2011 // which may destroy it before returning.
2012 const SdpType type = desc->GetType();
2013
2014 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002015 // |desc| may be destroyed at this point.
2016
2017 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002018 // If ApplyLocalDescription fails, the PeerConnection could be in an
2019 // inconsistent state, so act conservatively here and set the session error
2020 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2021 SetSessionError(SessionError::kContent, error.message());
2022 std::string error_message =
2023 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2024 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002025 PostSetSessionDescriptionFailure(
2026 observer,
2027 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002028 return;
2029 }
Steve Anton8a006912017-12-04 15:25:56 -08002030 RTC_DCHECK(local_description());
2031
2032 PostSetSessionDescriptionSuccess(observer);
2033
Steve Antonad182762018-09-05 20:22:40 +00002034 // MaybeStartGathering needs to be called after posting
2035 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2036 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002037 transport_controller_->MaybeStartGathering();
2038
Steve Antona3a92c22017-12-07 10:27:41 -08002039 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002040 // TODO(deadbeef): We already had to hop to the network thread for
2041 // MaybeStartGathering...
2042 network_thread()->Invoke<void>(
2043 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2044 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002045 // Make UMA notes about what was agreed to.
2046 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002047 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002048 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002049}
2050
2051RTCError PeerConnection::ApplyLocalDescription(
2052 std::unique_ptr<SessionDescriptionInterface> desc) {
2053 RTC_DCHECK_RUN_ON(signaling_thread());
2054 RTC_DCHECK(desc);
2055
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002056 // Update stats here so that we have the most recent stats for tracks and
2057 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002058 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002059
Steve Antondcc3c022017-12-22 16:02:54 -08002060 // Take a reference to the old local description since it's used below to
2061 // compare against the new local description. When setting the new local
2062 // description, grab ownership of the replaced session description in case it
2063 // is the same as |old_local_description|, to keep it alive for the duration
2064 // of the method.
2065 const SessionDescriptionInterface* old_local_description =
2066 local_description();
2067 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002068 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002069 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002070 replaced_local_description = pending_local_description_
2071 ? std::move(pending_local_description_)
2072 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002073 current_local_description_ = std::move(desc);
2074 pending_local_description_ = nullptr;
2075 current_remote_description_ = std::move(pending_remote_description_);
2076 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002077 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002078 pending_local_description_ = std::move(desc);
2079 }
2080 // The session description to apply now must be accessed by
2081 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002082 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002083
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002084 if (!is_caller_) {
2085 if (remote_description()) {
2086 // Remote description was applied first, so this PC is the callee.
2087 is_caller_ = false;
2088 } else {
2089 // Local description is applied first, so this PC is the caller.
2090 is_caller_ = true;
2091 }
2092 }
2093
Zhi Huange830e682018-03-30 10:48:35 -07002094 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2095 if (!error.ok()) {
2096 return error;
2097 }
2098
Steve Antondcc3c022017-12-22 16:02:54 -08002099 if (IsUnifiedPlan()) {
2100 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002101 cricket::CS_LOCAL, *local_description(), old_local_description,
2102 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002103 if (!error.ok()) {
2104 return error;
2105 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002106 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2107 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002108 for (auto transceiver : transceivers_) {
2109 const ContentInfo* content =
2110 FindMediaSectionForTransceiver(transceiver, local_description());
2111 if (!content) {
2112 continue;
2113 }
2114 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002115 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2116 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002117 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002118 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2119 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2120 // "recvonly", process the removal of a remote track for the media
2121 // description, given transceiver, removeList, and muteTracks.
2122 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2123 (transceiver->internal()->fired_direction() &&
2124 RtpTransceiverDirectionHasRecv(
2125 *transceiver->internal()->fired_direction()))) {
2126 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2127 &removed_streams);
2128 }
2129 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2130 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002131 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002132 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002133 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002134 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002135 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002136 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002137 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002138 }
2139 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002140 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002141 }
2142 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002143 // Media channels will be created only when offer is set. These may use new
2144 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002145 if (type == SdpType::kOffer) {
2146 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2147 // description is applied. Restore back to old description.
2148 RTCError error = CreateChannels(*local_description()->description());
2149 if (!error.ok()) {
2150 return error;
2151 }
2152 }
Steve Antondcc3c022017-12-22 16:02:54 -08002153 // Remove unused channels if MediaContentDescription is rejected.
2154 RemoveUnusedChannels(local_description()->description());
2155 }
Steve Anton8a006912017-12-04 15:25:56 -08002156
Zhi Huange830e682018-03-30 10:48:35 -07002157 error = UpdateSessionState(type, cricket::CS_LOCAL,
2158 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002159 if (!error.ok()) {
2160 return error;
2161 }
Steve Antondcc3c022017-12-22 16:02:54 -08002162
Steve Anton8a006912017-12-04 15:25:56 -08002163 if (remote_description()) {
2164 // Now that we have a local description, we can push down remote candidates.
2165 UseCandidatesInSessionDescription(remote_description());
2166 }
2167
2168 pending_ice_restarts_.clear();
2169 if (session_error() != SessionError::kNone) {
2170 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2171 }
2172
deadbeefab9b2d12015-10-14 11:33:11 -07002173 // If setting the description decided our SSL role, allocate any necessary
2174 // SCTP sids.
2175 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002176 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002177 AllocateSctpSids(role);
2178 }
2179
Steve Antond3679212018-01-17 17:41:02 -08002180 if (IsUnifiedPlan()) {
2181 for (auto transceiver : transceivers_) {
2182 const ContentInfo* content =
2183 FindMediaSectionForTransceiver(transceiver, local_description());
2184 if (!content) {
2185 continue;
2186 }
Steve Anton74255ff2018-01-24 18:32:57 -08002187 const auto& streams = content->media_description()->streams();
2188 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002189 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002190 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002191 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002192 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002193 } else {
2194 // 0 is a special value meaning "this sender has no associated send
2195 // stream". Need to call this so the sender won't attempt to configure
2196 // a no longer existing stream and run into DCHECKs in the lower
2197 // layers.
2198 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002199 }
2200 }
2201 } else {
2202 // Plan B semantics.
2203
Steve Antondcc3c022017-12-22 16:02:54 -08002204 // Update state and SSRC of local MediaStreams and DataChannels based on the
2205 // local session description.
2206 const cricket::ContentInfo* audio_content =
2207 GetFirstAudioContent(local_description()->description());
2208 if (audio_content) {
2209 if (audio_content->rejected) {
2210 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2211 } else {
2212 const cricket::AudioContentDescription* audio_desc =
2213 audio_content->media_description()->as_audio();
2214 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2215 }
deadbeeffaac4972015-11-12 15:33:07 -08002216 }
deadbeefab9b2d12015-10-14 11:33:11 -07002217
Steve Antondcc3c022017-12-22 16:02:54 -08002218 const cricket::ContentInfo* video_content =
2219 GetFirstVideoContent(local_description()->description());
2220 if (video_content) {
2221 if (video_content->rejected) {
2222 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2223 } else {
2224 const cricket::VideoContentDescription* video_desc =
2225 video_content->media_description()->as_video();
2226 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2227 }
deadbeeffaac4972015-11-12 15:33:07 -08002228 }
deadbeefab9b2d12015-10-14 11:33:11 -07002229 }
2230
2231 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002232 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002233 if (data_content) {
2234 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002235 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002236 if (rtc::starts_with(data_desc->protocol().data(),
2237 cricket::kMediaProtocolRtpPrefix)) {
2238 UpdateLocalRtpDataChannels(data_desc->streams());
2239 }
2240 }
2241
Steve Anton8a006912017-12-04 15:25:56 -08002242 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243}
2244
2245void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002246 SetSessionDescriptionObserver* observer,
2247 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002248 SetRemoteDescription(
2249 std::unique_ptr<SessionDescriptionInterface>(desc),
2250 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2251 new SetRemoteDescriptionObserverAdapter(this, observer)));
2252}
2253
2254void PeerConnection::SetRemoteDescription(
2255 std::unique_ptr<SessionDescriptionInterface> desc,
2256 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002257 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002258
nisse7ce109a2017-01-31 00:57:56 -08002259 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002260 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002261 return;
2262 }
Steve Anton8a006912017-12-04 15:25:56 -08002263
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002264 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002265 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002266 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002267 return;
2268 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002269
Steve Anton80dd7b52018-02-16 17:08:42 -08002270 // If a session error has occurred the PeerConnection is in a possibly
2271 // inconsistent state so fail right away.
2272 if (session_error() != SessionError::kNone) {
2273 std::string error_message = GetSessionErrorMsg();
2274 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2275 observer->OnSetRemoteDescriptionComplete(
2276 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2277 return;
2278 }
Steve Anton71439a62018-02-15 11:53:06 -08002279
Steve Antonba42e992018-04-09 14:10:01 -07002280 if (desc->GetType() == SdpType::kOffer) {
2281 // Report to UMA the format of the received offer.
2282 ReportSdpFormatReceived(*desc);
2283 }
2284
Steve Anton80dd7b52018-02-16 17:08:42 -08002285 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002286 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002287 std::string error_message = GetSetDescriptionErrorMessage(
2288 cricket::CS_REMOTE, desc->GetType(), error);
2289 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002290 observer->OnSetRemoteDescriptionComplete(
2291 RTCError(error.type(), std::move(error_message)));
2292 return;
2293 }
Steve Anton71439a62018-02-15 11:53:06 -08002294
Steve Anton80dd7b52018-02-16 17:08:42 -08002295 // Grab the description type before moving ownership to
2296 // ApplyRemoteDescription, which may destroy it before returning.
2297 const SdpType type = desc->GetType();
2298
2299 error = ApplyRemoteDescription(std::move(desc));
2300 // |desc| may be destroyed at this point.
2301
2302 if (!error.ok()) {
2303 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2304 // inconsistent state, so act conservatively here and set the session error
2305 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2306 SetSessionError(SessionError::kContent, error.message());
2307 std::string error_message =
2308 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2309 RTC_LOG(LS_ERROR) << error_message;
2310 observer->OnSetRemoteDescriptionComplete(
2311 RTCError(error.type(), std::move(error_message)));
2312 return;
2313 }
2314 RTC_DCHECK(remote_description());
2315
2316 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002317 // TODO(deadbeef): We already had to hop to the network thread for
2318 // MaybeStartGathering...
2319 network_thread()->Invoke<void>(
2320 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2321 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002322 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002323 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002324 }
2325
2326 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002327 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002328}
2329
2330RTCError PeerConnection::ApplyRemoteDescription(
2331 std::unique_ptr<SessionDescriptionInterface> desc) {
2332 RTC_DCHECK_RUN_ON(signaling_thread());
2333 RTC_DCHECK(desc);
2334
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002335 // Update stats here so that we have the most recent stats for tracks and
2336 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002337 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002338
Steve Antondcc3c022017-12-22 16:02:54 -08002339 // Take a reference to the old remote description since it's used below to
2340 // compare against the new remote description. When setting the new remote
2341 // description, grab ownership of the replaced session description in case it
2342 // is the same as |old_remote_description|, to keep it alive for the duration
2343 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002344 const SessionDescriptionInterface* old_remote_description =
2345 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002346 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002347 SdpType type = desc->GetType();
2348 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002349 replaced_remote_description = pending_remote_description_
2350 ? std::move(pending_remote_description_)
2351 : std::move(current_remote_description_);
2352 current_remote_description_ = std::move(desc);
2353 pending_remote_description_ = nullptr;
2354 current_local_description_ = std::move(pending_local_description_);
2355 } else {
2356 replaced_remote_description = std::move(pending_remote_description_);
2357 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002358 }
Steve Anton8a006912017-12-04 15:25:56 -08002359 // The session description to apply now must be accessed by
2360 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002361 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002362
Zhi Huange830e682018-03-30 10:48:35 -07002363 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2364 if (!error.ok()) {
2365 return error;
2366 }
Steve Anton8a006912017-12-04 15:25:56 -08002367 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002368 if (IsUnifiedPlan()) {
2369 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002370 cricket::CS_REMOTE, *remote_description(), local_description(),
2371 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002372 if (!error.ok()) {
2373 return error;
2374 }
Steve Antondcc3c022017-12-22 16:02:54 -08002375 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002376 // Media channels will be created only when offer is set. These may use new
2377 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002378 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002379 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002380 // description is applied. Restore back to old description.
2381 RTCError error = CreateChannels(*remote_description()->description());
2382 if (!error.ok()) {
2383 return error;
2384 }
2385 }
Steve Antondcc3c022017-12-22 16:02:54 -08002386 // Remove unused channels if MediaContentDescription is rejected.
2387 RemoveUnusedChannels(remote_description()->description());
2388 }
Steve Anton8a006912017-12-04 15:25:56 -08002389
Zhi Huange830e682018-03-30 10:48:35 -07002390 // NOTE: Candidates allocation will be initiated only when
2391 // SetLocalDescription is called.
2392 error = UpdateSessionState(type, cricket::CS_REMOTE,
2393 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002394 if (!error.ok()) {
2395 return error;
2396 }
2397
2398 if (local_description() &&
2399 !UseCandidatesInSessionDescription(remote_description())) {
2400 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2401 }
2402
2403 if (old_remote_description) {
2404 for (const cricket::ContentInfo& content :
2405 old_remote_description->description()->contents()) {
2406 // Check if this new SessionDescription contains new ICE ufrag and
2407 // password that indicates the remote peer requests an ICE restart.
2408 // TODO(deadbeef): When we start storing both the current and pending
2409 // remote description, this should reset pending_ice_restarts and compare
2410 // against the current description.
2411 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2412 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002413 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002414 pending_ice_restarts_.insert(content.name);
2415 }
2416 } else {
2417 // We retain all received candidates only if ICE is not restarted.
2418 // When ICE is restarted, all previous candidates belong to an old
2419 // generation and should not be kept.
2420 // TODO(deadbeef): This goes against the W3C spec which says the remote
2421 // description should only contain candidates from the last set remote
2422 // description plus any candidates added since then. We should remove
2423 // this once we're sure it won't break anything.
2424 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2425 old_remote_description, content.name, mutable_remote_description());
2426 }
2427 }
2428 }
2429
2430 if (session_error() != SessionError::kNone) {
2431 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2432 }
2433
2434 // Set the the ICE connection state to connecting since the connection may
2435 // become writable with peer reflexive candidates before any remote candidate
2436 // is signaled.
2437 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2438 // is to have a new signal the indicates a change in checking state from the
2439 // transport and expose a new checking() member from transport that can be
2440 // read to determine the current checking state. The existing SignalConnecting
2441 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002442 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002443 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002444 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2445 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2446 }
2447
deadbeefab9b2d12015-10-14 11:33:11 -07002448 // If setting the description decided our SSL role, allocate any necessary
2449 // SCTP sids.
2450 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002451 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002452 AllocateSctpSids(role);
2453 }
2454
Steve Antondcc3c022017-12-22 16:02:54 -08002455 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002456 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002457 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002458 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002459 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002460 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002461 for (auto transceiver : transceivers_) {
2462 const ContentInfo* content =
2463 FindMediaSectionForTransceiver(transceiver, remote_description());
2464 if (!content) {
2465 continue;
2466 }
2467 const MediaContentDescription* media_desc = content->media_description();
2468 RtpTransceiverDirection local_direction =
2469 RtpTransceiverDirectionReversed(media_desc->direction());
2470 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2471 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2472 // transceiver's current direction is neither sendrecv nor recvonly,
2473 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002474 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002475 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002476 // The remote description has signaled the stream IDs.
2477 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002478 }
Steve Antondcc3c022017-12-22 16:02:54 -08002479 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002480 (!transceiver->fired_direction() ||
2481 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002482 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002483 << content->name << " (added to "
2484 << GetStreamIdsString(stream_ids) << ").";
2485
2486 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2487 for (const std::string& stream_id : stream_ids) {
2488 rtc::scoped_refptr<MediaStreamInterface> stream =
2489 remote_streams_->find(stream_id);
2490 if (!stream) {
2491 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2492 MediaStream::Create(stream_id));
2493 remote_streams_->AddStream(stream);
2494 added_streams.push_back(stream);
2495 }
2496 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002497 }
Steve Anton3172c032018-05-03 15:30:18 -07002498 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002499 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2500 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002501 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002502 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002503 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002504 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2505 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2506 // removal of a remote track for the media description, given transceiver,
2507 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002508 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002509 (transceiver->fired_direction() &&
2510 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2511 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2512 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002513 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002514 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2515 transceiver->internal()->set_fired_direction(local_direction);
2516 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2517 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002518 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002519 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2520 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002521 transceiver->internal()->set_current_direction(local_direction);
2522 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002523 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2524 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002525 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002526 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2527 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002528 transceiver->Stop();
2529 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002530 if (!content->rejected &&
2531 RtpTransceiverDirectionHasRecv(local_direction)) {
2532 // Set ssrc to 0 in the case of an unsignalled ssrc.
2533 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002534 if (!media_desc->streams().empty() &&
2535 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002536 ssrc = media_desc->streams()[0].first_ssrc();
2537 }
2538 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002539 }
Steve Antondcc3c022017-12-22 16:02:54 -08002540 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002541 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002542 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002543 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002544 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002545 observer->OnTrack(transceiver);
2546 observer->OnAddTrack(transceiver->receiver(),
2547 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002548 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002549 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002550 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002551 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002552 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002553 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002554 }
2555 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002556 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002557 }
Steve Antondcc3c022017-12-22 16:02:54 -08002558 }
2559
Henrik Boströmfdb92012017-11-09 19:55:44 +01002560 const cricket::ContentInfo* audio_content =
2561 GetFirstAudioContent(remote_description()->description());
2562 const cricket::ContentInfo* video_content =
2563 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002564 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002565 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002566 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002567 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002568 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002569 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002570
2571 // Check if the descriptions include streams, just in case the peer supports
2572 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002573 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002574 (audio_desc && !audio_desc->streams().empty()) ||
2575 (video_desc && !video_desc->streams().empty())) {
2576 remote_peer_supports_msid_ = true;
2577 }
deadbeefab9b2d12015-10-14 11:33:11 -07002578
2579 // We wait to signal new streams until we finish processing the description,
2580 // since only at that point will new streams have all their tracks.
2581 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2582
Steve Antondcc3c022017-12-22 16:02:54 -08002583 if (!IsUnifiedPlan()) {
2584 // TODO(steveanton): When removing RTP senders/receivers in response to a
2585 // rejected media section, there is some cleanup logic that expects the
2586 // voice/ video channel to still be set. But in this method the voice/video
2587 // channel would have been destroyed by the SetRemoteDescription caller
2588 // above so the cleanup that relies on them fails to run. The RemoveSenders
2589 // calls should be moved to right before the DestroyChannel calls to fix
2590 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002591
Steve Antondcc3c022017-12-22 16:02:54 -08002592 // Find all audio rtp streams and create corresponding remote AudioTracks
2593 // and MediaStreams.
2594 if (audio_content) {
2595 if (audio_content->rejected) {
2596 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2597 } else {
2598 bool default_audio_track_needed =
2599 !remote_peer_supports_msid_ &&
2600 RtpTransceiverDirectionHasSend(audio_desc->direction());
2601 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2602 default_audio_track_needed, audio_desc->type(),
2603 new_streams);
2604 }
deadbeeffaac4972015-11-12 15:33:07 -08002605 }
deadbeefab9b2d12015-10-14 11:33:11 -07002606
Steve Antondcc3c022017-12-22 16:02:54 -08002607 // Find all video rtp streams and create corresponding remote VideoTracks
2608 // and MediaStreams.
2609 if (video_content) {
2610 if (video_content->rejected) {
2611 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2612 } else {
2613 bool default_video_track_needed =
2614 !remote_peer_supports_msid_ &&
2615 RtpTransceiverDirectionHasSend(video_desc->direction());
2616 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2617 default_video_track_needed, video_desc->type(),
2618 new_streams);
2619 }
deadbeeffaac4972015-11-12 15:33:07 -08002620 }
deadbeefab9b2d12015-10-14 11:33:11 -07002621
Steve Antondcc3c022017-12-22 16:02:54 -08002622 // Update the DataChannels with the information from the remote peer.
2623 if (data_desc) {
2624 if (rtc::starts_with(data_desc->protocol().data(),
2625 cricket::kMediaProtocolRtpPrefix)) {
2626 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2627 }
deadbeefab9b2d12015-10-14 11:33:11 -07002628 }
deadbeefab9b2d12015-10-14 11:33:11 -07002629
Steve Antondcc3c022017-12-22 16:02:54 -08002630 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002631 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002632 for (size_t i = 0; i < new_streams->count(); ++i) {
2633 MediaStreamInterface* new_stream = new_streams->at(i);
2634 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002635 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002636 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2637 }
deadbeefab9b2d12015-10-14 11:33:11 -07002638
Steve Antondcc3c022017-12-22 16:02:54 -08002639 UpdateEndedRemoteMediaStreams();
2640 }
deadbeefab9b2d12015-10-14 11:33:11 -07002641
Steve Anton8a006912017-12-04 15:25:56 -08002642 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002643}
2644
Steve Anton0f5400a2018-07-17 14:25:36 -07002645void PeerConnection::ProcessRemovalOfRemoteTrack(
2646 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2647 transceiver,
2648 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2649 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2650 RTC_DCHECK(transceiver->mid());
2651 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2652 << *transceiver->mid();
2653 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2654 transceiver->internal()->receiver_internal()->streams();
2655 // This will remove the remote track from the streams.
2656 transceiver->internal()->receiver_internal()->set_stream_ids({});
2657 remove_list->push_back(transceiver);
2658 // Remove any streams that no longer have tracks.
2659 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2660 // of streams, see if the stream was removed by checking if this was the
2661 // last receiver with that stream ID.
2662 for (auto stream : media_streams) {
2663 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2664 remote_streams_->RemoveStream(stream);
2665 removed_streams->push_back(stream);
2666 }
2667 }
2668}
2669
Steve Antondcc3c022017-12-22 16:02:54 -08002670RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2671 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002672 const SessionDescriptionInterface& new_session,
2673 const SessionDescriptionInterface* old_local_description,
2674 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002675 RTC_DCHECK(IsUnifiedPlan());
2676
Steve Anton7464fca2018-01-19 11:10:37 -08002677 const cricket::ContentGroup* bundle_group = nullptr;
2678 if (new_session.GetType() == SdpType::kOffer) {
2679 auto bundle_group_or_error =
2680 GetEarlyBundleGroup(*new_session.description());
2681 if (!bundle_group_or_error.ok()) {
2682 return bundle_group_or_error.MoveError();
2683 }
2684 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002685 }
Steve Antondcc3c022017-12-22 16:02:54 -08002686
Steve Antondcc3c022017-12-22 16:02:54 -08002687 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002688 for (size_t i = 0; i < new_contents.size(); ++i) {
2689 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002690 cricket::MediaType media_type = new_content.media_description()->type();
2691 seen_mids_.insert(new_content.name);
2692 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2693 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002694 const cricket::ContentInfo* old_local_content = nullptr;
2695 if (old_local_description &&
2696 i < old_local_description->description()->contents().size()) {
2697 old_local_content =
2698 &old_local_description->description()->contents()[i];
2699 }
2700 const cricket::ContentInfo* old_remote_content = nullptr;
2701 if (old_remote_description &&
2702 i < old_remote_description->description()->contents().size()) {
2703 old_remote_content =
2704 &old_remote_description->description()->contents()[i];
2705 }
Steve Antondcc3c022017-12-22 16:02:54 -08002706 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002707 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2708 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002709 if (!transceiver_or_error.ok()) {
2710 return transceiver_or_error.MoveError();
2711 }
2712 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002713 RTCError error =
2714 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2715 if (!error.ok()) {
2716 return error;
2717 }
2718 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002719 if (GetDataMid() && new_content.name != *GetDataMid()) {
2720 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002721 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2722 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002723 continue;
2724 }
2725 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2726 if (!error.ok()) {
2727 return error;
2728 }
Steve Antondcc3c022017-12-22 16:02:54 -08002729 } else {
2730 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2731 "Unknown section type.");
2732 }
2733 }
2734
2735 return RTCError::OK();
2736}
2737
2738RTCError PeerConnection::UpdateTransceiverChannel(
2739 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2740 transceiver,
2741 const cricket::ContentInfo& content,
2742 const cricket::ContentGroup* bundle_group) {
2743 RTC_DCHECK(IsUnifiedPlan());
2744 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002745 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002746 if (content.rejected) {
2747 if (channel) {
2748 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002749 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002750 }
2751 } else {
2752 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002753 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002754 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002755 } else {
Steve Anton69470252018-02-09 11:43:08 -08002756 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002757 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002758 }
2759 if (!channel) {
2760 LOG_AND_RETURN_ERROR(
2761 RTCErrorType::INTERNAL_ERROR,
2762 "Failed to create channel for mid=" + content.name);
2763 }
2764 transceiver->internal()->SetChannel(channel);
2765 }
2766 }
2767 return RTCError::OK();
2768}
2769
Steve Antonfa2260d2017-12-28 16:38:23 -08002770RTCError PeerConnection::UpdateDataChannel(
2771 cricket::ContentSource source,
2772 const cricket::ContentInfo& content,
2773 const cricket::ContentGroup* bundle_group) {
2774 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002775 // If data channels are disabled, ignore this media section. CreateAnswer
2776 // will take care of rejecting it.
2777 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002778 }
2779 if (content.rejected) {
2780 DestroyDataChannel();
2781 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002782 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002783 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002784 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2785 "Failed to create data channel.");
2786 }
2787 }
2788 if (source == cricket::CS_REMOTE) {
2789 const MediaContentDescription* data_desc = content.media_description();
2790 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2791 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2792 }
2793 }
2794 }
2795 return RTCError::OK();
2796}
2797
Steve Antondcc3c022017-12-22 16:02:54 -08002798RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2799PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002800 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002801 size_t mline_index,
2802 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002803 const ContentInfo* old_local_content,
2804 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002805 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002806 // If this is an offer then the m= section might be recycled. If the m=
2807 // section is being recycled (defined as: rejected in the current local or
2808 // remote description and not rejected in new description), dissociate the
2809 // currently associated RtpTransceiver by setting its mid property to null,
2810 // and discard the mapping between the transceiver and its m= section index.
2811 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2812 old_remote_content)) {
2813 // We want to dissociate the transceiver that has the rejected mid.
2814 const std::string& old_mid =
2815 (old_local_content && old_local_content->rejected)
2816 ? old_local_content->name
2817 : old_remote_content->name;
2818 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002819 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002820 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2821 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002822 old_transceiver->internal()->set_mid(absl::nullopt);
2823 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002824 }
2825 }
2826 const MediaContentDescription* media_desc = content.media_description();
2827 auto transceiver = GetAssociatedTransceiver(content.name);
2828 if (source == cricket::CS_LOCAL) {
2829 // Find the RtpTransceiver that corresponds to this m= section, using the
2830 // mapping between transceivers and m= section indices established when
2831 // creating the offer.
2832 if (!transceiver) {
2833 transceiver = GetTransceiverByMLineIndex(mline_index);
2834 }
2835 if (!transceiver) {
2836 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2837 "Unknown transceiver");
2838 }
2839 } else {
2840 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2841 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2842 // of the same type...
2843 if (!transceiver &&
2844 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2845 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2846 }
2847 // If no RtpTransceiver was found in the previous step, create one with a
2848 // recvonly direction.
2849 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002850 RTC_LOG(LS_INFO) << "Adding "
2851 << cricket::MediaTypeToString(media_desc->type())
2852 << " transceiver for MID=" << content.name
2853 << " at i=" << mline_index
2854 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002855 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002856 auto sender =
2857 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002858 std::string receiver_id;
2859 if (!media_desc->streams().empty()) {
2860 receiver_id = media_desc->streams()[0].id;
2861 } else {
2862 receiver_id = rtc::CreateRandomUuid();
2863 }
2864 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002865 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002866 transceiver->internal()->set_direction(
2867 RtpTransceiverDirection::kRecvOnly);
2868 }
2869 }
2870 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002871 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002872 LOG_AND_RETURN_ERROR(
2873 RTCErrorType::INVALID_PARAMETER,
2874 "Transceiver type does not match media description type.");
2875 }
2876 // Associate the found or created RtpTransceiver with the m= section by
2877 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2878 // section, and establish a mapping between the transceiver and the index of
2879 // the m= section.
2880 transceiver->internal()->set_mid(content.name);
2881 transceiver->internal()->set_mline_index(mline_index);
2882 return std::move(transceiver);
2883}
2884
2885rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2886PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2887 RTC_DCHECK(IsUnifiedPlan());
2888 for (auto transceiver : transceivers_) {
2889 if (transceiver->mid() == mid) {
2890 return transceiver;
2891 }
2892 }
2893 return nullptr;
2894}
2895
2896rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2897PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2898 RTC_DCHECK(IsUnifiedPlan());
2899 for (auto transceiver : transceivers_) {
2900 if (transceiver->internal()->mline_index() == mline_index) {
2901 return transceiver;
2902 }
2903 }
2904 return nullptr;
2905}
2906
2907rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2908PeerConnection::FindAvailableTransceiverToReceive(
2909 cricket::MediaType media_type) const {
2910 RTC_DCHECK(IsUnifiedPlan());
2911 // From JSEP section 5.10 (Applying a Remote Description):
2912 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2913 // the same type that were added to the PeerConnection by addTrack and are not
2914 // associated with any m= section and are not stopped, find the first such
2915 // RtpTransceiver.
2916 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002917 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002918 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2919 !transceiver->stopped()) {
2920 return transceiver;
2921 }
2922 }
2923 return nullptr;
2924}
2925
Steve Antoned10bd92017-12-05 10:52:59 -08002926const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2927 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2928 transceiver,
2929 const SessionDescriptionInterface* sdesc) const {
2930 RTC_DCHECK(transceiver);
2931 RTC_DCHECK(sdesc);
2932 if (IsUnifiedPlan()) {
2933 if (!transceiver->internal()->mid()) {
2934 // This transceiver is not associated with a media section yet.
2935 return nullptr;
2936 }
2937 return sdesc->description()->GetContentByName(
2938 *transceiver->internal()->mid());
2939 } else {
2940 // Plan B only allows at most one audio and one video section, so use the
2941 // first media section of that type.
2942 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002943 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002944 }
2945}
2946
deadbeef46c73892016-11-16 19:42:04 -08002947PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2948 return configuration_;
2949}
2950
deadbeef293e9262017-01-11 12:28:30 -08002951bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2952 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002953 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002954 if (IsClosed()) {
2955 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2956 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2957 }
2958
Qingsi Wanga2d60672018-04-11 16:57:45 -07002959 // According to JSEP, after setLocalDescription, changing the candidate pool
2960 // size is not allowed, and changing the set of ICE servers will not result
2961 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002962 if (local_description() && configuration.ice_candidate_pool_size !=
2963 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002964 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2965 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002966 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002967 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002968
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002969 if (local_description() &&
2970 configuration.use_media_transport != configuration_.use_media_transport) {
2971 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2972 "SetLocalDescription.";
2973 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2974 }
2975
2976 if (remote_description() &&
2977 configuration.use_media_transport != configuration_.use_media_transport) {
2978 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2979 "SetRemoteDescription.";
2980 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2981 }
2982
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002983 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002984 configuration.use_media_transport_for_data_channels !=
2985 configuration_.use_media_transport_for_data_channels) {
2986 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2987 "after calling SetLocalDescription.";
2988 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2989 }
2990
2991 if (remote_description() &&
2992 configuration.use_media_transport_for_data_channels !=
2993 configuration_.use_media_transport_for_data_channels) {
2994 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2995 "after calling SetRemoteDescription.";
2996 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2997 }
2998
2999 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003000 configuration.crypto_options != configuration_.crypto_options) {
3001 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3002 "SetLocalDescription.";
3003 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3004 }
3005
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003006 if (configuration.use_media_transport_for_data_channels ||
3007 configuration.use_media_transport) {
3008 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3009 << "Media transport requires MaxBundle policy.";
3010 }
3011
deadbeef293e9262017-01-11 12:28:30 -08003012 // The simplest (and most future-compatible) way to tell if the config was
3013 // modified in an invalid way is to copy each property we do support
3014 // modifying, then use operator==. There are far more properties we don't
3015 // support modifying than those we do, and more could be added.
3016 RTCConfiguration modified_config = configuration_;
3017 modified_config.servers = configuration.servers;
3018 modified_config.type = configuration.type;
3019 modified_config.ice_candidate_pool_size =
3020 configuration.ice_candidate_pool_size;
3021 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003022 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003023 modified_config.ice_check_interval_strong_connectivity =
3024 configuration.ice_check_interval_strong_connectivity;
3025 modified_config.ice_check_interval_weak_connectivity =
3026 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003027 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3028 modified_config.ice_unwritable_min_checks =
3029 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003030 modified_config.stun_candidate_keepalive_interval =
3031 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003032 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003033 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003034 modified_config.active_reset_srtp_params =
3035 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003036 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003037 modified_config.use_media_transport_for_data_channels =
3038 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003039 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003040 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003041 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3042 }
3043
Steve Anton038834f2017-07-14 15:59:59 -07003044 // Validate the modified configuration.
3045 RTCError validate_error = ValidateConfiguration(modified_config);
3046 if (!validate_error.ok()) {
3047 return SafeSetError(std::move(validate_error), error);
3048 }
3049
deadbeef293e9262017-01-11 12:28:30 -08003050 // Note that this isn't possible through chromium, since it's an unsigned
3051 // short in WebIDL.
3052 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003053 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003054 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3055 }
3056
3057 // Parse ICE servers before hopping to network thread.
3058 cricket::ServerAddresses stun_servers;
3059 std::vector<cricket::RelayServerConfig> turn_servers;
3060 RTCErrorType parse_error =
3061 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3062 if (parse_error != RTCErrorType::NONE) {
3063 return SafeSetError(parse_error, error);
3064 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003065 // Note if STUN or TURN servers were supplied.
3066 if (!stun_servers.empty()) {
3067 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3068 }
3069 if (!turn_servers.empty()) {
3070 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3071 }
deadbeef293e9262017-01-11 12:28:30 -08003072
3073 // In theory this shouldn't fail.
3074 if (!network_thread()->Invoke<bool>(
3075 RTC_FROM_HERE,
3076 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3077 stun_servers, turn_servers, modified_config.type,
3078 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003079 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003080 modified_config.turn_customizer,
3081 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003082 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003083 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3084 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003085
deadbeefd1a38b52016-12-10 13:15:33 -08003086 // As described in JSEP, calling setConfiguration with new ICE servers or
3087 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3088 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003089 if (modified_config.servers != configuration_.servers ||
3090 modified_config.type != configuration_.type ||
3091 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003092 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003093 }
skvladd1f5fda2017-02-03 16:54:05 -08003094
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003095 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003096 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003097 modified_config.use_media_transport ||
3098 modified_config.use_media_transport_for_data_channels
3099 ? factory_->media_transport_factory()
3100 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003101
Zhi Huangb57e1692018-06-12 11:41:11 -07003102 if (configuration_.active_reset_srtp_params !=
3103 modified_config.active_reset_srtp_params) {
3104 transport_controller_->SetActiveResetSrtpParams(
3105 modified_config.active_reset_srtp_params);
3106 }
3107
deadbeef293e9262017-01-11 12:28:30 -08003108 configuration_ = modified_config;
3109 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003110}
3111
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003112bool PeerConnection::AddIceCandidate(
3113 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003114 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003115 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003116 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003117 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003118 return false;
3119 }
Steve Antond25da372017-11-06 14:50:29 -08003120
3121 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003122 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003123 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003124 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003125 return false;
3126 }
3127
3128 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003129 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003130 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003131 return false;
3132 }
3133
3134 bool valid = false;
3135 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3136 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003137 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003138 return false;
3139 }
3140
3141 // Add this candidate to the remote session description.
3142 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003143 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003144 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003145 return false;
3146 }
3147
3148 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003149 bool result = UseCandidate(ice_candidate);
3150 if (result) {
3151 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3152 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3153 } else {
3154 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3155 }
3156 return result;
Steve Antond25da372017-11-06 14:50:29 -08003157 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003158 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003159 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003160 return true;
3161 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003162}
3163
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003164bool PeerConnection::RemoveIceCandidates(
3165 const std::vector<cricket::Candidate>& candidates) {
3166 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003167 if (IsClosed()) {
3168 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3169 return false;
3170 }
3171
Steve Antond25da372017-11-06 14:50:29 -08003172 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003173 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3174 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003175 return false;
3176 }
3177
3178 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003179 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003180 return false;
3181 }
3182
3183 size_t number_removed =
3184 mutable_remote_description()->RemoveCandidates(candidates);
3185 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003186 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003187 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003188 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003189 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003190 }
3191
3192 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003193 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3194 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003195 RTC_LOG(LS_ERROR)
3196 << "RemoveIceCandidates: Error when removing remote candidates: "
3197 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003198 }
3199 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003200}
3201
Niels Möller0c4f7be2018-05-07 14:01:37 +02003202RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003203 if (!worker_thread()->IsCurrent()) {
3204 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003205 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003206 }
3207
Niels Möller0c4f7be2018-05-07 14:01:37 +02003208 const bool has_min = bitrate.min_bitrate_bps.has_value();
3209 const bool has_start = bitrate.start_bitrate_bps.has_value();
3210 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003211 if (has_min && *bitrate.min_bitrate_bps < 0) {
3212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3213 "min_bitrate_bps <= 0");
3214 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003215 if (has_start) {
3216 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003218 "start_bitrate_bps < min_bitrate_bps");
3219 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3221 "curent_bitrate_bps < 0");
3222 }
3223 }
3224 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003225 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003227 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003228 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3229 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3230 "max_bitrate_bps < min_bitrate_bps");
3231 } else if (*bitrate.max_bitrate_bps < 0) {
3232 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3233 "max_bitrate_bps < 0");
3234 }
3235 }
3236
zstein4b979802017-06-02 14:37:37 -07003237 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003238 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003239
3240 return RTCError::OK();
3241}
3242
Alex Narest78609d52017-10-20 10:37:47 +02003243void PeerConnection::SetBitrateAllocationStrategy(
3244 std::unique_ptr<rtc::BitrateAllocationStrategy>
3245 bitrate_allocation_strategy) {
3246 rtc::Thread* worker_thread = factory_->worker_thread();
3247 if (!worker_thread->IsCurrent()) {
3248 rtc::BitrateAllocationStrategy* strategy_raw =
3249 bitrate_allocation_strategy.release();
3250 auto functor = [this, strategy_raw]() {
3251 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003252 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003253 };
3254 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3255 return;
3256 }
3257 RTC_DCHECK(call_.get());
3258 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3259}
3260
henrika5f6bf242017-11-01 11:06:56 +01003261void PeerConnection::SetAudioPlayout(bool playout) {
3262 if (!worker_thread()->IsCurrent()) {
3263 worker_thread()->Invoke<void>(
3264 RTC_FROM_HERE,
3265 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3266 return;
3267 }
3268 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003269 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003270 audio_state->SetPlayout(playout);
3271}
3272
3273void PeerConnection::SetAudioRecording(bool recording) {
3274 if (!worker_thread()->IsCurrent()) {
3275 worker_thread()->Invoke<void>(
3276 RTC_FROM_HERE,
3277 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3278 return;
3279 }
3280 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003281 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003282 audio_state->SetRecording(recording);
3283}
3284
Steve Anton8c0f7a72017-10-03 10:03:10 -07003285std::unique_ptr<rtc::SSLCertificate>
3286PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003287 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3288 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003289 return nullptr;
3290 }
Steve Antonf25303e2018-10-16 15:23:31 -07003291 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003292}
3293
Zhi Huang70b820f2018-01-27 14:16:15 -08003294std::unique_ptr<rtc::SSLCertChain>
3295PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003296 auto audio_transceiver = GetFirstAudioTransceiver();
3297 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003298 return nullptr;
3299 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003300 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003301 audio_transceiver->internal()->channel()->transport_name());
3302}
3303
3304rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3305PeerConnection::GetFirstAudioTransceiver() const {
3306 for (auto transceiver : transceivers_) {
3307 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3308 return transceiver;
3309 }
3310 }
3311 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003312}
3313
ivoc14d5dbe2016-07-04 07:06:55 -07003314bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3315 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003316 // TODO(eladalon): It would be better to not allow negative values into PC.
3317 const size_t max_size = (max_size_bytes < 0)
3318 ? RtcEventLog::kUnlimitedOutput
3319 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003320 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3321 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3322 output_period_ms = 5000;
3323 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003324 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003325 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003326 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003327}
3328
Bjorn Tereliusde939432017-11-20 17:38:14 +01003329bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3330 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003331 // TODO(eladalon): In C++14, this can be done with a lambda.
3332 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003333 bool operator()() {
3334 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3335 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003336 PeerConnection* const pc;
3337 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003338 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003339 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003340 return worker_thread()->Invoke<bool>(
3341 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003342}
3343
3344void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003345 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003346 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3347}
3348
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003350 return pending_local_description_ ? pending_local_description_.get()
3351 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003352}
3353
3354const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003355 return pending_remote_description_ ? pending_remote_description_.get()
3356 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
deadbeeffe4a8a42016-12-20 17:56:17 -08003359const SessionDescriptionInterface* PeerConnection::current_local_description()
3360 const {
Steve Anton75737c02017-11-06 10:37:17 -08003361 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003362}
3363
3364const SessionDescriptionInterface* PeerConnection::current_remote_description()
3365 const {
Steve Anton75737c02017-11-06 10:37:17 -08003366 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003367}
3368
3369const SessionDescriptionInterface* PeerConnection::pending_local_description()
3370 const {
Steve Anton75737c02017-11-06 10:37:17 -08003371 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003372}
3373
3374const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3375 const {
Steve Anton75737c02017-11-06 10:37:17 -08003376 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003377}
3378
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003379void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003380 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003381 // Update stats here so that we have the most recent stats for tracks and
3382 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003383 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003384
Steve Anton75737c02017-11-06 10:37:17 -08003385 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003386 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003387
Steve Anton8af21862017-12-15 11:20:13 -08003388 for (auto transceiver : transceivers_) {
3389 transceiver->Stop();
3390 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003391
3392 // Ensure that all asynchronous stats requests are completed before destroying
3393 // the transport controller below.
3394 if (stats_collector_) {
3395 stats_collector_->WaitForPendingRequest();
3396 }
3397
3398 // Don't destroy BaseChannels until after stats has been cleaned up so that
3399 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003400 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003401
Qingsi Wang93a84392018-01-30 17:13:09 -08003402 // The event log is used in the transport controller, which must be outlived
3403 // by the former. CreateOffer by the peer connection is implemented
3404 // asynchronously and if the peer connection is closed without resetting the
3405 // WebRTC session description factory, the session description factory would
3406 // call the transport controller.
3407 webrtc_session_desc_factory_.reset();
3408 transport_controller_.reset();
3409
deadbeef42a42632017-03-10 15:18:00 -08003410 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003411 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3412 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003413
Steve Anton978b8762017-09-29 12:15:02 -07003414 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003415 call_.reset();
3416 // The event log must outlive call (and any other object that uses it).
3417 event_log_.reset();
3418 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003419 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003420 // The .h file says that observer can be discarded after close() returns.
3421 // Make sure this is true.
3422 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003423}
3424
Steve Antonad182762018-09-05 20:22:40 +00003425void PeerConnection::OnMessage(rtc::Message* msg) {
3426 switch (msg->message_id) {
3427 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3428 SetSessionDescriptionMsg* param =
3429 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3430 param->observer->OnSuccess();
3431 delete param;
3432 break;
3433 }
3434 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3435 SetSessionDescriptionMsg* param =
3436 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3437 param->observer->OnFailure(std::move(param->error));
3438 delete param;
3439 break;
3440 }
3441 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3442 CreateSessionDescriptionMsg* param =
3443 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3444 param->observer->OnFailure(std::move(param->error));
3445 delete param;
3446 break;
3447 }
3448 case MSG_GETSTATS: {
3449 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3450 StatsReports reports;
3451 stats_->GetStats(param->track, &reports);
3452 param->observer->OnComplete(reports);
3453 delete param;
3454 break;
3455 }
3456 case MSG_FREE_DATACHANNELS: {
3457 sctp_data_channels_to_free_.clear();
3458 break;
3459 }
3460 case MSG_REPORT_USAGE_PATTERN: {
3461 ReportUsagePattern();
3462 break;
3463 }
3464 default:
3465 RTC_NOTREACHED() << "Not implemented";
3466 break;
3467 }
3468}
3469
Steve Antonafb0bb72018-02-20 11:35:37 -08003470cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3471 RTC_DCHECK(!IsUnifiedPlan());
3472 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3473 GetAudioTransceiver()->internal()->channel());
3474 if (voice_channel) {
3475 return voice_channel->media_channel();
3476 } else {
3477 return nullptr;
3478 }
3479}
3480
3481cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3482 RTC_DCHECK(!IsUnifiedPlan());
3483 auto* video_channel = static_cast<cricket::VideoChannel*>(
3484 GetVideoTransceiver()->internal()->channel());
3485 if (video_channel) {
3486 return video_channel->media_channel();
3487 } else {
3488 return nullptr;
3489 }
3490}
3491
Steve Anton4171afb2017-11-20 10:20:22 -08003492void PeerConnection::CreateAudioReceiver(
3493 MediaStreamInterface* stream,
3494 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003495 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3496 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003497 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3498 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003499 auto* audio_receiver = new AudioRtpReceiver(
3500 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003501 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003502 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3503 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3504 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003505 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003506 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003507 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508}
3509
Steve Anton4171afb2017-11-20 10:20:22 -08003510void PeerConnection::CreateVideoReceiver(
3511 MediaStreamInterface* stream,
3512 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003513 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3514 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003515 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3516 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003517 auto* video_receiver = new VideoRtpReceiver(
3518 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003519 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003520 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3521 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3522 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003523 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003524 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003525 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003526}
3527
deadbeef70ab1a12015-09-28 16:53:55 -07003528// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3529// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003530rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003531 const RtpSenderInfo& remote_sender_info) {
3532 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3533 if (!receiver) {
3534 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3535 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003536 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003537 }
Steve Anton4171afb2017-11-20 10:20:22 -08003538 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3539 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3540 } else {
3541 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3542 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003543 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003544}
3545
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003546void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3547 MediaStreamInterface* stream) {
3548 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003549 RTC_DCHECK(track);
3550 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003551 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003552 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003553 // We already have a sender for this track, so just change the stream_id
3554 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003555 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003556 return;
3557 }
3558
3559 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003560 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003561 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003562 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003563 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003564 // If the sender has already been configured in SDP, we call SetSsrc,
3565 // which will connect the sender to the underlying transport. This can
3566 // occur if a local session description that contains the ID of the sender
3567 // is set before AddStream is called. It can also occur if the local
3568 // session description is not changed and RemoveStream is called, and
3569 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003570 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003571 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003572 if (sender_info) {
3573 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003574 }
3575}
3576
3577// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3578// indefinitely, when we have unified plan SDP.
3579void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3580 MediaStreamInterface* stream) {
3581 RTC_DCHECK(!IsClosed());
3582 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003583 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003584 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3585 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003586 return;
3587 }
Steve Anton4171afb2017-11-20 10:20:22 -08003588 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003589}
3590
3591void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3592 MediaStreamInterface* stream) {
3593 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003594 RTC_DCHECK(track);
3595 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003596 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003597 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003598 // We already have a sender for this track, so just change the stream_id
3599 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003600 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003601 return;
3602 }
3603
3604 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003605 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003606 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003607 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003608 GetVideoTransceiver()->internal()->AddSender(new_sender);
3609 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003610 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003611 if (sender_info) {
3612 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003613 }
3614}
3615
3616void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3617 MediaStreamInterface* stream) {
3618 RTC_DCHECK(!IsClosed());
3619 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003620 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003621 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3622 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003623 return;
3624 }
Steve Anton4171afb2017-11-20 10:20:22 -08003625 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003626}
3627
Steve Antonba818672017-11-06 10:21:57 -08003628void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003629 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003630 if (ice_connection_state_ == new_state) {
3631 return;
3632 }
3633
deadbeefcbecd352015-09-23 11:50:27 -07003634 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003635 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003636 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003637 return;
3638 }
Steve Antonba818672017-11-06 10:21:57 -08003639
Mirko Bonadei675513b2017-11-09 11:09:25 +01003640 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3641 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003642 RTC_DCHECK(ice_connection_state_ !=
3643 PeerConnectionInterface::kIceConnectionClosed);
3644
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003645 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003646 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003647}
3648
Alex Loiko9289eda2018-11-23 16:18:59 +00003649void PeerConnection::SetStandardizedIceConnectionState(
3650 PeerConnectionInterface::IceConnectionState new_state) {
3651 RTC_DCHECK(signaling_thread()->IsCurrent());
3652 if (standardized_ice_connection_state_ == new_state)
3653 return;
3654 if (IsClosed())
3655 return;
3656 standardized_ice_connection_state_ = new_state;
3657 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3658 // the old one once disconnects are handled properly.
3659}
3660
Jonas Olsson635474e2018-10-18 15:58:17 +02003661void PeerConnection::SetConnectionState(
3662 PeerConnectionInterface::PeerConnectionState new_state) {
3663 RTC_DCHECK(signaling_thread()->IsCurrent());
3664 if (connection_state_ == new_state)
3665 return;
3666 if (IsClosed())
3667 return;
3668 connection_state_ = new_state;
3669 Observer()->OnConnectionChange(new_state);
3670}
3671
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003672void PeerConnection::OnIceGatheringChange(
3673 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003674 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003675 if (IsClosed()) {
3676 return;
3677 }
3678 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003679 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003680}
3681
jbauch81bf7b02017-03-25 08:31:12 -07003682void PeerConnection::OnIceCandidate(
3683 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003684 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003685 if (IsClosed()) {
3686 return;
3687 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003688 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003689 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3690 candidate->candidate().address().IsPrivateIP()) {
3691 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3692 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003693 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003694}
3695
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003696void PeerConnection::OnIceCandidatesRemoved(
3697 const std::vector<cricket::Candidate>& candidates) {
3698 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003699 if (IsClosed()) {
3700 return;
3701 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003702 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003703}
3704
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003705void PeerConnection::ChangeSignalingState(
3706 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003707 RTC_DCHECK(signaling_thread()->IsCurrent());
3708 if (signaling_state_ == signaling_state) {
3709 return;
3710 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003711 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3712 << GetSignalingStateString(signaling_state_)
3713 << " New state: "
3714 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003715 signaling_state_ = signaling_state;
3716 if (signaling_state == kClosed) {
3717 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003718 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003719 standardized_ice_connection_state_ =
3720 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003721 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3722 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003723 if (ice_gathering_state_ != kIceGatheringComplete) {
3724 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003725 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003726 }
3727 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003728 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003729}
3730
deadbeefeb459812015-12-15 19:24:43 -08003731void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3732 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003733 if (IsClosed()) {
3734 return;
3735 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003736 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003737 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003738}
3739
deadbeefeb459812015-12-15 19:24:43 -08003740void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3741 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003742 if (IsClosed()) {
3743 return;
3744 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003745 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003746 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003747}
3748
3749void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3750 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003751 if (IsClosed()) {
3752 return;
3753 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003754 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003755 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003756}
3757
3758void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3759 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003760 if (IsClosed()) {
3761 return;
3762 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003763 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003764 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003765}
3766
Henrik Boström31638672017-11-23 17:48:32 +01003767void PeerConnection::PostSetSessionDescriptionSuccess(
3768 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003769 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3770 signaling_thread()->Post(RTC_FROM_HERE, this,
3771 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003772}
3773
deadbeefab9b2d12015-10-14 11:33:11 -07003774void PeerConnection::PostSetSessionDescriptionFailure(
3775 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003776 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003777 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003778 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3779 msg->error = std::move(error);
3780 signaling_thread()->Post(RTC_FROM_HERE, this,
3781 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003782}
3783
3784void PeerConnection::PostCreateSessionDescriptionFailure(
3785 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003786 RTCError error) {
3787 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003788 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3789 msg->error = std::move(error);
3790 signaling_thread()->Post(RTC_FROM_HERE, this,
3791 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003792}
3793
zhihuang1c378ed2017-08-17 14:10:50 -07003794void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003795 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003796 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003797 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003798
Steve Antondcc3c022017-12-22 16:02:54 -08003799 if (IsUnifiedPlan()) {
3800 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3801 } else {
3802 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3803 }
3804
Steve Antonfa2260d2017-12-28 16:38:23 -08003805 // Intentionally unset the data channel type for RTP data channel with the
3806 // second condition. Otherwise the RTP data channels would be successfully
3807 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3808 // when building with chromium. We want to leave RTP data channels broken, so
3809 // people won't try to use them.
3810 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3811 session_options->data_channel_type = data_channel_type();
3812 }
3813
Steve Antondcc3c022017-12-22 16:02:54 -08003814 // Apply ICE restart flag and renomination flag.
3815 for (auto& options : session_options->media_description_options) {
3816 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3817 options.transport_options.enable_ice_renomination =
3818 configuration_.enable_ice_renomination;
3819 }
3820
3821 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003822 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08003823 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003824 session_options->pooled_ice_credentials =
3825 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3826 RTC_FROM_HERE,
3827 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3828 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003829 session_options->offer_extmap_allow_mixed =
3830 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003831}
3832
3833void PeerConnection::GetOptionsForPlanBOffer(
3834 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3835 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003836 // Figure out transceiver directional preferences.
3837 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3838 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3839
3840 // By default, generate sendrecv/recvonly m= sections.
3841 bool recv_audio = true;
3842 bool recv_video = true;
3843
3844 // By default, only offer a new m= section if we have media to send with it.
3845 bool offer_new_audio_description = send_audio;
3846 bool offer_new_video_description = send_video;
3847 bool offer_new_data_description = HasDataChannels();
3848
3849 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003850 if (offer_answer_options.offer_to_receive_audio !=
3851 RTCOfferAnswerOptions::kUndefined) {
3852 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003853 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003854 offer_new_audio_description ||
3855 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003856 }
Steve Antondcc3c022017-12-22 16:02:54 -08003857 if (offer_answer_options.offer_to_receive_video !=
3858 RTCOfferAnswerOptions::kUndefined) {
3859 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003860 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003861 offer_new_video_description ||
3862 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003863 }
3864
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003865 absl::optional<size_t> audio_index;
3866 absl::optional<size_t> video_index;
3867 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003868 // If a current description exists, generate m= sections in the same order,
3869 // using the first audio/video/data section that appears and rejecting
3870 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003871 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003872 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003873 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003874 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3875 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3876 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003877 }
3878
zhihuang1c378ed2017-08-17 14:10:50 -07003879 // Add audio/video/data m= sections to the end if needed.
3880 if (!audio_index && offer_new_audio_description) {
3881 session_options->media_description_options.push_back(
3882 cricket::MediaDescriptionOptions(
3883 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003884 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3885 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003886 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003887 }
zhihuang1c378ed2017-08-17 14:10:50 -07003888 if (!video_index && offer_new_video_description) {
3889 session_options->media_description_options.push_back(
3890 cricket::MediaDescriptionOptions(
3891 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003892 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3893 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003894 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003895 }
zhihuang1c378ed2017-08-17 14:10:50 -07003896 if (!data_index && offer_new_data_description) {
3897 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003898 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003899 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003900 }
3901
3902 cricket::MediaDescriptionOptions* audio_media_description_options =
3903 !audio_index ? nullptr
3904 : &session_options->media_description_options[*audio_index];
3905 cricket::MediaDescriptionOptions* video_media_description_options =
3906 !video_index ? nullptr
3907 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003908
Steve Anton4171afb2017-11-20 10:20:22 -08003909 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003910 video_media_description_options,
3911 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003912}
3913
3914// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3915// and return a reference to it.
3916// Generated MIDs should be no more than 3 bytes long to take up less space in
3917// the RTP packet.
3918static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3919 RTC_DCHECK(used_mids);
3920 // We're boring: just generate MIDs 0, 1, 2, ...
3921 size_t i = 0;
3922 std::set<std::string>::iterator it;
3923 bool inserted;
3924 do {
3925 std::string mid = rtc::ToString(i++);
3926 auto insert_result = used_mids->insert(mid);
3927 it = insert_result.first;
3928 inserted = insert_result.second;
3929 } while (!inserted);
3930 return *it;
3931}
3932
3933static cricket::MediaDescriptionOptions
3934GetMediaDescriptionOptionsForTransceiver(
3935 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3936 transceiver,
3937 const std::string& mid) {
3938 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003939 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003940 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003941 // This behavior is specified in JSEP. The gist is that:
3942 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3943 // sendrecv.
3944 // 2. If the MSID is included, then it must be included in any subsequent
3945 // offer/answer exactly the same until the RtpTransceiver is stopped.
3946 if (!transceiver->stopped() &&
3947 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3948 transceiver->internal()->has_ever_been_used_to_send())) {
3949 cricket::SenderOptions sender_options;
3950 sender_options.track_id = transceiver->sender()->id();
3951 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003952 int num_send_encoding_layers =
3953 transceiver->sender()->init_send_encodings().size();
3954 sender_options.num_sim_layers =
3955 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003956 media_description_options.sender_options.push_back(sender_options);
3957 }
Steve Antondcc3c022017-12-22 16:02:54 -08003958 return media_description_options;
3959}
3960
3961void PeerConnection::GetOptionsForUnifiedPlanOffer(
3962 const RTCOfferAnswerOptions& offer_answer_options,
3963 cricket::MediaSessionOptions* session_options) {
3964 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3965 // Offers) and 5.2.2 (Subsequent Offers).
3966 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3967 const ContentInfos& local_contents =
3968 (local_description() ? local_description()->description()->contents()
3969 : ContentInfos());
3970 const ContentInfos& remote_contents =
3971 (remote_description() ? remote_description()->description()->contents()
3972 : ContentInfos());
3973 // The mline indices that can be recycled. New transceivers should reuse these
3974 // slots first.
3975 std::queue<size_t> recycleable_mline_indices;
3976 // Track the MIDs used in previous offer/answer exchanges and the current
3977 // offer so that new, unique MIDs are generated.
3978 std::set<std::string> used_mids = seen_mids_;
3979 // First, go through each media section that exists in either the local or
3980 // remote description and generate a media section in this offer for the
3981 // associated transceiver. If a media section can be recycled, generate a
3982 // default, rejected media section here that can be later overwritten.
3983 for (size_t i = 0;
3984 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3985 // Either |local_content| or |remote_content| is non-null.
3986 const ContentInfo* local_content =
3987 (i < local_contents.size() ? &local_contents[i] : nullptr);
3988 const ContentInfo* remote_content =
3989 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3990 bool had_been_rejected = (local_content && local_content->rejected) ||
3991 (remote_content && remote_content->rejected);
3992 const std::string& mid =
3993 (local_content ? local_content->name : remote_content->name);
3994 cricket::MediaType media_type =
3995 (local_content ? local_content->media_description()->type()
3996 : remote_content->media_description()->type());
3997 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3998 media_type == cricket::MEDIA_TYPE_VIDEO) {
3999 auto transceiver = GetAssociatedTransceiver(mid);
4000 RTC_CHECK(transceiver);
4001 // A media section is considered eligible for recycling if it is marked as
4002 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004003 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004004 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004005 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4006 RtpTransceiverDirection::kInactive,
4007 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004008 recycleable_mline_indices.push(i);
4009 } else {
4010 session_options->media_description_options.push_back(
4011 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4012 // CreateOffer shouldn't really cause any state changes in
4013 // PeerConnection, but we need a way to match new transceivers to new
4014 // media sections in SetLocalDescription and JSEP specifies this is done
4015 // by recording the index of the media section generated for the
4016 // transceiver in the offer.
4017 transceiver->internal()->set_mline_index(i);
4018 }
4019 } else {
4020 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004021 RTC_CHECK(GetDataMid());
4022 if (had_been_rejected || mid != *GetDataMid()) {
4023 session_options->media_description_options.push_back(
4024 GetMediaDescriptionOptionsForRejectedData(mid));
4025 } else {
4026 session_options->media_description_options.push_back(
4027 GetMediaDescriptionOptionsForActiveData(mid));
4028 }
Steve Antondcc3c022017-12-22 16:02:54 -08004029 }
4030 }
4031 // Next, look for transceivers that are newly added (that is, are not stopped
4032 // and not associated). Reuse media sections marked as recyclable first,
4033 // otherwise append to the end of the offer. New media sections should be
4034 // added in the order they were added to the PeerConnection.
4035 for (auto transceiver : transceivers_) {
4036 if (transceiver->mid() || transceiver->stopped()) {
4037 continue;
4038 }
4039 size_t mline_index;
4040 if (!recycleable_mline_indices.empty()) {
4041 mline_index = recycleable_mline_indices.front();
4042 recycleable_mline_indices.pop();
4043 session_options->media_description_options[mline_index] =
4044 GetMediaDescriptionOptionsForTransceiver(transceiver,
4045 AllocateMid(&used_mids));
4046 } else {
4047 mline_index = session_options->media_description_options.size();
4048 session_options->media_description_options.push_back(
4049 GetMediaDescriptionOptionsForTransceiver(transceiver,
4050 AllocateMid(&used_mids)));
4051 }
4052 // See comment above for why CreateOffer changes the transceiver's state.
4053 transceiver->internal()->set_mline_index(mline_index);
4054 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004055 // Lastly, add a m-section if we have local data channels and an m section
4056 // does not already exist.
4057 if (!GetDataMid() && HasDataChannels()) {
4058 session_options->media_description_options.push_back(
4059 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4060 }
Steve Antondcc3c022017-12-22 16:02:54 -08004061}
4062
4063void PeerConnection::GetOptionsForAnswer(
4064 const RTCOfferAnswerOptions& offer_answer_options,
4065 cricket::MediaSessionOptions* session_options) {
4066 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4067
4068 if (IsUnifiedPlan()) {
4069 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4070 } else {
4071 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4072 }
4073
Steve Antonfa2260d2017-12-28 16:38:23 -08004074 // Intentionally unset the data channel type for RTP data channel. Otherwise
4075 // the RTP data channels would be successfully negotiated by default and the
4076 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4077 // We want to leave RTP data channels broken, so people won't try to use them.
4078 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4079 session_options->data_channel_type = data_channel_type();
4080 }
4081
Steve Antondcc3c022017-12-22 16:02:54 -08004082 // Apply ICE renomination flag.
4083 for (auto& options : session_options->media_description_options) {
4084 options.transport_options.enable_ice_renomination =
4085 configuration_.enable_ice_renomination;
4086 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004087
4088 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004089 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08004090 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004091 session_options->pooled_ice_credentials =
4092 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4093 RTC_FROM_HERE,
4094 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4095 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004096}
4097
Steve Antondcc3c022017-12-22 16:02:54 -08004098void PeerConnection::GetOptionsForPlanBAnswer(
4099 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004100 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004101 // Figure out transceiver directional preferences.
4102 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4103 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4104
4105 // By default, generate sendrecv/recvonly m= sections. The direction is also
4106 // restricted by the direction in the offer.
4107 bool recv_audio = true;
4108 bool recv_video = true;
4109
4110 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004111 if (offer_answer_options.offer_to_receive_audio !=
4112 RTCOfferAnswerOptions::kUndefined) {
4113 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004114 }
Steve Antondcc3c022017-12-22 16:02:54 -08004115 if (offer_answer_options.offer_to_receive_video !=
4116 RTCOfferAnswerOptions::kUndefined) {
4117 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004118 }
4119
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004120 absl::optional<size_t> audio_index;
4121 absl::optional<size_t> video_index;
4122 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004123
4124 // Generate m= sections that match those in the offer.
4125 // Note that mediasession.cc will handle intersection our preferred
4126 // direction with the offered direction.
4127 GenerateMediaDescriptionOptions(
4128 remote_description(),
4129 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4130 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4131 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004132
4133 cricket::MediaDescriptionOptions* audio_media_description_options =
4134 !audio_index ? nullptr
4135 : &session_options->media_description_options[*audio_index];
4136 cricket::MediaDescriptionOptions* video_media_description_options =
4137 !video_index ? nullptr
4138 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004139
Steve Anton4171afb2017-11-20 10:20:22 -08004140 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004141 video_media_description_options,
4142 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004143}
zhihuangaf388472016-11-02 16:49:48 -07004144
Steve Antondcc3c022017-12-22 16:02:54 -08004145void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4146 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4147 cricket::MediaSessionOptions* session_options) {
4148 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4149 // Answers) and 5.3.2 (Subsequent Answers).
4150 RTC_DCHECK(remote_description());
4151 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4152 for (const ContentInfo& content :
4153 remote_description()->description()->contents()) {
4154 cricket::MediaType media_type = content.media_description()->type();
4155 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4156 media_type == cricket::MEDIA_TYPE_VIDEO) {
4157 auto transceiver = GetAssociatedTransceiver(content.name);
4158 RTC_CHECK(transceiver);
4159 session_options->media_description_options.push_back(
4160 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4161 } else {
4162 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004163 // Reject all data sections if data channels are disabled.
4164 // Reject a data section if it has already been rejected.
4165 // Reject all data sections except for the first one.
4166 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4167 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004168 session_options->media_description_options.push_back(
4169 GetMediaDescriptionOptionsForRejectedData(content.name));
4170 } else {
4171 session_options->media_description_options.push_back(
4172 GetMediaDescriptionOptionsForActiveData(content.name));
4173 }
Steve Antondcc3c022017-12-22 16:02:54 -08004174 }
4175 }
htaa2a49d92016-03-04 02:51:39 -08004176}
4177
zhihuang1c378ed2017-08-17 14:10:50 -07004178void PeerConnection::GenerateMediaDescriptionOptions(
4179 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004180 RtpTransceiverDirection audio_direction,
4181 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004182 absl::optional<size_t>* audio_index,
4183 absl::optional<size_t>* video_index,
4184 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004185 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004186 for (const cricket::ContentInfo& content :
4187 session_desc->description()->contents()) {
4188 if (IsAudioContent(&content)) {
4189 // If we already have an audio m= section, reject this extra one.
4190 if (*audio_index) {
4191 session_options->media_description_options.push_back(
4192 cricket::MediaDescriptionOptions(
4193 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004194 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004195 } else {
4196 session_options->media_description_options.push_back(
4197 cricket::MediaDescriptionOptions(
4198 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004199 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004200 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004201 }
4202 } else if (IsVideoContent(&content)) {
4203 // If we already have an video m= section, reject this extra one.
4204 if (*video_index) {
4205 session_options->media_description_options.push_back(
4206 cricket::MediaDescriptionOptions(
4207 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004208 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004209 } else {
4210 session_options->media_description_options.push_back(
4211 cricket::MediaDescriptionOptions(
4212 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004213 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004214 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004215 }
4216 } else {
4217 RTC_DCHECK(IsDataContent(&content));
4218 // If we already have an data m= section, reject this extra one.
4219 if (*data_index) {
4220 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004221 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004222 } else {
4223 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004224 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004225 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004226 }
4227 }
htaa2a49d92016-03-04 02:51:39 -08004228 }
deadbeefab9b2d12015-10-14 11:33:11 -07004229}
4230
Steve Antonfa2260d2017-12-28 16:38:23 -08004231cricket::MediaDescriptionOptions
4232PeerConnection::GetMediaDescriptionOptionsForActiveData(
4233 const std::string& mid) const {
4234 // Direction for data sections is meaningless, but legacy endpoints might
4235 // expect sendrecv.
4236 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4237 RtpTransceiverDirection::kSendRecv,
4238 /*stopped=*/false);
4239 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4240 return options;
4241}
4242
4243cricket::MediaDescriptionOptions
4244PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4245 const std::string& mid) const {
4246 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4247 RtpTransceiverDirection::kInactive,
4248 /*stopped=*/true);
4249 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4250 return options;
4251}
4252
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004253absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004254 switch (data_channel_type_) {
4255 case cricket::DCT_RTP:
4256 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004257 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004258 }
4259 return rtp_data_channel_->content_name();
4260 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004261 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004262 case cricket::DCT_MEDIA_TRANSPORT:
4263 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004264 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004265 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004266 }
4267}
4268
Steve Anton4171afb2017-11-20 10:20:22 -08004269void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4270 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4271 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004272 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004273}
4274
Steve Anton4171afb2017-11-20 10:20:22 -08004275void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004276 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004277 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004278 cricket::MediaType media_type,
4279 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004280 RTC_DCHECK(!IsUnifiedPlan());
4281
Steve Anton4171afb2017-11-20 10:20:22 -08004282 std::vector<RtpSenderInfo>* current_senders =
4283 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004284
Steve Anton4171afb2017-11-20 10:20:22 -08004285 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004286 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004287 for (auto sender_it = current_senders->begin();
4288 sender_it != current_senders->end();
4289 /* incremented manually */) {
4290 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004291 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004292 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004293 std::string params_stream_id;
4294 if (params) {
4295 params_stream_id =
4296 (!params->first_stream_id().empty() ? params->first_stream_id()
4297 : kDefaultStreamId);
4298 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004299 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004300 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004301 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004302 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004303 sender_exists) {
4304 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004305 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004306 OnRemoteSenderRemoved(info, media_type);
4307 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004308 }
4309 }
4310
Steve Anton4171afb2017-11-20 10:20:22 -08004311 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004312 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004313 if (!params.has_ssrcs()) {
4314 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4315 // sender, this means it is coming from a Unified Plan endpoint,so we just
4316 // create a default.
4317 default_sender_needed = true;
4318 break;
4319 }
4320
Seth Hampson845e8782018-03-02 11:34:10 -08004321 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004322 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004323 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4324 // not supported in Plan B, we just take the first here and create the
4325 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004326 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004327 (!params.first_stream_id().empty() ? params.first_stream_id()
4328 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004329 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004330 uint32_t ssrc = params.first_ssrc();
4331
4332 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004333 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004334 if (!stream) {
4335 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004336 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004337 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004338 remote_streams_->AddStream(stream);
4339 new_streams->AddStream(stream);
4340 }
4341
Steve Anton4171afb2017-11-20 10:20:22 -08004342 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004343 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004344 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004345 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004346 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004347 }
4348 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004349
Steve Anton4171afb2017-11-20 10:20:22 -08004350 // Add default sender if necessary.
4351 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004352 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004353 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004354 if (!default_stream) {
4355 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004356 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004357 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004358 remote_streams_->AddStream(default_stream);
4359 new_streams->AddStream(default_stream);
4360 }
Steve Anton4171afb2017-11-20 10:20:22 -08004361 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4362 ? kDefaultAudioSenderId
4363 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004364 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004365 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004366 if (!default_sender_info) {
4367 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004368 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004369 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004370 }
4371 }
deadbeefab9b2d12015-10-14 11:33:11 -07004372}
4373
Steve Anton4171afb2017-11-20 10:20:22 -08004374void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4375 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004376 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4377 << " receiver for track_id=" << sender_info.sender_id
4378 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004379
Steve Anton3d954a62018-04-02 11:27:23 -07004380 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004381 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004382 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004383 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004384 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004385 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004386 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004387 }
4388}
4389
Steve Anton4171afb2017-11-20 10:20:22 -08004390void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4391 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004392 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4393 << " receiver for track_id=" << sender_info.sender_id
4394 << " and stream_id=" << sender_info.stream_id;
4395
Seth Hampson845e8782018-03-02 11:34:10 -08004396 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004397
Henrik Boström933d8b02017-10-10 10:05:16 -07004398 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004399 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004400 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4401 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004402 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004403 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004404 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004405 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004406 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004407 }
4408 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004409 // Stopping or destroying a VideoRtpReceiver will end the
4410 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004411 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004412 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004413 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004414 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004415 // There's no guarantee the track is still available, e.g. the track may
4416 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004417 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004418 }
4419 } else {
nisseede5da42017-01-12 05:15:36 -08004420 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004421 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004422 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004423 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004424 }
deadbeefab9b2d12015-10-14 11:33:11 -07004425}
4426
4427void PeerConnection::UpdateEndedRemoteMediaStreams() {
4428 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4429 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4430 MediaStreamInterface* stream = remote_streams_->at(i);
4431 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4432 streams_to_remove.push_back(stream);
4433 }
4434 }
4435
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004436 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004437 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004438 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004439 }
4440}
4441
Steve Anton4171afb2017-11-20 10:20:22 -08004442void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004443 const std::vector<cricket::StreamParams>& streams,
4444 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004445 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004446
Seth Hampson845e8782018-03-02 11:34:10 -08004447 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004448 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004449 for (auto sender_it = current_senders->begin();
4450 sender_it != current_senders->end();
4451 /* incremented manually */) {
4452 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004453 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004454 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4455 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004456 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004457 OnLocalSenderRemoved(info, media_type);
4458 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004459 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004460 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004461 }
4462 }
4463
Steve Anton4171afb2017-11-20 10:20:22 -08004464 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004465 for (const cricket::StreamParams& params : streams) {
4466 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004467 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004468 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004469 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004470 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004471 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004472 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004473 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004474 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004475 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004476 }
4477 }
4478}
4479
Steve Anton4171afb2017-11-20 10:20:22 -08004480void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4481 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004482 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004483 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004484 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004485 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4486 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004487 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004488 return;
4489 }
4490
deadbeeffac06552015-11-25 11:26:01 -08004491 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004492 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004493 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004494 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004495 }
deadbeeffac06552015-11-25 11:26:01 -08004496
Seth Hampson5b4f0752018-04-02 16:31:36 -07004497 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004498 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004499}
4500
Steve Anton4171afb2017-11-20 10:20:22 -08004501void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4502 cricket::MediaType media_type) {
4503 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004504 if (!sender) {
4505 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004506 // SessionDescriptions has been renegotiated.
4507 return;
4508 }
deadbeeffac06552015-11-25 11:26:01 -08004509
4510 // A sender has been removed from the SessionDescription but it's still
4511 // associated with the PeerConnection. This only occurs if the SDP doesn't
4512 // match with the calls to CreateSender, AddStream and RemoveStream.
4513 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004514 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004515 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004516 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004517 }
deadbeeffac06552015-11-25 11:26:01 -08004518
Steve Anton4171afb2017-11-20 10:20:22 -08004519 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004520}
4521
4522void PeerConnection::UpdateLocalRtpDataChannels(
4523 const cricket::StreamParamsVec& streams) {
4524 std::vector<std::string> existing_channels;
4525
4526 // Find new and active data channels.
4527 for (const cricket::StreamParams& params : streams) {
4528 // |it->sync_label| is actually the data channel label. The reason is that
4529 // we use the same naming of data channels as we do for
4530 // MediaStreams and Tracks.
4531 // For MediaStreams, the sync_label is the MediaStream label and the
4532 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004533 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004534 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004535 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004536 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004537 continue;
4538 }
4539 // Set the SSRC the data channel should use for sending.
4540 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4541 existing_channels.push_back(data_channel_it->first);
4542 }
4543
4544 UpdateClosingRtpDataChannels(existing_channels, true);
4545}
4546
4547void PeerConnection::UpdateRemoteRtpDataChannels(
4548 const cricket::StreamParamsVec& streams) {
4549 std::vector<std::string> existing_channels;
4550
4551 // Find new and active data channels.
4552 for (const cricket::StreamParams& params : streams) {
4553 // The data channel label is either the mslabel or the SSRC if the mslabel
4554 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004555 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004556 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004557 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004558 auto data_channel_it = rtp_data_channels_.find(label);
4559 if (data_channel_it == rtp_data_channels_.end()) {
4560 // This is a new data channel.
4561 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4562 } else {
4563 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4564 }
4565 existing_channels.push_back(label);
4566 }
4567
4568 UpdateClosingRtpDataChannels(existing_channels, false);
4569}
4570
4571void PeerConnection::UpdateClosingRtpDataChannels(
4572 const std::vector<std::string>& active_channels,
4573 bool is_local_update) {
4574 auto it = rtp_data_channels_.begin();
4575 while (it != rtp_data_channels_.end()) {
4576 DataChannel* data_channel = it->second;
4577 if (std::find(active_channels.begin(), active_channels.end(),
4578 data_channel->label()) != active_channels.end()) {
4579 ++it;
4580 continue;
4581 }
4582
4583 if (is_local_update) {
4584 data_channel->SetSendSsrc(0);
4585 } else {
4586 data_channel->RemotePeerRequestClose();
4587 }
4588
4589 if (data_channel->state() == DataChannel::kClosed) {
4590 rtp_data_channels_.erase(it);
4591 it = rtp_data_channels_.begin();
4592 } else {
4593 ++it;
4594 }
4595 }
4596}
4597
4598void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4599 uint32_t remote_ssrc) {
4600 rtc::scoped_refptr<DataChannel> channel(
4601 InternalCreateDataChannel(label, nullptr));
4602 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004603 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004604 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004605 return;
4606 }
4607 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004608 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4609 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004610 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004611}
4612
4613rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4614 const std::string& label,
4615 const InternalDataChannelInit* config) {
4616 if (IsClosed()) {
4617 return nullptr;
4618 }
Steve Anton75737c02017-11-06 10:37:17 -08004619 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004620 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004621 << "InternalCreateDataChannel: Data is not supported in this call.";
4622 return nullptr;
4623 }
4624 InternalDataChannelInit new_config =
4625 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004626 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004627 if (new_config.id < 0) {
4628 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004629 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004630 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004631 RTC_LOG(LS_ERROR)
4632 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004633 return nullptr;
4634 }
4635 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004636 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004637 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004638 return nullptr;
4639 }
4640 }
4641
Steve Anton75737c02017-11-06 10:37:17 -08004642 rtc::scoped_refptr<DataChannel> channel(
4643 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004644 if (!channel) {
4645 sid_allocator_.ReleaseSid(new_config.id);
4646 return nullptr;
4647 }
4648
4649 if (channel->data_channel_type() == cricket::DCT_RTP) {
4650 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004651 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4652 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004653 return nullptr;
4654 }
4655 rtp_data_channels_[channel->label()] = channel;
4656 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004657 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004658 sctp_data_channels_.push_back(channel);
4659 channel->SignalClosed.connect(this,
4660 &PeerConnection::OnSctpDataChannelClosed);
4661 }
4662
Steve Anton2d8609c2018-01-23 16:38:46 -08004663 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004664 return channel;
4665}
4666
4667bool PeerConnection::HasDataChannels() const {
4668 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4669}
4670
4671void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4672 for (const auto& channel : sctp_data_channels_) {
4673 if (channel->id() < 0) {
4674 int sid;
4675 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004676 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004677 continue;
4678 }
4679 channel->SetSctpSid(sid);
4680 }
4681 }
4682}
4683
4684void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004685 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004686 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4687 ++it) {
4688 if (it->get() == channel) {
4689 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004690 // After the closing procedure is done, it's safe to use this ID for
4691 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004692 sid_allocator_.ReleaseSid(channel->id());
4693 }
deadbeefbd292462015-12-14 18:15:29 -08004694 // Since this method is triggered by a signal from the DataChannel,
4695 // we can't free it directly here; we need to free it asynchronously.
4696 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004697 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004698 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4699 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004700 return;
4701 }
4702 }
4703}
4704
deadbeefab9b2d12015-10-14 11:33:11 -07004705void PeerConnection::OnDataChannelDestroyed() {
4706 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4707 // DataChannel may callback to us and try to modify the list.
4708 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4709 temp_rtp_dcs.swap(rtp_data_channels_);
4710 for (const auto& kv : temp_rtp_dcs) {
4711 kv.second->OnTransportChannelDestroyed();
4712 }
4713
4714 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4715 temp_sctp_dcs.swap(sctp_data_channels_);
4716 for (const auto& channel : temp_sctp_dcs) {
4717 channel->OnTransportChannelDestroyed();
4718 }
4719}
4720
4721void PeerConnection::OnDataChannelOpenMessage(
4722 const std::string& label,
4723 const InternalDataChannelInit& config) {
4724 rtc::scoped_refptr<DataChannel> channel(
4725 InternalCreateDataChannel(label, &config));
4726 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004727 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004728 return;
4729 }
4730
deadbeefa601f5c2016-06-06 14:27:39 -07004731 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4732 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004733 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004734 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004735}
4736
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004737bool PeerConnection::HandleOpenMessage_s(
4738 const cricket::ReceiveDataParams& params,
4739 const rtc::CopyOnWriteBuffer& buffer) {
4740 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4741 // Received OPEN message; parse and signal that a new data channel should
4742 // be created.
4743 std::string label;
4744 InternalDataChannelInit config;
4745 config.id = params.ssrc;
4746 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4747 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4748 << params.ssrc;
4749 return true;
4750 }
4751 config.open_handshake_role = InternalDataChannelInit::kAcker;
4752 OnDataChannelOpenMessage(label, config);
4753 return true;
4754 }
4755 return false;
4756}
4757
Steve Anton4171afb2017-11-20 10:20:22 -08004758rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4759PeerConnection::GetAudioTransceiver() const {
4760 // This method only works with Plan B SDP, where there is a single
4761 // audio/video transceiver.
4762 RTC_DCHECK(!IsUnifiedPlan());
4763 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004764 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004765 return transceiver;
4766 }
4767 }
4768 RTC_NOTREACHED();
4769 return nullptr;
4770}
4771
4772rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4773PeerConnection::GetVideoTransceiver() const {
4774 // This method only works with Plan B SDP, where there is a single
4775 // audio/video transceiver.
4776 RTC_DCHECK(!IsUnifiedPlan());
4777 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004778 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004779 return transceiver;
4780 }
4781 }
4782 RTC_NOTREACHED();
4783 return nullptr;
4784}
4785
4786// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4787// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004788bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004789 switch (type) {
4790 case cricket::MEDIA_TYPE_AUDIO:
4791 return !GetAudioTransceiver()->internal()->senders().empty();
4792 case cricket::MEDIA_TYPE_VIDEO:
4793 return !GetVideoTransceiver()->internal()->senders().empty();
4794 case cricket::MEDIA_TYPE_DATA:
4795 return false;
4796 }
4797 RTC_NOTREACHED();
4798 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004799}
4800
Steve Anton4171afb2017-11-20 10:20:22 -08004801rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4802PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4803 for (auto transceiver : transceivers_) {
4804 for (auto sender : transceiver->internal()->senders()) {
4805 if (sender->track() == track) {
4806 return sender;
4807 }
4808 }
4809 }
4810 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004811}
4812
Steve Anton4171afb2017-11-20 10:20:22 -08004813rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4814PeerConnection::FindSenderById(const std::string& sender_id) const {
4815 for (auto transceiver : transceivers_) {
4816 for (auto sender : transceiver->internal()->senders()) {
4817 if (sender->id() == sender_id) {
4818 return sender;
4819 }
4820 }
4821 }
4822 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004823}
4824
Steve Anton4171afb2017-11-20 10:20:22 -08004825rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4826PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4827 for (auto transceiver : transceivers_) {
4828 for (auto receiver : transceiver->internal()->receivers()) {
4829 if (receiver->id() == receiver_id) {
4830 return receiver;
4831 }
4832 }
4833 }
4834 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004835}
4836
Steve Anton4171afb2017-11-20 10:20:22 -08004837std::vector<PeerConnection::RtpSenderInfo>*
4838PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4839 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4840 media_type == cricket::MEDIA_TYPE_VIDEO);
4841 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4842 ? &remote_audio_sender_infos_
4843 : &remote_video_sender_infos_;
4844}
4845
4846std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004847 cricket::MediaType media_type) {
4848 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4849 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004850 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4851 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004852}
4853
Steve Anton4171afb2017-11-20 10:20:22 -08004854const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4855 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004856 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004857 const std::string sender_id) const {
4858 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004859 if (sender_info.stream_id == stream_id &&
4860 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004861 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004862 }
4863 }
4864 return nullptr;
4865}
4866
4867DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4868 for (const auto& channel : sctp_data_channels_) {
4869 if (channel->id() == sid) {
4870 return channel;
4871 }
4872 }
4873 return nullptr;
4874}
4875
deadbeef91dd5672016-05-18 16:55:30 -07004876bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004877 const cricket::ServerAddresses& stun_servers,
4878 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004879 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004880 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004881 // To handle both internal and externally created port allocator, we will
4882 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004883 port_allocator_flags_ = port_allocator_->flags();
4884 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4885 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4886 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004887 // If the disable-IPv6 flag was specified, we'll not override it
4888 // by experiment.
4889 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004890 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004891 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4892 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004893 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004894 }
4895
zhihuangb09b3f92017-03-07 14:40:51 -08004896 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004897 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004898 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004899 }
4900
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004901 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004902 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004903 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004904 }
4905
honghaiz60347052016-05-31 18:29:12 -07004906 if (configuration.candidate_network_policy ==
4907 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004908 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004909 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004910 }
4911
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004912 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004913 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004914 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4915 }
4916
Qingsi Wanga2d60672018-04-11 16:57:45 -07004917 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004918 // No step delay is used while allocating ports.
4919 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4920 port_allocator_->set_candidate_filter(
4921 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004922 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004923
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004924 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004925 for (auto& turn_server : turn_servers_copy) {
4926 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004927 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004928 // Call this last since it may create pooled allocator sessions using the
4929 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004930 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004931 stun_servers, std::move(turn_servers_copy),
4932 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4933 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004934 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004935 return true;
4936}
4937
deadbeef91dd5672016-05-18 16:55:30 -07004938bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004939 const cricket::ServerAddresses& stun_servers,
4940 const std::vector<cricket::RelayServerConfig>& turn_servers,
4941 IceTransportsType type,
4942 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004943 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004944 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004945 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004946 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004947 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004948 // According to JSEP, after setLocalDescription, changing the candidate pool
4949 // size is not allowed, and changing the set of ICE servers will not result
4950 // in new candidates being gathered.
4951 if (local_description()) {
4952 port_allocator_->FreezeCandidatePool();
4953 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004954 // Add the custom tls turn servers if they exist.
4955 auto turn_servers_copy = turn_servers;
4956 for (auto& turn_server : turn_servers_copy) {
4957 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4958 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004959 // Call this last since it may create pooled allocator sessions using the
4960 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004961 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004962 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4963 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004964}
4965
Steve Antonba818672017-11-06 10:21:57 -08004966cricket::ChannelManager* PeerConnection::channel_manager() const {
4967 return factory_->channel_manager();
4968}
4969
Elad Alon99c3fe52017-10-13 16:29:40 +02004970bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004971 std::unique_ptr<RtcEventLogOutput> output,
4972 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004973 if (!event_log_) {
4974 return false;
4975 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004976 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004977}
4978
4979void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004980 if (event_log_) {
4981 event_log_->StopLogging();
4982 }
ivoc14d5dbe2016-07-04 07:06:55 -07004983}
nisseeaabdf62017-05-05 02:23:02 -07004984
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004985cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08004986 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004987 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004988 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08004989 if (channel && channel->content_name() == content_name) {
4990 return channel;
4991 }
Steve Anton75737c02017-11-06 10:37:17 -08004992 }
4993 if (rtp_data_channel() &&
4994 rtp_data_channel()->content_name() == content_name) {
4995 return rtp_data_channel();
4996 }
4997 return nullptr;
4998}
4999
5000bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005001 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005002 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005003 RTC_LOG(LS_INFO)
5004 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005005 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005006 return false;
5007 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005008 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005009 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005010 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005011 return false;
5012 }
5013
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005014 absl::optional<rtc::SSLRole> dtls_role;
5015 if (sctp_mid_) {
5016 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5017 } else if (is_caller_) {
5018 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5019 }
Zhi Huange830e682018-03-30 10:48:35 -07005020 if (dtls_role) {
5021 *role = *dtls_role;
5022 return true;
5023 }
5024 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005025}
5026
5027bool PeerConnection::GetSslRole(const std::string& content_name,
5028 rtc::SSLRole* role) {
5029 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005030 RTC_LOG(LS_INFO)
5031 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005032 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005033 return false;
5034 }
5035
Zhi Huange830e682018-03-30 10:48:35 -07005036 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5037 if (dtls_role) {
5038 *role = *dtls_role;
5039 return true;
5040 }
5041 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005042}
5043
Steve Antonf8470812017-12-04 10:46:21 -08005044void PeerConnection::SetSessionError(SessionError error,
5045 const std::string& error_desc) {
5046 RTC_DCHECK_RUN_ON(signaling_thread());
5047 if (error != session_error_) {
5048 session_error_ = error;
5049 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005050 }
5051}
5052
Zhi Huange830e682018-03-30 10:48:35 -07005053RTCError PeerConnection::UpdateSessionState(
5054 SdpType type,
5055 cricket::ContentSource source,
5056 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005057 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005058
5059 // If there's already a pending error then no state transition should happen.
5060 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005061 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005062
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005063 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005064 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005065 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005066 }
5067
5068 // Update the signaling state according to the specified state machine (see
5069 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005070 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005071 ChangeSignalingState(source == cricket::CS_LOCAL
5072 ? PeerConnectionInterface::kHaveLocalOffer
5073 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005074 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005075 ChangeSignalingState(source == cricket::CS_LOCAL
5076 ? PeerConnectionInterface::kHaveLocalPrAnswer
5077 : PeerConnectionInterface::kHaveRemotePrAnswer);
5078 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005079 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005080 ChangeSignalingState(PeerConnectionInterface::kStable);
5081 }
5082
5083 // Update internal objects according to the session description's media
5084 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005085 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005086 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005087 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005088 }
5089
Steve Anton8a006912017-12-04 15:25:56 -08005090 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005091}
5092
Steve Anton8a006912017-12-04 15:25:56 -08005093RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005094 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005095 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005096 const SessionDescriptionInterface* sdesc =
5097 (source == cricket::CS_LOCAL ? local_description()
5098 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005099 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005100
5101 // Push down the new SDP media section for each audio/video transceiver.
5102 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005103 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005104 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005105 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005106 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005107 continue;
5108 }
5109 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005110 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005111 if (!content_desc) {
5112 continue;
5113 }
5114 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005115 bool success = (source == cricket::CS_LOCAL)
5116 ? channel->SetLocalContent(content_desc, type, &error)
5117 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005118 if (!success) {
5119 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5120 }
5121 }
5122
5123 // If using the RtpDataChannel, push down the new SDP section for it too.
5124 if (rtp_data_channel_) {
5125 const ContentInfo* data_content =
5126 cricket::GetFirstDataContent(sdesc->description());
5127 if (data_content && !data_content->rejected) {
5128 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005129 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005130 if (data_desc) {
5131 std::string error;
5132 bool success =
5133 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005134 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005135 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005136 if (!success) {
5137 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5138 std::move(error));
5139 }
Steve Anton75737c02017-11-06 10:37:17 -08005140 }
5141 }
5142 }
Steve Antoned10bd92017-12-05 10:52:59 -08005143
Steve Anton75737c02017-11-06 10:37:17 -08005144 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5145 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5146 if (sctp_transport_ && local_description() && remote_description() &&
5147 cricket::GetFirstDataContent(local_description()->description()) &&
5148 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005149 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005150 RTC_FROM_HERE,
5151 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005152 if (!success) {
5153 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5154 "Failed to push down SCTP parameters.");
5155 }
Steve Anton75737c02017-11-06 10:37:17 -08005156 }
Steve Antoned10bd92017-12-05 10:52:59 -08005157
Steve Anton8a006912017-12-04 15:25:56 -08005158 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005159}
5160
5161bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5162 RTC_DCHECK(network_thread()->IsCurrent());
5163 RTC_DCHECK(local_description());
5164 RTC_DCHECK(remote_description());
5165 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5166 // When we support "max-message-size", that would also be pushed down here.
5167 return sctp_transport_->Start(
5168 GetSctpPort(local_description()->description()),
5169 GetSctpPort(remote_description()->description()));
5170}
5171
Steve Anton8a006912017-12-04 15:25:56 -08005172RTCError PeerConnection::PushdownTransportDescription(
5173 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005174 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005175 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005176
Zhi Huange830e682018-03-30 10:48:35 -07005177 if (source == cricket::CS_LOCAL) {
5178 const SessionDescriptionInterface* sdesc = local_description();
5179 RTC_DCHECK(sdesc);
5180 return transport_controller_->SetLocalDescription(type,
5181 sdesc->description());
5182 } else {
5183 const SessionDescriptionInterface* sdesc = remote_description();
5184 RTC_DCHECK(sdesc);
5185 return transport_controller_->SetRemoteDescription(type,
5186 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005187 }
Steve Anton75737c02017-11-06 10:37:17 -08005188}
5189
5190bool PeerConnection::GetTransportDescription(
5191 const SessionDescription* description,
5192 const std::string& content_name,
5193 cricket::TransportDescription* tdesc) {
5194 if (!description || !tdesc) {
5195 return false;
5196 }
5197 const TransportInfo* transport_info =
5198 description->GetTransportInfoByName(content_name);
5199 if (!transport_info) {
5200 return false;
5201 }
5202 *tdesc = transport_info->description;
5203 return true;
5204}
5205
Steve Anton75737c02017-11-06 10:37:17 -08005206cricket::IceConfig PeerConnection::ParseIceConfig(
5207 const PeerConnectionInterface::RTCConfiguration& config) const {
5208 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005209 switch (config.continual_gathering_policy) {
5210 case PeerConnectionInterface::GATHER_ONCE:
5211 gathering_policy = cricket::GATHER_ONCE;
5212 break;
5213 case PeerConnectionInterface::GATHER_CONTINUALLY:
5214 gathering_policy = cricket::GATHER_CONTINUALLY;
5215 break;
5216 default:
5217 RTC_NOTREACHED();
5218 gathering_policy = cricket::GATHER_ONCE;
5219 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005220
Steve Anton75737c02017-11-06 10:37:17 -08005221 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005222 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5223 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005224 ice_config.prioritize_most_likely_candidate_pairs =
5225 config.prioritize_most_likely_ice_candidate_pairs;
5226 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005227 RTCConfigurationToIceConfigOptionalInt(
5228 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005229 ice_config.continual_gathering_policy = gathering_policy;
5230 ice_config.presume_writable_when_fully_relayed =
5231 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005232 ice_config.ice_check_interval_strong_connectivity =
5233 config.ice_check_interval_strong_connectivity;
5234 ice_config.ice_check_interval_weak_connectivity =
5235 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005236 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005237 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005238 ice_config.regather_all_networks_interval_range =
5239 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005240 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005241 return ice_config;
5242}
5243
Steve Anton75737c02017-11-06 10:37:17 -08005244bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5245 std::string* track_id) {
5246 if (!local_description()) {
5247 return false;
5248 }
5249 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5250 track_id);
5251}
5252
5253bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5254 std::string* track_id) {
5255 if (!remote_description()) {
5256 return false;
5257 }
5258 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5259 track_id);
5260}
5261
5262bool PeerConnection::SendData(const cricket::SendDataParams& params,
5263 const rtc::CopyOnWriteBuffer& payload,
5264 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005265 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5266 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5267 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005268 return false;
5269 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005270 if (media_transport_) {
5271 SendDataParams send_params;
5272 send_params.type = ToWebrtcDataMessageType(params.type);
5273 send_params.ordered = params.ordered;
5274 if (params.max_rtx_count >= 0) {
5275 send_params.max_rtx_count = params.max_rtx_count;
5276 } else if (params.max_rtx_ms >= 0) {
5277 send_params.max_rtx_ms = params.max_rtx_ms;
5278 }
5279 return media_transport_->SendData(params.sid, send_params, payload).ok();
5280 }
Steve Anton75737c02017-11-06 10:37:17 -08005281 return rtp_data_channel_
5282 ? rtp_data_channel_->SendData(params, payload, result)
5283 : network_thread()->Invoke<bool>(
5284 RTC_FROM_HERE,
5285 Bind(&cricket::SctpTransportInternal::SendData,
5286 sctp_transport_.get(), params, payload, result));
5287}
5288
5289bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005290 RTC_DCHECK_RUN_ON(signaling_thread());
5291 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005292 // Don't log an error here, because DataChannels are expected to call
5293 // ConnectDataChannel in this state. It's the only way to initially tell
5294 // whether or not the underlying transport is ready.
5295 return false;
5296 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005297 if (media_transport_) {
5298 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5299 &DataChannel::OnChannelReady);
5300 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5301 &DataChannel::OnDataReceived);
5302 SignalMediaTransportChannelClosing_s.connect(
5303 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5304 SignalMediaTransportChannelClosed_s.connect(
5305 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5306 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005307 rtp_data_channel_->SignalReadyToSendData.connect(
5308 webrtc_data_channel, &DataChannel::OnChannelReady);
5309 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5310 &DataChannel::OnDataReceived);
5311 } else {
5312 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5313 &DataChannel::OnChannelReady);
5314 SignalSctpDataReceived.connect(webrtc_data_channel,
5315 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005316 SignalSctpClosingProcedureStartedRemotely.connect(
5317 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5318 SignalSctpClosingProcedureComplete.connect(
5319 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005320 }
5321 return true;
5322}
5323
5324void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005325 RTC_DCHECK_RUN_ON(signaling_thread());
5326 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005327 RTC_LOG(LS_ERROR)
5328 << "DisconnectDataChannel called when rtp_data_channel_ and "
5329 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005330 return;
5331 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005332 if (media_transport_) {
5333 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5334 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5335 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5336 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5337 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005338 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5339 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5340 } else {
5341 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5342 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005343 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5344 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005345 }
5346}
5347
5348void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005349 if (media_transport_) {
5350 // No-op. Media transport does not need to add streams.
5351 return;
5352 }
Steve Anton75737c02017-11-06 10:37:17 -08005353 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005354 RTC_LOG(LS_ERROR)
5355 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005356 return;
5357 }
5358 network_thread()->Invoke<void>(
5359 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5360 sctp_transport_.get(), sid));
5361}
5362
5363void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005364 if (media_transport_) {
5365 media_transport_->CloseChannel(sid);
5366 return;
5367 }
Steve Anton75737c02017-11-06 10:37:17 -08005368 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005369 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005370 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005371 return;
5372 }
5373 network_thread()->Invoke<void>(
5374 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5375 sctp_transport_.get(), sid));
5376}
5377
5378bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005379 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005380 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005381 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005382 sctp_ready_to_send_data_;
5383}
5384
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005385void PeerConnection::OnDataReceived(int channel_id,
5386 DataMessageType type,
5387 const rtc::CopyOnWriteBuffer& buffer) {
5388 cricket::ReceiveDataParams params;
5389 params.sid = channel_id;
5390 params.type = ToCricketDataMessageType(type);
5391 media_transport_invoker_->AsyncInvoke<void>(
5392 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5393 RTC_DCHECK_RUN_ON(signaling_thread());
5394 if (!HandleOpenMessage_s(params, buffer)) {
5395 SignalMediaTransportReceivedData_s(params, buffer);
5396 }
5397 });
5398}
5399
5400void PeerConnection::OnChannelClosing(int channel_id) {
5401 media_transport_invoker_->AsyncInvoke<void>(
5402 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5403 RTC_DCHECK_RUN_ON(signaling_thread());
5404 SignalMediaTransportChannelClosing_s(channel_id);
5405 });
5406}
5407
5408void PeerConnection::OnChannelClosed(int channel_id) {
5409 media_transport_invoker_->AsyncInvoke<void>(
5410 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5411 RTC_DCHECK_RUN_ON(signaling_thread());
5412 SignalMediaTransportChannelClosed_s(channel_id);
5413 });
5414}
5415
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005416absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005417 if (sctp_mid_ && transport_controller_) {
5418 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5419 if (dtls_transport) {
5420 return dtls_transport->transport_name();
5421 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005422 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005423 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005424 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005425}
5426
Qingsi Wang72a43a12018-02-20 16:03:18 -08005427cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5428 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005429 network_thread()->Invoke<void>(
5430 RTC_FROM_HERE,
5431 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5432 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005433 return candidate_states_list;
5434}
5435
Steve Anton5dfde182018-02-06 10:34:40 -08005436std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5437 const {
5438 std::map<std::string, std::string> transport_names_by_mid;
5439 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005440 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005441 if (channel) {
5442 transport_names_by_mid[channel->content_name()] =
5443 channel->transport_name();
5444 }
Steve Anton75737c02017-11-06 10:37:17 -08005445 }
Steve Anton5dfde182018-02-06 10:34:40 -08005446 if (rtp_data_channel_) {
5447 transport_names_by_mid[rtp_data_channel_->content_name()] =
5448 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005449 }
5450 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005451 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005452 RTC_DCHECK(transport_name);
5453 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005454 }
Steve Anton5dfde182018-02-06 10:34:40 -08005455 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005456}
5457
Steve Anton5dfde182018-02-06 10:34:40 -08005458std::map<std::string, cricket::TransportStats>
5459PeerConnection::GetTransportStatsByNames(
5460 const std::set<std::string>& transport_names) {
5461 if (!network_thread()->IsCurrent()) {
5462 return network_thread()
5463 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5464 RTC_FROM_HERE,
5465 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005466 }
Steve Anton5dfde182018-02-06 10:34:40 -08005467 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5468 for (const std::string& transport_name : transport_names) {
5469 cricket::TransportStats transport_stats;
5470 bool success =
5471 transport_controller_->GetStats(transport_name, &transport_stats);
5472 if (success) {
5473 transport_stats_by_name[transport_name] = std::move(transport_stats);
5474 } else {
5475 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5476 << transport_name;
5477 }
5478 }
5479 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005480}
5481
5482bool PeerConnection::GetLocalCertificate(
5483 const std::string& transport_name,
5484 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005485 if (!certificate) {
5486 return false;
5487 }
5488 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5489 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005490}
5491
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005492std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005493 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005494 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005495}
5496
5497cricket::DataChannelType PeerConnection::data_channel_type() const {
5498 return data_channel_type_;
5499}
5500
5501bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5502 return pending_ice_restarts_.find(content_name) !=
5503 pending_ice_restarts_.end();
5504}
5505
Steve Anton75737c02017-11-06 10:37:17 -08005506bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5507 return transport_controller_->NeedsIceRestart(content_name);
5508}
5509
5510void PeerConnection::OnCertificateReady(
5511 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5512 transport_controller_->SetLocalCertificate(certificate);
5513}
5514
5515void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005516 SetSessionError(SessionError::kTransport,
5517 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005518}
5519
Alex Loiko9289eda2018-11-23 16:18:59 +00005520void PeerConnection::OnTransportControllerConnectionState(
5521 cricket::IceConnectionState state) {
5522 switch (state) {
5523 case cricket::kIceConnectionConnecting:
5524 // If the current state is Connected or Completed, then there were
5525 // writable channels but now there are not, so the next state must
5526 // be Disconnected.
5527 // kIceConnectionConnecting is currently used as the default,
5528 // un-connected state by the TransportController, so its only use is
5529 // detecting disconnections.
5530 if (ice_connection_state_ ==
5531 PeerConnectionInterface::kIceConnectionConnected ||
5532 ice_connection_state_ ==
5533 PeerConnectionInterface::kIceConnectionCompleted) {
5534 SetIceConnectionState(
5535 PeerConnectionInterface::kIceConnectionDisconnected);
5536 }
5537 break;
5538 case cricket::kIceConnectionFailed:
5539 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5540 break;
5541 case cricket::kIceConnectionConnected:
5542 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5543 "all transports are writable.";
5544 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5545 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5546 break;
5547 case cricket::kIceConnectionCompleted:
5548 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5549 "all transports are complete.";
5550 if (ice_connection_state_ !=
5551 PeerConnectionInterface::kIceConnectionConnected) {
5552 // If jumping directly from "checking" to "connected",
5553 // signal "connected" first.
5554 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5555 }
5556 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5557 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5558 ReportTransportStats();
5559 break;
5560 default:
5561 RTC_NOTREACHED();
5562 }
5563}
5564
Steve Anton75737c02017-11-06 10:37:17 -08005565void PeerConnection::OnTransportControllerCandidatesGathered(
5566 const std::string& transport_name,
5567 const cricket::Candidates& candidates) {
5568 RTC_DCHECK(signaling_thread()->IsCurrent());
5569 int sdp_mline_index;
5570 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005571 RTC_LOG(LS_ERROR)
5572 << "OnTransportControllerCandidatesGathered: content name "
5573 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005574 return;
5575 }
5576
5577 for (cricket::Candidates::const_iterator citer = candidates.begin();
5578 citer != candidates.end(); ++citer) {
5579 // Use transport_name as the candidate media id.
5580 std::unique_ptr<JsepIceCandidate> candidate(
5581 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5582 if (local_description()) {
5583 mutable_local_description()->AddCandidate(candidate.get());
5584 }
5585 OnIceCandidate(std::move(candidate));
5586 }
5587}
5588
5589void PeerConnection::OnTransportControllerCandidatesRemoved(
5590 const std::vector<cricket::Candidate>& candidates) {
5591 RTC_DCHECK(signaling_thread()->IsCurrent());
5592 // Sanity check.
5593 for (const cricket::Candidate& candidate : candidates) {
5594 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005595 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005596 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005597 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005598 return;
5599 }
5600 }
5601
5602 if (local_description()) {
5603 mutable_local_description()->RemoveCandidates(candidates);
5604 }
5605 OnIceCandidatesRemoved(candidates);
5606}
5607
5608void PeerConnection::OnTransportControllerDtlsHandshakeError(
5609 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005610 RTC_HISTOGRAM_ENUMERATION(
5611 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5612 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005613}
5614
Steve Antoned10bd92017-12-05 10:52:59 -08005615void PeerConnection::EnableSending() {
5616 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005617 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005618 if (channel && !channel->enabled()) {
5619 channel->Enable(true);
5620 }
Steve Anton75737c02017-11-06 10:37:17 -08005621 }
5622
Steve Anton4171afb2017-11-20 10:20:22 -08005623 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005624 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005625 }
Steve Anton75737c02017-11-06 10:37:17 -08005626}
5627
5628// Returns the media index for a local ice candidate given the content name.
5629bool PeerConnection::GetLocalCandidateMediaIndex(
5630 const std::string& content_name,
5631 int* sdp_mline_index) {
5632 if (!local_description() || !sdp_mline_index) {
5633 return false;
5634 }
5635
5636 bool content_found = false;
5637 const ContentInfos& contents = local_description()->description()->contents();
5638 for (size_t index = 0; index < contents.size(); ++index) {
5639 if (contents[index].name == content_name) {
5640 *sdp_mline_index = static_cast<int>(index);
5641 content_found = true;
5642 break;
5643 }
5644 }
5645 return content_found;
5646}
5647
5648bool PeerConnection::UseCandidatesInSessionDescription(
5649 const SessionDescriptionInterface* remote_desc) {
5650 if (!remote_desc) {
5651 return true;
5652 }
5653 bool ret = true;
5654
5655 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5656 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5657 for (size_t n = 0; n < candidates->count(); ++n) {
5658 const IceCandidateInterface* candidate = candidates->at(n);
5659 bool valid = false;
5660 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5661 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005662 RTC_LOG(LS_INFO)
5663 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005664 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005665 }
5666 continue;
5667 }
5668 ret = UseCandidate(candidate);
5669 if (!ret) {
5670 break;
5671 }
5672 }
5673 }
5674 return ret;
5675}
5676
5677bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5678 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5679 size_t remote_content_size =
5680 remote_description()->description()->contents().size();
5681 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005682 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005683 return false;
5684 }
5685
5686 cricket::ContentInfo content =
5687 remote_description()->description()->contents()[mediacontent_index];
5688 std::vector<cricket::Candidate> candidates;
5689 candidates.push_back(candidate->candidate());
5690 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005691 RTCError error =
5692 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005693 if (error.ok()) {
5694 // Candidates successfully submitted for checking.
5695 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5696 ice_connection_state_ ==
5697 PeerConnectionInterface::kIceConnectionDisconnected) {
5698 // If state is New, then the session has just gotten its first remote ICE
5699 // candidates, so go to Checking.
5700 // If state is Disconnected, the session is re-using old candidates or
5701 // receiving additional ones, so go to Checking.
5702 // If state is Connected, stay Connected.
5703 // TODO(bemasc): If state is Connected, and the new candidates are for a
5704 // newly added transport, then the state actually _should_ move to
5705 // checking. Add a way to distinguish that case.
5706 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5707 }
5708 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005709 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005710 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005711 }
5712 return true;
5713}
5714
5715void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005716 // Destroy video channel first since it may have a pointer to the
5717 // voice channel.
5718 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005719 if (!video_info || video_info->rejected) {
5720 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005721 }
5722
Steve Anton6fec8802017-12-04 10:37:29 -08005723 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5724 if (!audio_info || audio_info->rejected) {
5725 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005726 }
5727
5728 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5729 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005730 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005731 }
5732}
5733
Steve Antondcc3c022017-12-22 16:02:54 -08005734RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5735 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005736 const cricket::ContentGroup* bundle_group = nullptr;
5737 if (configuration_.bundle_policy ==
5738 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005739 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005740 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005741 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5742 "max-bundle configured but session description "
5743 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005744 }
5745 }
Steve Antondcc3c022017-12-22 16:02:54 -08005746 return std::move(bundle_group);
5747}
5748
5749RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005750 // Creating the media channels. Transports should already have been created
5751 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005752 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005753 if (voice && !voice->rejected &&
5754 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005755 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005756 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005757 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5758 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005759 }
5760 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5761 }
5762
Steve Antondcc3c022017-12-22 16:02:54 -08005763 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005764 if (video && !video->rejected &&
5765 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005766 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005767 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005768 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5769 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005770 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005771 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005772 }
5773
Steve Antondcc3c022017-12-22 16:02:54 -08005774 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005775 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005776 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005777 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005778 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5779 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005780 }
5781 }
5782
Steve Anton8a006912017-12-04 15:25:56 -08005783 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005784}
5785
Steve Anton4171afb2017-11-20 10:20:22 -08005786// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005787cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005788 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005789 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005790 MediaTransportInterface* media_transport = nullptr;
5791 if (configuration_.use_media_transport) {
5792 media_transport = GetMediaTransport(mid);
5793 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005794
Steve Anton75737c02017-11-06 10:37:17 -08005795 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005796 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005797 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5798 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005799 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005800 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005801 }
Steve Anton75737c02017-11-06 10:37:17 -08005802 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5803 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005804 voice_channel->SignalSentPacket.connect(this,
5805 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005806 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005807
Steve Antoneda6ccd2017-12-04 10:21:55 -08005808 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005809}
5810
Steve Anton4171afb2017-11-20 10:20:22 -08005811// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005812cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005813 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005814 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5815
5816 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005817 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005818 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005819 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5820 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005821 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005822 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005823 }
Steve Anton75737c02017-11-06 10:37:17 -08005824 video_channel->SignalDtlsSrtpSetupFailure.connect(
5825 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005826 video_channel->SignalSentPacket.connect(this,
5827 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005828 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005829
Steve Antoneda6ccd2017-12-04 10:21:55 -08005830 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005831}
5832
Zhi Huange830e682018-03-30 10:48:35 -07005833bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005834 switch (data_channel_type_) {
5835 case cricket::DCT_MEDIA_TRANSPORT:
5836 if (network_thread()->Invoke<bool>(
5837 RTC_FROM_HERE,
5838 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5839 this, mid))) {
5840 for (const auto& channel : sctp_data_channels_) {
5841 channel->OnTransportChannelCreated();
5842 }
5843 return true;
5844 }
Steve Anton75737c02017-11-06 10:37:17 -08005845 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005846 case cricket::DCT_SCTP:
5847 if (!sctp_factory_) {
5848 RTC_LOG(LS_ERROR)
5849 << "Trying to create SCTP transport, but didn't compile with "
5850 "SCTP support (HAVE_SCTP)";
5851 return false;
5852 }
5853 if (!network_thread()->Invoke<bool>(
5854 RTC_FROM_HERE,
5855 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5856 return false;
5857 }
5858 for (const auto& channel : sctp_data_channels_) {
5859 channel->OnTransportChannelCreated();
5860 }
5861 return true;
5862 case cricket::DCT_RTP:
5863 default:
5864 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5865 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5866 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5867 SrtpRequired(), GetCryptoOptions());
5868 if (!rtp_data_channel_) {
5869 return false;
5870 }
5871 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5872 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5873 rtp_data_channel_->SignalSentPacket.connect(
5874 this, &PeerConnection::OnSentPacket_w);
5875 rtp_data_channel_->SetRtpTransport(rtp_transport);
5876 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005877 }
5878
Steve Anton75737c02017-11-06 10:37:17 -08005879 return true;
5880}
5881
5882Call::Stats PeerConnection::GetCallStats() {
5883 if (!worker_thread()->IsCurrent()) {
5884 return worker_thread()->Invoke<Call::Stats>(
5885 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5886 }
5887 if (call_) {
5888 return call_->GetStats();
5889 } else {
5890 return Call::Stats();
5891 }
5892}
5893
Zhi Huange830e682018-03-30 10:48:35 -07005894bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005895 RTC_DCHECK(network_thread()->IsCurrent());
5896 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005897 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005898 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005899 RTC_DCHECK(dtls_transport);
5900 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005901 RTC_DCHECK(sctp_transport_);
5902 sctp_invoker_.reset(new rtc::AsyncInvoker());
5903 sctp_transport_->SignalReadyToSendData.connect(
5904 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5905 sctp_transport_->SignalDataReceived.connect(
5906 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005907 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5908 // another thread. Would be nice if there was a helper class similar to
5909 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5910 // code.
5911 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5912 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5913 sctp_transport_->SignalClosingProcedureComplete.connect(
5914 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005915 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005916 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005917 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005918}
5919
5920void PeerConnection::DestroySctpTransport_n() {
5921 RTC_DCHECK(network_thread()->IsCurrent());
5922 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005923 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005924 sctp_invoker_.reset(nullptr);
5925 sctp_ready_to_send_data_ = false;
5926}
5927
5928void PeerConnection::OnSctpTransportReadyToSendData_n() {
5929 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5930 RTC_DCHECK(network_thread()->IsCurrent());
5931 // Note: Cannot use rtc::Bind here because it will grab a reference to
5932 // PeerConnection and potentially cause PeerConnection to live longer than
5933 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5934 // be destroyed before PeerConnection is destroyed, and at that point all
5935 // pending tasks will be cleared.
5936 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5937 OnSctpTransportReadyToSendData_s(true);
5938 });
5939}
5940
5941void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5942 RTC_DCHECK(signaling_thread()->IsCurrent());
5943 sctp_ready_to_send_data_ = ready;
5944 SignalSctpReadyToSendData(ready);
5945}
5946
5947void PeerConnection::OnSctpTransportDataReceived_n(
5948 const cricket::ReceiveDataParams& params,
5949 const rtc::CopyOnWriteBuffer& payload) {
5950 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5951 RTC_DCHECK(network_thread()->IsCurrent());
5952 // Note: Cannot use rtc::Bind here because it will grab a reference to
5953 // PeerConnection and potentially cause PeerConnection to live longer than
5954 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5955 // be destroyed before PeerConnection is destroyed, and at that point all
5956 // pending tasks will be cleared.
5957 sctp_invoker_->AsyncInvoke<void>(
5958 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5959 OnSctpTransportDataReceived_s(params, payload);
5960 });
5961}
5962
5963void PeerConnection::OnSctpTransportDataReceived_s(
5964 const cricket::ReceiveDataParams& params,
5965 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005966 RTC_DCHECK_RUN_ON(signaling_thread());
5967 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005968 SignalSctpDataReceived(params, payload);
5969 }
5970}
5971
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005972void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005973 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5974 RTC_DCHECK(network_thread()->IsCurrent());
5975 sctp_invoker_->AsyncInvoke<void>(
5976 RTC_FROM_HERE, signaling_thread(),
5977 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005978 &SignalSctpClosingProcedureStartedRemotely, sid));
5979}
5980
5981void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5982 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5983 RTC_DCHECK(network_thread()->IsCurrent());
5984 sctp_invoker_->AsyncInvoke<void>(
5985 RTC_FROM_HERE, signaling_thread(),
5986 rtc::Bind(&sigslot::signal1<int>::operator(),
5987 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005988}
5989
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005990bool PeerConnection::SetupMediaTransportForDataChannels_n(
5991 const std::string& mid) {
5992 media_transport_ = transport_controller_->GetMediaTransport(mid);
5993 if (!media_transport_) {
5994 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
5995 return false;
5996 }
5997
5998 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
5999 media_transport_->SetDataSink(this);
6000 media_transport_data_mid_ = mid;
6001 transport_controller_->SignalMediaTransportStateChanged.connect(
6002 this, &PeerConnection::OnMediaTransportStateChanged_n);
6003 // Check the initial state right away, in case transport is already writable.
6004 OnMediaTransportStateChanged_n();
6005 return true;
6006}
6007
6008void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6009 if (!media_transport_) {
6010 return;
6011 }
6012 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6013 media_transport_data_mid_.reset();
6014 media_transport_->SetDataSink(nullptr);
6015 media_transport_invoker_ = nullptr;
6016 media_transport_ = nullptr;
6017}
6018
6019void PeerConnection::OnMediaTransportStateChanged_n() {
6020 if (!media_transport_data_mid_ ||
6021 transport_controller_->GetMediaTransportState(
6022 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6023 return;
6024 }
6025 media_transport_invoker_->AsyncInvoke<void>(
6026 RTC_FROM_HERE, signaling_thread(), [this] {
6027 RTC_DCHECK_RUN_ON(signaling_thread());
6028 media_transport_ready_to_send_data_ = true;
6029 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6030 });
6031}
6032
Steve Anton75737c02017-11-06 10:37:17 -08006033// Returns false if bundle is enabled and rtcp_mux is disabled.
6034bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6035 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6036 if (!bundle_enabled)
6037 return true;
6038
6039 const cricket::ContentGroup* bundle_group =
6040 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6041 RTC_DCHECK(bundle_group != NULL);
6042
6043 const cricket::ContentInfos& contents = desc->contents();
6044 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6045 citer != contents.end(); ++citer) {
6046 const cricket::ContentInfo* content = (&*citer);
6047 RTC_DCHECK(content != NULL);
6048 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006049 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006050 if (!HasRtcpMuxEnabled(content))
6051 return false;
6052 }
6053 }
6054 // RTCP-MUX is enabled in all the contents.
6055 return true;
6056}
6057
6058bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006059 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006060}
6061
Steve Anton8a006912017-12-04 15:25:56 -08006062RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006063 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006064 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006065 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006066 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006067 }
6068
6069 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006071 }
6072
Steve Anton3828c062017-12-06 10:34:51 -08006073 SdpType type = sdesc->GetType();
6074 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6075 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006076 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006077 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006078 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006079 }
6080
6081 // Verify crypto settings.
6082 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006083 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6084 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006085 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006086 if (!crypto_error.ok()) {
6087 return crypto_error;
6088 }
Steve Anton75737c02017-11-06 10:37:17 -08006089 }
6090
6091 // Verify ice-ufrag and ice-pwd.
6092 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006093 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6094 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006095 }
6096
6097 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006098 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6099 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006100 }
6101
6102 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6103 // m-lines that do not rtcp-mux enabled.
6104
6105 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006106 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006107 // With an answer we want to compare the new answer session description with
6108 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006109 const cricket::SessionDescription* offer_desc =
6110 (source == cricket::CS_LOCAL) ? remote_description()->description()
6111 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006112 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6113 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6114 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006115 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6116 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006117 }
6118 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006119 // The re-offers should respect the order of m= sections in current
6120 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006121 // With a re-offer, either the current local or current remote descriptions
6122 // could be the most up to date, so we would like to check against both of
6123 // them if they exist. It could be the case that one of them has a 0 port
6124 // for a media section, but the other does not. This is important to check
6125 // against in the case that we are recycling an m= section.
6126 const cricket::SessionDescription* current_desc = nullptr;
6127 const cricket::SessionDescription* secondary_current_desc = nullptr;
6128 if (local_description()) {
6129 current_desc = local_description()->description();
6130 if (remote_description()) {
6131 secondary_current_desc = remote_description()->description();
6132 }
6133 } else if (remote_description()) {
6134 current_desc = remote_description()->description();
6135 }
Steve Anton75737c02017-11-06 10:37:17 -08006136 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006137 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6138 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006139 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6140 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006141 }
6142 }
6143
Steve Antonba42e992018-04-09 14:10:01 -07006144 if (IsUnifiedPlan()) {
6145 // Ensure that each audio and video media section has at most one
6146 // "StreamParams". This will return an error if receiving a session
6147 // description from a "Plan B" endpoint which adds multiple tracks of the
6148 // same type. With Unified Plan, there can only be at most one track per
6149 // media section.
6150 for (const ContentInfo& content : sdesc->description()->contents()) {
6151 const MediaContentDescription& desc = *content.description;
6152 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6153 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6154 desc.streams().size() > 1u) {
6155 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6156 "Media section has more than one track specified "
6157 "with a=ssrc lines which is not supported with "
6158 "Unified Plan.");
6159 }
6160 }
6161 }
6162
Steve Anton8a006912017-12-04 15:25:56 -08006163 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006164}
6165
Steve Anton3828c062017-12-06 10:34:51 -08006166bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006167 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006168 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006169 return (state == PeerConnectionInterface::kStable) ||
6170 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006171 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006172 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006173 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6174 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6175 }
6176}
6177
Steve Anton3828c062017-12-06 10:34:51 -08006178bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006179 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006180 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006181 return (state == PeerConnectionInterface::kStable) ||
6182 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006183 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006184 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006185 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6186 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6187 }
6188}
6189
Steve Antonf8470812017-12-04 10:46:21 -08006190const char* PeerConnection::SessionErrorToString(SessionError error) const {
6191 switch (error) {
6192 case SessionError::kNone:
6193 return "ERROR_NONE";
6194 case SessionError::kContent:
6195 return "ERROR_CONTENT";
6196 case SessionError::kTransport:
6197 return "ERROR_TRANSPORT";
6198 }
6199 RTC_NOTREACHED();
6200 return "";
6201}
6202
Steve Anton75737c02017-11-06 10:37:17 -08006203std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006204 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006205 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6206 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006207 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006208}
6209
Steve Anton8e20f172018-03-06 10:55:04 -08006210void PeerConnection::ReportSdpFormatReceived(
6211 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006212 int num_audio_mlines = 0;
6213 int num_video_mlines = 0;
6214 int num_audio_tracks = 0;
6215 int num_video_tracks = 0;
6216 for (const ContentInfo& content : remote_offer.description()->contents()) {
6217 cricket::MediaType media_type = content.media_description()->type();
6218 int num_tracks = std::max(
6219 1, static_cast<int>(content.media_description()->streams().size()));
6220 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6221 num_audio_mlines += 1;
6222 num_audio_tracks += num_tracks;
6223 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6224 num_video_mlines += 1;
6225 num_video_tracks += num_tracks;
6226 }
6227 }
6228 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6229 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6230 format = kSdpFormatReceivedComplexUnifiedPlan;
6231 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6232 format = kSdpFormatReceivedComplexPlanB;
6233 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6234 format = kSdpFormatReceivedSimple;
6235 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006236 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6237 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006238}
6239
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006240void PeerConnection::NoteUsageEvent(UsageEvent event) {
6241 RTC_DCHECK_RUN_ON(signaling_thread());
6242 usage_event_accumulator_ |= static_cast<int>(event);
6243}
6244
6245void PeerConnection::ReportUsagePattern() const {
6246 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006247 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6248 usage_event_accumulator_,
6249 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006250 const int bad_bits =
6251 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6252 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6253 const int good_bits =
6254 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6255 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6256 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6257 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6258 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006259 // If called after close(), we can't report, because observer may have
6260 // been deallocated, and therefore pointer is null. Write to log instead.
6261 if (observer_) {
6262 Observer()->OnInterestingUsage(usage_event_accumulator_);
6263 } else {
6264 RTC_LOG(LS_INFO) << "Interesting usage signature "
6265 << usage_event_accumulator_
6266 << " observed after observer shutdown";
6267 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006268 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006269}
6270
Steve Anton0ffaaa22018-02-23 10:31:30 -08006271void PeerConnection::ReportNegotiatedSdpSemantics(
6272 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006273 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006274 switch (answer.description()->msid_signaling()) {
6275 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006276 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006277 break;
6278 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006279 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006280 break;
6281 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006282 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006283 break;
6284 case cricket::kMsidSignalingMediaSection |
6285 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006286 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006287 break;
6288 default:
6289 RTC_NOTREACHED();
6290 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006291 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6292 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006293}
6294
Steve Anton75737c02017-11-06 10:37:17 -08006295// We need to check the local/remote description for the Transport instead of
6296// the session, because a new Transport added during renegotiation may have
6297// them unset while the session has them set from the previous negotiation.
6298// Not doing so may trigger the auto generation of transport description and
6299// mess up DTLS identity information, ICE credential, etc.
6300bool PeerConnection::ReadyToUseRemoteCandidate(
6301 const IceCandidateInterface* candidate,
6302 const SessionDescriptionInterface* remote_desc,
6303 bool* valid) {
6304 *valid = true;
6305
6306 const SessionDescriptionInterface* current_remote_desc =
6307 remote_desc ? remote_desc : remote_description();
6308
6309 if (!current_remote_desc) {
6310 return false;
6311 }
6312
6313 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6314 size_t remote_content_size =
6315 current_remote_desc->description()->contents().size();
6316 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006317 RTC_LOG(LS_ERROR)
6318 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6319 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006320
6321 *valid = false;
6322 return false;
6323 }
6324
6325 cricket::ContentInfo content =
6326 current_remote_desc->description()->contents()[mediacontent_index];
6327
6328 const std::string transport_name = GetTransportName(content.name);
6329 if (transport_name.empty()) {
6330 return false;
6331 }
Zhi Huange830e682018-03-30 10:48:35 -07006332 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006333}
6334
6335bool PeerConnection::SrtpRequired() const {
6336 return dtls_enabled_ ||
6337 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6338}
6339
6340void PeerConnection::OnTransportControllerGatheringState(
6341 cricket::IceGatheringState state) {
6342 RTC_DCHECK(signaling_thread()->IsCurrent());
6343 if (state == cricket::kIceGatheringGathering) {
6344 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6345 } else if (state == cricket::kIceGatheringComplete) {
6346 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6347 }
6348}
6349
6350void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006351 std::map<std::string, std::set<cricket::MediaType>>
6352 media_types_by_transport_name;
6353 for (auto transceiver : transceivers_) {
6354 if (transceiver->internal()->channel()) {
6355 const std::string& transport_name =
6356 transceiver->internal()->channel()->transport_name();
6357 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006358 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006359 }
Steve Anton75737c02017-11-06 10:37:17 -08006360 }
6361 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006362 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6363 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006364 }
Zhi Huange830e682018-03-30 10:48:35 -07006365
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006366 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006367 if (transport_name) {
6368 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006369 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006370 }
Zhi Huange830e682018-03-30 10:48:35 -07006371
Steve Antonc7b964c2018-02-01 14:39:45 -08006372 for (const auto& entry : media_types_by_transport_name) {
6373 const std::string& transport_name = entry.first;
6374 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006375 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006376 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006377 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006378 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006379 }
6380 }
6381}
6382// Walk through the ConnectionInfos to gather best connection usage
6383// for IPv4 and IPv6.
6384void PeerConnection::ReportBestConnectionState(
6385 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006386 for (const cricket::TransportChannelStats& channel_stats :
6387 stats.channel_stats) {
6388 for (const cricket::ConnectionInfo& connection_info :
6389 channel_stats.connection_infos) {
6390 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006391 continue;
6392 }
6393
Steve Antonc7b964c2018-02-01 14:39:45 -08006394 const cricket::Candidate& local = connection_info.local_candidate;
6395 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006396
6397 // Increment the counter for IceCandidatePairType.
6398 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6399 (local.type() == RELAY_PORT_TYPE &&
6400 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006401 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6402 GetIceCandidatePairCounter(local, remote),
6403 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006404 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006405 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6406 GetIceCandidatePairCounter(local, remote),
6407 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006408 } else {
6409 RTC_CHECK(0);
6410 }
Steve Anton75737c02017-11-06 10:37:17 -08006411
6412 // Increment the counter for IP type.
6413 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006414 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6415 kBestConnections_IPv4,
6416 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006417 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006418 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6419 kBestConnections_IPv6,
6420 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006421 } else {
6422 RTC_CHECK(0);
6423 }
6424
6425 return;
6426 }
6427 }
6428}
6429
6430void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006431 const cricket::TransportStats& stats,
6432 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006433 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6434 return;
6435 }
6436
6437 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6438 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6439 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6440 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6441 return;
6442 }
6443
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006444 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6445 for (cricket::MediaType media_type : media_types) {
6446 switch (media_type) {
6447 case cricket::MEDIA_TYPE_AUDIO:
6448 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6449 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6450 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6451 break;
6452 case cricket::MEDIA_TYPE_VIDEO:
6453 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6454 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6455 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6456 break;
6457 case cricket::MEDIA_TYPE_DATA:
6458 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6459 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6460 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6461 break;
6462 default:
6463 RTC_NOTREACHED();
6464 continue;
6465 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006466 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006467 }
6468
6469 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6470 for (cricket::MediaType media_type : media_types) {
6471 switch (media_type) {
6472 case cricket::MEDIA_TYPE_AUDIO:
6473 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6474 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6475 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6476 break;
6477 case cricket::MEDIA_TYPE_VIDEO:
6478 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6479 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6480 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6481 break;
6482 case cricket::MEDIA_TYPE_DATA:
6483 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6484 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6485 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6486 break;
6487 default:
6488 RTC_NOTREACHED();
6489 continue;
6490 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006491 }
Steve Anton75737c02017-11-06 10:37:17 -08006492 }
6493}
6494
6495void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6496 RTC_DCHECK(worker_thread()->IsCurrent());
6497 RTC_DCHECK(call_);
6498 call_->OnSentPacket(sent_packet);
6499}
6500
6501const std::string PeerConnection::GetTransportName(
6502 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006503 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006504 if (channel) {
6505 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006506 }
Steve Anton6fec8802017-12-04 10:37:29 -08006507 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006508 RTC_DCHECK(sctp_mid_);
6509 if (content_name == *sctp_mid_) {
6510 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006511 }
6512 }
6513 // Return an empty string if failed to retrieve the transport name.
6514 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006515}
6516
Steve Anton6fec8802017-12-04 10:37:29 -08006517void PeerConnection::DestroyTransceiverChannel(
6518 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6519 transceiver) {
6520 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006521
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006522 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006523 if (channel) {
6524 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006525 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006526 }
6527}
6528
6529void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006530 if (rtp_data_channel_) {
6531 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006532 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006533 rtp_data_channel_ = nullptr;
6534 }
6535
6536 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6537 // grab a reference to this PeerConnection. If this is called from the
6538 // PeerConnection destructor, the RefCountedObject vtable will have already
6539 // been destroyed (since it is a subclass of PeerConnection) and using
6540 // rtc::Bind will cause "Pure virtual function called" error to appear.
6541
6542 if (sctp_transport_) {
6543 OnDataChannelDestroyed();
6544 network_thread()->Invoke<void>(RTC_FROM_HERE,
6545 [this] { DestroySctpTransport_n(); });
6546 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006547
6548 if (media_transport_) {
6549 OnDataChannelDestroyed();
6550 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6551 RTC_DCHECK_RUN_ON(network_thread());
6552 TeardownMediaTransportForDataChannels_n();
6553 });
6554 }
Steve Anton6fec8802017-12-04 10:37:29 -08006555}
6556
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006557void PeerConnection::DestroyChannelInterface(
6558 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006559 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006560 switch (channel->media_type()) {
6561 case cricket::MEDIA_TYPE_AUDIO:
6562 channel_manager()->DestroyVoiceChannel(
6563 static_cast<cricket::VoiceChannel*>(channel));
6564 break;
6565 case cricket::MEDIA_TYPE_VIDEO:
6566 channel_manager()->DestroyVideoChannel(
6567 static_cast<cricket::VideoChannel*>(channel));
6568 break;
6569 case cricket::MEDIA_TYPE_DATA:
6570 channel_manager()->DestroyRtpDataChannel(
6571 static_cast<cricket::RtpDataChannel*>(channel));
6572 break;
6573 default:
6574 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6575 break;
6576 }
Zhi Huange830e682018-03-30 10:48:35 -07006577}
Steve Anton6fec8802017-12-04 10:37:29 -08006578
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006579bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006580 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006581 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006582 cricket::DtlsTransportInternal* dtls_transport,
6583 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006584 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006585 auto base_channel = GetChannel(mid);
6586 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006587 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006588 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006589 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006590 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006591 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006592
6593 call_->MediaTransportChange(media_transport);
6594
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006595 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006596}
6597
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006598PeerConnectionObserver* PeerConnection::Observer() const {
6599 // In earlier production code, the pointer was not cleared on close,
6600 // which might have led to undefined behavior if the observer was not
6601 // deallocated, or strange crashes if it was.
6602 // We use CHECK in order to catch such behavior if it exists.
6603 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6604 RTC_CHECK(observer_);
6605 return observer_;
6606}
6607
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006608CryptoOptions PeerConnection::GetCryptoOptions() {
6609 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6610 // after it has been removed.
6611 return configuration_.crypto_options.has_value()
6612 ? *configuration_.crypto_options
6613 : factory_->options().crypto_options;
6614}
6615
Harald Alvestrand89061872018-01-02 14:08:34 +01006616void PeerConnection::ClearStatsCache() {
6617 if (stats_collector_) {
6618 stats_collector_->ClearCachedStatsReport();
6619 }
6620}
6621
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006622void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006623 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6624 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006625}
6626
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006627} // namespace webrtc