blob: 9c04c31834400177bdecda46747132652aaca649 [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
Harald Alvestrandad88c882018-11-28 16:47:46 +01003349rtc::scoped_refptr<DtlsTransportInterface>
3350PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3351 return transport_controller_->LookupDtlsTransportByMid(mid);
3352}
3353
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003354const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003355 return pending_local_description_ ? pending_local_description_.get()
3356 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
3359const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003360 return pending_remote_description_ ? pending_remote_description_.get()
3361 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003362}
3363
deadbeeffe4a8a42016-12-20 17:56:17 -08003364const SessionDescriptionInterface* PeerConnection::current_local_description()
3365 const {
Steve Anton75737c02017-11-06 10:37:17 -08003366 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003367}
3368
3369const SessionDescriptionInterface* PeerConnection::current_remote_description()
3370 const {
Steve Anton75737c02017-11-06 10:37:17 -08003371 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003372}
3373
3374const SessionDescriptionInterface* PeerConnection::pending_local_description()
3375 const {
Steve Anton75737c02017-11-06 10:37:17 -08003376 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003377}
3378
3379const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3380 const {
Steve Anton75737c02017-11-06 10:37:17 -08003381 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003382}
3383
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003384void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003385 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003386 // Update stats here so that we have the most recent stats for tracks and
3387 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003388 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389
Steve Anton75737c02017-11-06 10:37:17 -08003390 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003391 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003392
Steve Anton8af21862017-12-15 11:20:13 -08003393 for (auto transceiver : transceivers_) {
3394 transceiver->Stop();
3395 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003396
3397 // Ensure that all asynchronous stats requests are completed before destroying
3398 // the transport controller below.
3399 if (stats_collector_) {
3400 stats_collector_->WaitForPendingRequest();
3401 }
3402
3403 // Don't destroy BaseChannels until after stats has been cleaned up so that
3404 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003405 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003406
Qingsi Wang93a84392018-01-30 17:13:09 -08003407 // The event log is used in the transport controller, which must be outlived
3408 // by the former. CreateOffer by the peer connection is implemented
3409 // asynchronously and if the peer connection is closed without resetting the
3410 // WebRTC session description factory, the session description factory would
3411 // call the transport controller.
3412 webrtc_session_desc_factory_.reset();
3413 transport_controller_.reset();
3414
deadbeef42a42632017-03-10 15:18:00 -08003415 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003416 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3417 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003418
Steve Anton978b8762017-09-29 12:15:02 -07003419 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003420 call_.reset();
3421 // The event log must outlive call (and any other object that uses it).
3422 event_log_.reset();
3423 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003424 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003425 // The .h file says that observer can be discarded after close() returns.
3426 // Make sure this is true.
3427 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003428}
3429
Steve Antonad182762018-09-05 20:22:40 +00003430void PeerConnection::OnMessage(rtc::Message* msg) {
3431 switch (msg->message_id) {
3432 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3433 SetSessionDescriptionMsg* param =
3434 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3435 param->observer->OnSuccess();
3436 delete param;
3437 break;
3438 }
3439 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3440 SetSessionDescriptionMsg* param =
3441 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3442 param->observer->OnFailure(std::move(param->error));
3443 delete param;
3444 break;
3445 }
3446 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3447 CreateSessionDescriptionMsg* param =
3448 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3449 param->observer->OnFailure(std::move(param->error));
3450 delete param;
3451 break;
3452 }
3453 case MSG_GETSTATS: {
3454 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3455 StatsReports reports;
3456 stats_->GetStats(param->track, &reports);
3457 param->observer->OnComplete(reports);
3458 delete param;
3459 break;
3460 }
3461 case MSG_FREE_DATACHANNELS: {
3462 sctp_data_channels_to_free_.clear();
3463 break;
3464 }
3465 case MSG_REPORT_USAGE_PATTERN: {
3466 ReportUsagePattern();
3467 break;
3468 }
3469 default:
3470 RTC_NOTREACHED() << "Not implemented";
3471 break;
3472 }
3473}
3474
Steve Antonafb0bb72018-02-20 11:35:37 -08003475cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3476 RTC_DCHECK(!IsUnifiedPlan());
3477 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3478 GetAudioTransceiver()->internal()->channel());
3479 if (voice_channel) {
3480 return voice_channel->media_channel();
3481 } else {
3482 return nullptr;
3483 }
3484}
3485
3486cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3487 RTC_DCHECK(!IsUnifiedPlan());
3488 auto* video_channel = static_cast<cricket::VideoChannel*>(
3489 GetVideoTransceiver()->internal()->channel());
3490 if (video_channel) {
3491 return video_channel->media_channel();
3492 } else {
3493 return nullptr;
3494 }
3495}
3496
Steve Anton4171afb2017-11-20 10:20:22 -08003497void PeerConnection::CreateAudioReceiver(
3498 MediaStreamInterface* stream,
3499 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003500 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3501 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003502 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3503 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003504 auto* audio_receiver = new AudioRtpReceiver(
3505 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003506 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003507 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3508 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3509 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003510 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003511 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003512 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003513}
3514
Steve Anton4171afb2017-11-20 10:20:22 -08003515void PeerConnection::CreateVideoReceiver(
3516 MediaStreamInterface* stream,
3517 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003518 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3519 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003520 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3521 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003522 auto* video_receiver = new VideoRtpReceiver(
3523 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003524 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003525 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3526 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3527 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003528 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003529 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003530 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003531}
3532
deadbeef70ab1a12015-09-28 16:53:55 -07003533// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3534// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003535rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003536 const RtpSenderInfo& remote_sender_info) {
3537 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3538 if (!receiver) {
3539 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3540 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003541 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003542 }
Steve Anton4171afb2017-11-20 10:20:22 -08003543 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3544 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3545 } else {
3546 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3547 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003548 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003549}
3550
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003551void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3552 MediaStreamInterface* stream) {
3553 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003554 RTC_DCHECK(track);
3555 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003556 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003557 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003558 // We already have a sender for this track, so just change the stream_id
3559 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003560 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003561 return;
3562 }
3563
3564 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003565 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003566 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003567 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003568 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003569 // If the sender has already been configured in SDP, we call SetSsrc,
3570 // which will connect the sender to the underlying transport. This can
3571 // occur if a local session description that contains the ID of the sender
3572 // is set before AddStream is called. It can also occur if the local
3573 // session description is not changed and RemoveStream is called, and
3574 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003575 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003576 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003577 if (sender_info) {
3578 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003579 }
3580}
3581
3582// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3583// indefinitely, when we have unified plan SDP.
3584void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3585 MediaStreamInterface* stream) {
3586 RTC_DCHECK(!IsClosed());
3587 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003588 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003589 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3590 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003591 return;
3592 }
Steve Anton4171afb2017-11-20 10:20:22 -08003593 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003594}
3595
3596void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3597 MediaStreamInterface* stream) {
3598 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003599 RTC_DCHECK(track);
3600 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003601 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003602 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003603 // We already have a sender for this track, so just change the stream_id
3604 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003605 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003606 return;
3607 }
3608
3609 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003610 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003611 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003612 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003613 GetVideoTransceiver()->internal()->AddSender(new_sender);
3614 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003615 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003616 if (sender_info) {
3617 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003618 }
3619}
3620
3621void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3622 MediaStreamInterface* stream) {
3623 RTC_DCHECK(!IsClosed());
3624 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003625 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003626 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3627 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003628 return;
3629 }
Steve Anton4171afb2017-11-20 10:20:22 -08003630 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003631}
3632
Steve Antonba818672017-11-06 10:21:57 -08003633void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003634 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003635 if (ice_connection_state_ == new_state) {
3636 return;
3637 }
3638
deadbeefcbecd352015-09-23 11:50:27 -07003639 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003640 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003641 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003642 return;
3643 }
Steve Antonba818672017-11-06 10:21:57 -08003644
Mirko Bonadei675513b2017-11-09 11:09:25 +01003645 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3646 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003647 RTC_DCHECK(ice_connection_state_ !=
3648 PeerConnectionInterface::kIceConnectionClosed);
3649
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003650 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003651 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003652}
3653
Alex Loiko9289eda2018-11-23 16:18:59 +00003654void PeerConnection::SetStandardizedIceConnectionState(
3655 PeerConnectionInterface::IceConnectionState new_state) {
3656 RTC_DCHECK(signaling_thread()->IsCurrent());
3657 if (standardized_ice_connection_state_ == new_state)
3658 return;
3659 if (IsClosed())
3660 return;
3661 standardized_ice_connection_state_ = new_state;
3662 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3663 // the old one once disconnects are handled properly.
3664}
3665
Jonas Olsson635474e2018-10-18 15:58:17 +02003666void PeerConnection::SetConnectionState(
3667 PeerConnectionInterface::PeerConnectionState new_state) {
3668 RTC_DCHECK(signaling_thread()->IsCurrent());
3669 if (connection_state_ == new_state)
3670 return;
3671 if (IsClosed())
3672 return;
3673 connection_state_ = new_state;
3674 Observer()->OnConnectionChange(new_state);
3675}
3676
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003677void PeerConnection::OnIceGatheringChange(
3678 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003679 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003680 if (IsClosed()) {
3681 return;
3682 }
3683 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003684 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003685}
3686
jbauch81bf7b02017-03-25 08:31:12 -07003687void PeerConnection::OnIceCandidate(
3688 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003689 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003690 if (IsClosed()) {
3691 return;
3692 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003693 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003694 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3695 candidate->candidate().address().IsPrivateIP()) {
3696 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3697 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003698 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003699}
3700
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003701void PeerConnection::OnIceCandidatesRemoved(
3702 const std::vector<cricket::Candidate>& candidates) {
3703 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003704 if (IsClosed()) {
3705 return;
3706 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003707 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003708}
3709
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003710void PeerConnection::ChangeSignalingState(
3711 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003712 RTC_DCHECK(signaling_thread()->IsCurrent());
3713 if (signaling_state_ == signaling_state) {
3714 return;
3715 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003716 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3717 << GetSignalingStateString(signaling_state_)
3718 << " New state: "
3719 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003720 signaling_state_ = signaling_state;
3721 if (signaling_state == kClosed) {
3722 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003723 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003724 standardized_ice_connection_state_ =
3725 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003726 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3727 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003728 if (ice_gathering_state_ != kIceGatheringComplete) {
3729 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003730 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003731 }
3732 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003733 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003734}
3735
deadbeefeb459812015-12-15 19:24:43 -08003736void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3737 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003738 if (IsClosed()) {
3739 return;
3740 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003741 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003742 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003743}
3744
deadbeefeb459812015-12-15 19:24:43 -08003745void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3746 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003747 if (IsClosed()) {
3748 return;
3749 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003750 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003751 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003752}
3753
3754void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3755 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003756 if (IsClosed()) {
3757 return;
3758 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003759 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003760 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003761}
3762
3763void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3764 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003765 if (IsClosed()) {
3766 return;
3767 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003768 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003769 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003770}
3771
Henrik Boström31638672017-11-23 17:48:32 +01003772void PeerConnection::PostSetSessionDescriptionSuccess(
3773 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003774 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3775 signaling_thread()->Post(RTC_FROM_HERE, this,
3776 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003777}
3778
deadbeefab9b2d12015-10-14 11:33:11 -07003779void PeerConnection::PostSetSessionDescriptionFailure(
3780 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003781 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003782 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003783 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3784 msg->error = std::move(error);
3785 signaling_thread()->Post(RTC_FROM_HERE, this,
3786 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003787}
3788
3789void PeerConnection::PostCreateSessionDescriptionFailure(
3790 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003791 RTCError error) {
3792 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003793 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3794 msg->error = std::move(error);
3795 signaling_thread()->Post(RTC_FROM_HERE, this,
3796 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003797}
3798
zhihuang1c378ed2017-08-17 14:10:50 -07003799void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003800 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003801 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003802 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003803
Steve Antondcc3c022017-12-22 16:02:54 -08003804 if (IsUnifiedPlan()) {
3805 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3806 } else {
3807 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3808 }
3809
Steve Antonfa2260d2017-12-28 16:38:23 -08003810 // Intentionally unset the data channel type for RTP data channel with the
3811 // second condition. Otherwise the RTP data channels would be successfully
3812 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3813 // when building with chromium. We want to leave RTP data channels broken, so
3814 // people won't try to use them.
3815 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3816 session_options->data_channel_type = data_channel_type();
3817 }
3818
Steve Antondcc3c022017-12-22 16:02:54 -08003819 // Apply ICE restart flag and renomination flag.
3820 for (auto& options : session_options->media_description_options) {
3821 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3822 options.transport_options.enable_ice_renomination =
3823 configuration_.enable_ice_renomination;
3824 }
3825
3826 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003827 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08003828 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003829 session_options->pooled_ice_credentials =
3830 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3831 RTC_FROM_HERE,
3832 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3833 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003834 session_options->offer_extmap_allow_mixed =
3835 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003836}
3837
3838void PeerConnection::GetOptionsForPlanBOffer(
3839 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3840 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003841 // Figure out transceiver directional preferences.
3842 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3843 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3844
3845 // By default, generate sendrecv/recvonly m= sections.
3846 bool recv_audio = true;
3847 bool recv_video = true;
3848
3849 // By default, only offer a new m= section if we have media to send with it.
3850 bool offer_new_audio_description = send_audio;
3851 bool offer_new_video_description = send_video;
3852 bool offer_new_data_description = HasDataChannels();
3853
3854 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003855 if (offer_answer_options.offer_to_receive_audio !=
3856 RTCOfferAnswerOptions::kUndefined) {
3857 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003858 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003859 offer_new_audio_description ||
3860 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003861 }
Steve Antondcc3c022017-12-22 16:02:54 -08003862 if (offer_answer_options.offer_to_receive_video !=
3863 RTCOfferAnswerOptions::kUndefined) {
3864 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003865 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003866 offer_new_video_description ||
3867 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003868 }
3869
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003870 absl::optional<size_t> audio_index;
3871 absl::optional<size_t> video_index;
3872 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003873 // If a current description exists, generate m= sections in the same order,
3874 // using the first audio/video/data section that appears and rejecting
3875 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003876 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003877 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003878 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003879 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3880 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3881 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003882 }
3883
zhihuang1c378ed2017-08-17 14:10:50 -07003884 // Add audio/video/data m= sections to the end if needed.
3885 if (!audio_index && offer_new_audio_description) {
3886 session_options->media_description_options.push_back(
3887 cricket::MediaDescriptionOptions(
3888 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003889 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3890 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003891 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003892 }
zhihuang1c378ed2017-08-17 14:10:50 -07003893 if (!video_index && offer_new_video_description) {
3894 session_options->media_description_options.push_back(
3895 cricket::MediaDescriptionOptions(
3896 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003897 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3898 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003899 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003900 }
zhihuang1c378ed2017-08-17 14:10:50 -07003901 if (!data_index && offer_new_data_description) {
3902 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003903 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003904 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003905 }
3906
3907 cricket::MediaDescriptionOptions* audio_media_description_options =
3908 !audio_index ? nullptr
3909 : &session_options->media_description_options[*audio_index];
3910 cricket::MediaDescriptionOptions* video_media_description_options =
3911 !video_index ? nullptr
3912 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003913
Steve Anton4171afb2017-11-20 10:20:22 -08003914 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003915 video_media_description_options,
3916 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003917}
3918
3919// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3920// and return a reference to it.
3921// Generated MIDs should be no more than 3 bytes long to take up less space in
3922// the RTP packet.
3923static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3924 RTC_DCHECK(used_mids);
3925 // We're boring: just generate MIDs 0, 1, 2, ...
3926 size_t i = 0;
3927 std::set<std::string>::iterator it;
3928 bool inserted;
3929 do {
3930 std::string mid = rtc::ToString(i++);
3931 auto insert_result = used_mids->insert(mid);
3932 it = insert_result.first;
3933 inserted = insert_result.second;
3934 } while (!inserted);
3935 return *it;
3936}
3937
3938static cricket::MediaDescriptionOptions
3939GetMediaDescriptionOptionsForTransceiver(
3940 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3941 transceiver,
3942 const std::string& mid) {
3943 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003944 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003945 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003946 // This behavior is specified in JSEP. The gist is that:
3947 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3948 // sendrecv.
3949 // 2. If the MSID is included, then it must be included in any subsequent
3950 // offer/answer exactly the same until the RtpTransceiver is stopped.
3951 if (!transceiver->stopped() &&
3952 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3953 transceiver->internal()->has_ever_been_used_to_send())) {
3954 cricket::SenderOptions sender_options;
3955 sender_options.track_id = transceiver->sender()->id();
3956 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003957 int num_send_encoding_layers =
3958 transceiver->sender()->init_send_encodings().size();
3959 sender_options.num_sim_layers =
3960 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003961 media_description_options.sender_options.push_back(sender_options);
3962 }
Steve Antondcc3c022017-12-22 16:02:54 -08003963 return media_description_options;
3964}
3965
3966void PeerConnection::GetOptionsForUnifiedPlanOffer(
3967 const RTCOfferAnswerOptions& offer_answer_options,
3968 cricket::MediaSessionOptions* session_options) {
3969 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3970 // Offers) and 5.2.2 (Subsequent Offers).
3971 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3972 const ContentInfos& local_contents =
3973 (local_description() ? local_description()->description()->contents()
3974 : ContentInfos());
3975 const ContentInfos& remote_contents =
3976 (remote_description() ? remote_description()->description()->contents()
3977 : ContentInfos());
3978 // The mline indices that can be recycled. New transceivers should reuse these
3979 // slots first.
3980 std::queue<size_t> recycleable_mline_indices;
3981 // Track the MIDs used in previous offer/answer exchanges and the current
3982 // offer so that new, unique MIDs are generated.
3983 std::set<std::string> used_mids = seen_mids_;
3984 // First, go through each media section that exists in either the local or
3985 // remote description and generate a media section in this offer for the
3986 // associated transceiver. If a media section can be recycled, generate a
3987 // default, rejected media section here that can be later overwritten.
3988 for (size_t i = 0;
3989 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3990 // Either |local_content| or |remote_content| is non-null.
3991 const ContentInfo* local_content =
3992 (i < local_contents.size() ? &local_contents[i] : nullptr);
3993 const ContentInfo* remote_content =
3994 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3995 bool had_been_rejected = (local_content && local_content->rejected) ||
3996 (remote_content && remote_content->rejected);
3997 const std::string& mid =
3998 (local_content ? local_content->name : remote_content->name);
3999 cricket::MediaType media_type =
4000 (local_content ? local_content->media_description()->type()
4001 : remote_content->media_description()->type());
4002 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4003 media_type == cricket::MEDIA_TYPE_VIDEO) {
4004 auto transceiver = GetAssociatedTransceiver(mid);
4005 RTC_CHECK(transceiver);
4006 // A media section is considered eligible for recycling if it is marked as
4007 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004008 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004009 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004010 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4011 RtpTransceiverDirection::kInactive,
4012 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004013 recycleable_mline_indices.push(i);
4014 } else {
4015 session_options->media_description_options.push_back(
4016 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4017 // CreateOffer shouldn't really cause any state changes in
4018 // PeerConnection, but we need a way to match new transceivers to new
4019 // media sections in SetLocalDescription and JSEP specifies this is done
4020 // by recording the index of the media section generated for the
4021 // transceiver in the offer.
4022 transceiver->internal()->set_mline_index(i);
4023 }
4024 } else {
4025 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004026 RTC_CHECK(GetDataMid());
4027 if (had_been_rejected || mid != *GetDataMid()) {
4028 session_options->media_description_options.push_back(
4029 GetMediaDescriptionOptionsForRejectedData(mid));
4030 } else {
4031 session_options->media_description_options.push_back(
4032 GetMediaDescriptionOptionsForActiveData(mid));
4033 }
Steve Antondcc3c022017-12-22 16:02:54 -08004034 }
4035 }
4036 // Next, look for transceivers that are newly added (that is, are not stopped
4037 // and not associated). Reuse media sections marked as recyclable first,
4038 // otherwise append to the end of the offer. New media sections should be
4039 // added in the order they were added to the PeerConnection.
4040 for (auto transceiver : transceivers_) {
4041 if (transceiver->mid() || transceiver->stopped()) {
4042 continue;
4043 }
4044 size_t mline_index;
4045 if (!recycleable_mline_indices.empty()) {
4046 mline_index = recycleable_mline_indices.front();
4047 recycleable_mline_indices.pop();
4048 session_options->media_description_options[mline_index] =
4049 GetMediaDescriptionOptionsForTransceiver(transceiver,
4050 AllocateMid(&used_mids));
4051 } else {
4052 mline_index = session_options->media_description_options.size();
4053 session_options->media_description_options.push_back(
4054 GetMediaDescriptionOptionsForTransceiver(transceiver,
4055 AllocateMid(&used_mids)));
4056 }
4057 // See comment above for why CreateOffer changes the transceiver's state.
4058 transceiver->internal()->set_mline_index(mline_index);
4059 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004060 // Lastly, add a m-section if we have local data channels and an m section
4061 // does not already exist.
4062 if (!GetDataMid() && HasDataChannels()) {
4063 session_options->media_description_options.push_back(
4064 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4065 }
Steve Antondcc3c022017-12-22 16:02:54 -08004066}
4067
4068void PeerConnection::GetOptionsForAnswer(
4069 const RTCOfferAnswerOptions& offer_answer_options,
4070 cricket::MediaSessionOptions* session_options) {
4071 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4072
4073 if (IsUnifiedPlan()) {
4074 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4075 } else {
4076 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4077 }
4078
Steve Antonfa2260d2017-12-28 16:38:23 -08004079 // Intentionally unset the data channel type for RTP data channel. Otherwise
4080 // the RTP data channels would be successfully negotiated by default and the
4081 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4082 // We want to leave RTP data channels broken, so people won't try to use them.
4083 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4084 session_options->data_channel_type = data_channel_type();
4085 }
4086
Steve Antondcc3c022017-12-22 16:02:54 -08004087 // Apply ICE renomination flag.
4088 for (auto& options : session_options->media_description_options) {
4089 options.transport_options.enable_ice_renomination =
4090 configuration_.enable_ice_renomination;
4091 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004092
4093 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004094 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08004095 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004096 session_options->pooled_ice_credentials =
4097 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4098 RTC_FROM_HERE,
4099 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4100 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004101}
4102
Steve Antondcc3c022017-12-22 16:02:54 -08004103void PeerConnection::GetOptionsForPlanBAnswer(
4104 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004105 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004106 // Figure out transceiver directional preferences.
4107 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4108 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4109
4110 // By default, generate sendrecv/recvonly m= sections. The direction is also
4111 // restricted by the direction in the offer.
4112 bool recv_audio = true;
4113 bool recv_video = true;
4114
4115 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004116 if (offer_answer_options.offer_to_receive_audio !=
4117 RTCOfferAnswerOptions::kUndefined) {
4118 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004119 }
Steve Antondcc3c022017-12-22 16:02:54 -08004120 if (offer_answer_options.offer_to_receive_video !=
4121 RTCOfferAnswerOptions::kUndefined) {
4122 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004123 }
4124
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004125 absl::optional<size_t> audio_index;
4126 absl::optional<size_t> video_index;
4127 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004128
4129 // Generate m= sections that match those in the offer.
4130 // Note that mediasession.cc will handle intersection our preferred
4131 // direction with the offered direction.
4132 GenerateMediaDescriptionOptions(
4133 remote_description(),
4134 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4135 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4136 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004137
4138 cricket::MediaDescriptionOptions* audio_media_description_options =
4139 !audio_index ? nullptr
4140 : &session_options->media_description_options[*audio_index];
4141 cricket::MediaDescriptionOptions* video_media_description_options =
4142 !video_index ? nullptr
4143 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004144
Steve Anton4171afb2017-11-20 10:20:22 -08004145 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004146 video_media_description_options,
4147 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004148}
zhihuangaf388472016-11-02 16:49:48 -07004149
Steve Antondcc3c022017-12-22 16:02:54 -08004150void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4151 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4152 cricket::MediaSessionOptions* session_options) {
4153 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4154 // Answers) and 5.3.2 (Subsequent Answers).
4155 RTC_DCHECK(remote_description());
4156 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4157 for (const ContentInfo& content :
4158 remote_description()->description()->contents()) {
4159 cricket::MediaType media_type = content.media_description()->type();
4160 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4161 media_type == cricket::MEDIA_TYPE_VIDEO) {
4162 auto transceiver = GetAssociatedTransceiver(content.name);
4163 RTC_CHECK(transceiver);
4164 session_options->media_description_options.push_back(
4165 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4166 } else {
4167 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004168 // Reject all data sections if data channels are disabled.
4169 // Reject a data section if it has already been rejected.
4170 // Reject all data sections except for the first one.
4171 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4172 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004173 session_options->media_description_options.push_back(
4174 GetMediaDescriptionOptionsForRejectedData(content.name));
4175 } else {
4176 session_options->media_description_options.push_back(
4177 GetMediaDescriptionOptionsForActiveData(content.name));
4178 }
Steve Antondcc3c022017-12-22 16:02:54 -08004179 }
4180 }
htaa2a49d92016-03-04 02:51:39 -08004181}
4182
zhihuang1c378ed2017-08-17 14:10:50 -07004183void PeerConnection::GenerateMediaDescriptionOptions(
4184 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004185 RtpTransceiverDirection audio_direction,
4186 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004187 absl::optional<size_t>* audio_index,
4188 absl::optional<size_t>* video_index,
4189 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004190 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004191 for (const cricket::ContentInfo& content :
4192 session_desc->description()->contents()) {
4193 if (IsAudioContent(&content)) {
4194 // If we already have an audio m= section, reject this extra one.
4195 if (*audio_index) {
4196 session_options->media_description_options.push_back(
4197 cricket::MediaDescriptionOptions(
4198 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004199 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004200 } else {
4201 session_options->media_description_options.push_back(
4202 cricket::MediaDescriptionOptions(
4203 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004204 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004205 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004206 }
4207 } else if (IsVideoContent(&content)) {
4208 // If we already have an video m= section, reject this extra one.
4209 if (*video_index) {
4210 session_options->media_description_options.push_back(
4211 cricket::MediaDescriptionOptions(
4212 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004213 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004214 } else {
4215 session_options->media_description_options.push_back(
4216 cricket::MediaDescriptionOptions(
4217 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004218 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004219 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004220 }
4221 } else {
4222 RTC_DCHECK(IsDataContent(&content));
4223 // If we already have an data m= section, reject this extra one.
4224 if (*data_index) {
4225 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004226 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004227 } else {
4228 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004229 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004230 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004231 }
4232 }
htaa2a49d92016-03-04 02:51:39 -08004233 }
deadbeefab9b2d12015-10-14 11:33:11 -07004234}
4235
Steve Antonfa2260d2017-12-28 16:38:23 -08004236cricket::MediaDescriptionOptions
4237PeerConnection::GetMediaDescriptionOptionsForActiveData(
4238 const std::string& mid) const {
4239 // Direction for data sections is meaningless, but legacy endpoints might
4240 // expect sendrecv.
4241 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4242 RtpTransceiverDirection::kSendRecv,
4243 /*stopped=*/false);
4244 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4245 return options;
4246}
4247
4248cricket::MediaDescriptionOptions
4249PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4250 const std::string& mid) const {
4251 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4252 RtpTransceiverDirection::kInactive,
4253 /*stopped=*/true);
4254 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4255 return options;
4256}
4257
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004258absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004259 switch (data_channel_type_) {
4260 case cricket::DCT_RTP:
4261 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004262 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004263 }
4264 return rtp_data_channel_->content_name();
4265 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004266 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004267 case cricket::DCT_MEDIA_TRANSPORT:
4268 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004269 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004270 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004271 }
4272}
4273
Steve Anton4171afb2017-11-20 10:20:22 -08004274void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4275 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4276 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004277 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004278}
4279
Steve Anton4171afb2017-11-20 10:20:22 -08004280void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004281 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004282 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004283 cricket::MediaType media_type,
4284 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004285 RTC_DCHECK(!IsUnifiedPlan());
4286
Steve Anton4171afb2017-11-20 10:20:22 -08004287 std::vector<RtpSenderInfo>* current_senders =
4288 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004289
Steve Anton4171afb2017-11-20 10:20:22 -08004290 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004291 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004292 for (auto sender_it = current_senders->begin();
4293 sender_it != current_senders->end();
4294 /* incremented manually */) {
4295 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004296 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004297 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004298 std::string params_stream_id;
4299 if (params) {
4300 params_stream_id =
4301 (!params->first_stream_id().empty() ? params->first_stream_id()
4302 : kDefaultStreamId);
4303 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004304 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004305 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004306 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004307 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004308 sender_exists) {
4309 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004310 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004311 OnRemoteSenderRemoved(info, media_type);
4312 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004313 }
4314 }
4315
Steve Anton4171afb2017-11-20 10:20:22 -08004316 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004317 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004318 if (!params.has_ssrcs()) {
4319 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4320 // sender, this means it is coming from a Unified Plan endpoint,so we just
4321 // create a default.
4322 default_sender_needed = true;
4323 break;
4324 }
4325
Seth Hampson845e8782018-03-02 11:34:10 -08004326 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004327 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004328 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4329 // not supported in Plan B, we just take the first here and create the
4330 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004331 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004332 (!params.first_stream_id().empty() ? params.first_stream_id()
4333 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004334 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004335 uint32_t ssrc = params.first_ssrc();
4336
4337 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004338 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004339 if (!stream) {
4340 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004341 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004342 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004343 remote_streams_->AddStream(stream);
4344 new_streams->AddStream(stream);
4345 }
4346
Steve Anton4171afb2017-11-20 10:20:22 -08004347 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004348 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004349 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004350 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004351 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004352 }
4353 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004354
Steve Anton4171afb2017-11-20 10:20:22 -08004355 // Add default sender if necessary.
4356 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004357 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004358 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004359 if (!default_stream) {
4360 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004361 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004362 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004363 remote_streams_->AddStream(default_stream);
4364 new_streams->AddStream(default_stream);
4365 }
Steve Anton4171afb2017-11-20 10:20:22 -08004366 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4367 ? kDefaultAudioSenderId
4368 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004369 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004370 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004371 if (!default_sender_info) {
4372 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004373 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004374 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004375 }
4376 }
deadbeefab9b2d12015-10-14 11:33:11 -07004377}
4378
Steve Anton4171afb2017-11-20 10:20:22 -08004379void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4380 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004381 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4382 << " receiver for track_id=" << sender_info.sender_id
4383 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004384
Steve Anton3d954a62018-04-02 11:27:23 -07004385 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004386 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004387 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004388 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004389 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004390 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004391 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004392 }
4393}
4394
Steve Anton4171afb2017-11-20 10:20:22 -08004395void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4396 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004397 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4398 << " receiver for track_id=" << sender_info.sender_id
4399 << " and stream_id=" << sender_info.stream_id;
4400
Seth Hampson845e8782018-03-02 11:34:10 -08004401 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004402
Henrik Boström933d8b02017-10-10 10:05:16 -07004403 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004404 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004405 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4406 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004407 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004408 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004409 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004410 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004411 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004412 }
4413 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004414 // Stopping or destroying a VideoRtpReceiver will end the
4415 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004416 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004417 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004418 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004419 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004420 // There's no guarantee the track is still available, e.g. the track may
4421 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004422 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004423 }
4424 } else {
nisseede5da42017-01-12 05:15:36 -08004425 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004426 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004427 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004428 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004429 }
deadbeefab9b2d12015-10-14 11:33:11 -07004430}
4431
4432void PeerConnection::UpdateEndedRemoteMediaStreams() {
4433 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4434 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4435 MediaStreamInterface* stream = remote_streams_->at(i);
4436 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4437 streams_to_remove.push_back(stream);
4438 }
4439 }
4440
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004441 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004442 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004443 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004444 }
4445}
4446
Steve Anton4171afb2017-11-20 10:20:22 -08004447void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004448 const std::vector<cricket::StreamParams>& streams,
4449 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004450 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004451
Seth Hampson845e8782018-03-02 11:34:10 -08004452 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004453 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004454 for (auto sender_it = current_senders->begin();
4455 sender_it != current_senders->end();
4456 /* incremented manually */) {
4457 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004458 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004459 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4460 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004461 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004462 OnLocalSenderRemoved(info, media_type);
4463 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004464 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004465 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004466 }
4467 }
4468
Steve Anton4171afb2017-11-20 10:20:22 -08004469 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004470 for (const cricket::StreamParams& params : streams) {
4471 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004472 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004473 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004474 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004475 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004476 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004477 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004478 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004479 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004480 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004481 }
4482 }
4483}
4484
Steve Anton4171afb2017-11-20 10:20:22 -08004485void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4486 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004487 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004488 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004489 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004490 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4491 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004492 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004493 return;
4494 }
4495
deadbeeffac06552015-11-25 11:26:01 -08004496 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004497 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004498 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004499 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004500 }
deadbeeffac06552015-11-25 11:26:01 -08004501
Seth Hampson5b4f0752018-04-02 16:31:36 -07004502 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004503 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004504}
4505
Steve Anton4171afb2017-11-20 10:20:22 -08004506void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4507 cricket::MediaType media_type) {
4508 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004509 if (!sender) {
4510 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004511 // SessionDescriptions has been renegotiated.
4512 return;
4513 }
deadbeeffac06552015-11-25 11:26:01 -08004514
4515 // A sender has been removed from the SessionDescription but it's still
4516 // associated with the PeerConnection. This only occurs if the SDP doesn't
4517 // match with the calls to CreateSender, AddStream and RemoveStream.
4518 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004519 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004520 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004521 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004522 }
deadbeeffac06552015-11-25 11:26:01 -08004523
Steve Anton4171afb2017-11-20 10:20:22 -08004524 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004525}
4526
4527void PeerConnection::UpdateLocalRtpDataChannels(
4528 const cricket::StreamParamsVec& streams) {
4529 std::vector<std::string> existing_channels;
4530
4531 // Find new and active data channels.
4532 for (const cricket::StreamParams& params : streams) {
4533 // |it->sync_label| is actually the data channel label. The reason is that
4534 // we use the same naming of data channels as we do for
4535 // MediaStreams and Tracks.
4536 // For MediaStreams, the sync_label is the MediaStream label and the
4537 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004538 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004539 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004540 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004541 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004542 continue;
4543 }
4544 // Set the SSRC the data channel should use for sending.
4545 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4546 existing_channels.push_back(data_channel_it->first);
4547 }
4548
4549 UpdateClosingRtpDataChannels(existing_channels, true);
4550}
4551
4552void PeerConnection::UpdateRemoteRtpDataChannels(
4553 const cricket::StreamParamsVec& streams) {
4554 std::vector<std::string> existing_channels;
4555
4556 // Find new and active data channels.
4557 for (const cricket::StreamParams& params : streams) {
4558 // The data channel label is either the mslabel or the SSRC if the mslabel
4559 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004560 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004561 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004562 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004563 auto data_channel_it = rtp_data_channels_.find(label);
4564 if (data_channel_it == rtp_data_channels_.end()) {
4565 // This is a new data channel.
4566 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4567 } else {
4568 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4569 }
4570 existing_channels.push_back(label);
4571 }
4572
4573 UpdateClosingRtpDataChannels(existing_channels, false);
4574}
4575
4576void PeerConnection::UpdateClosingRtpDataChannels(
4577 const std::vector<std::string>& active_channels,
4578 bool is_local_update) {
4579 auto it = rtp_data_channels_.begin();
4580 while (it != rtp_data_channels_.end()) {
4581 DataChannel* data_channel = it->second;
4582 if (std::find(active_channels.begin(), active_channels.end(),
4583 data_channel->label()) != active_channels.end()) {
4584 ++it;
4585 continue;
4586 }
4587
4588 if (is_local_update) {
4589 data_channel->SetSendSsrc(0);
4590 } else {
4591 data_channel->RemotePeerRequestClose();
4592 }
4593
4594 if (data_channel->state() == DataChannel::kClosed) {
4595 rtp_data_channels_.erase(it);
4596 it = rtp_data_channels_.begin();
4597 } else {
4598 ++it;
4599 }
4600 }
4601}
4602
4603void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4604 uint32_t remote_ssrc) {
4605 rtc::scoped_refptr<DataChannel> channel(
4606 InternalCreateDataChannel(label, nullptr));
4607 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004608 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004609 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004610 return;
4611 }
4612 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004613 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4614 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004615 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004616}
4617
4618rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4619 const std::string& label,
4620 const InternalDataChannelInit* config) {
4621 if (IsClosed()) {
4622 return nullptr;
4623 }
Steve Anton75737c02017-11-06 10:37:17 -08004624 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004625 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004626 << "InternalCreateDataChannel: Data is not supported in this call.";
4627 return nullptr;
4628 }
4629 InternalDataChannelInit new_config =
4630 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004631 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004632 if (new_config.id < 0) {
4633 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004634 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004635 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004636 RTC_LOG(LS_ERROR)
4637 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004638 return nullptr;
4639 }
4640 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004641 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004642 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004643 return nullptr;
4644 }
4645 }
4646
Steve Anton75737c02017-11-06 10:37:17 -08004647 rtc::scoped_refptr<DataChannel> channel(
4648 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004649 if (!channel) {
4650 sid_allocator_.ReleaseSid(new_config.id);
4651 return nullptr;
4652 }
4653
4654 if (channel->data_channel_type() == cricket::DCT_RTP) {
4655 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004656 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4657 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004658 return nullptr;
4659 }
4660 rtp_data_channels_[channel->label()] = channel;
4661 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004662 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004663 sctp_data_channels_.push_back(channel);
4664 channel->SignalClosed.connect(this,
4665 &PeerConnection::OnSctpDataChannelClosed);
4666 }
4667
Steve Anton2d8609c2018-01-23 16:38:46 -08004668 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004669 return channel;
4670}
4671
4672bool PeerConnection::HasDataChannels() const {
4673 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4674}
4675
4676void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4677 for (const auto& channel : sctp_data_channels_) {
4678 if (channel->id() < 0) {
4679 int sid;
4680 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004681 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004682 continue;
4683 }
4684 channel->SetSctpSid(sid);
4685 }
4686 }
4687}
4688
4689void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004690 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004691 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4692 ++it) {
4693 if (it->get() == channel) {
4694 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004695 // After the closing procedure is done, it's safe to use this ID for
4696 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004697 sid_allocator_.ReleaseSid(channel->id());
4698 }
deadbeefbd292462015-12-14 18:15:29 -08004699 // Since this method is triggered by a signal from the DataChannel,
4700 // we can't free it directly here; we need to free it asynchronously.
4701 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004702 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004703 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4704 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004705 return;
4706 }
4707 }
4708}
4709
deadbeefab9b2d12015-10-14 11:33:11 -07004710void PeerConnection::OnDataChannelDestroyed() {
4711 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4712 // DataChannel may callback to us and try to modify the list.
4713 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4714 temp_rtp_dcs.swap(rtp_data_channels_);
4715 for (const auto& kv : temp_rtp_dcs) {
4716 kv.second->OnTransportChannelDestroyed();
4717 }
4718
4719 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4720 temp_sctp_dcs.swap(sctp_data_channels_);
4721 for (const auto& channel : temp_sctp_dcs) {
4722 channel->OnTransportChannelDestroyed();
4723 }
4724}
4725
4726void PeerConnection::OnDataChannelOpenMessage(
4727 const std::string& label,
4728 const InternalDataChannelInit& config) {
4729 rtc::scoped_refptr<DataChannel> channel(
4730 InternalCreateDataChannel(label, &config));
4731 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004732 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004733 return;
4734 }
4735
deadbeefa601f5c2016-06-06 14:27:39 -07004736 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4737 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004738 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004739 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004740}
4741
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004742bool PeerConnection::HandleOpenMessage_s(
4743 const cricket::ReceiveDataParams& params,
4744 const rtc::CopyOnWriteBuffer& buffer) {
4745 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4746 // Received OPEN message; parse and signal that a new data channel should
4747 // be created.
4748 std::string label;
4749 InternalDataChannelInit config;
4750 config.id = params.ssrc;
4751 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4752 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4753 << params.ssrc;
4754 return true;
4755 }
4756 config.open_handshake_role = InternalDataChannelInit::kAcker;
4757 OnDataChannelOpenMessage(label, config);
4758 return true;
4759 }
4760 return false;
4761}
4762
Steve Anton4171afb2017-11-20 10:20:22 -08004763rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4764PeerConnection::GetAudioTransceiver() const {
4765 // This method only works with Plan B SDP, where there is a single
4766 // audio/video transceiver.
4767 RTC_DCHECK(!IsUnifiedPlan());
4768 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004769 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004770 return transceiver;
4771 }
4772 }
4773 RTC_NOTREACHED();
4774 return nullptr;
4775}
4776
4777rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4778PeerConnection::GetVideoTransceiver() const {
4779 // This method only works with Plan B SDP, where there is a single
4780 // audio/video transceiver.
4781 RTC_DCHECK(!IsUnifiedPlan());
4782 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004783 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004784 return transceiver;
4785 }
4786 }
4787 RTC_NOTREACHED();
4788 return nullptr;
4789}
4790
4791// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4792// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004793bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004794 switch (type) {
4795 case cricket::MEDIA_TYPE_AUDIO:
4796 return !GetAudioTransceiver()->internal()->senders().empty();
4797 case cricket::MEDIA_TYPE_VIDEO:
4798 return !GetVideoTransceiver()->internal()->senders().empty();
4799 case cricket::MEDIA_TYPE_DATA:
4800 return false;
4801 }
4802 RTC_NOTREACHED();
4803 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004804}
4805
Steve Anton4171afb2017-11-20 10:20:22 -08004806rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4807PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4808 for (auto transceiver : transceivers_) {
4809 for (auto sender : transceiver->internal()->senders()) {
4810 if (sender->track() == track) {
4811 return sender;
4812 }
4813 }
4814 }
4815 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004816}
4817
Steve Anton4171afb2017-11-20 10:20:22 -08004818rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4819PeerConnection::FindSenderById(const std::string& sender_id) const {
4820 for (auto transceiver : transceivers_) {
4821 for (auto sender : transceiver->internal()->senders()) {
4822 if (sender->id() == sender_id) {
4823 return sender;
4824 }
4825 }
4826 }
4827 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004828}
4829
Steve Anton4171afb2017-11-20 10:20:22 -08004830rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4831PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4832 for (auto transceiver : transceivers_) {
4833 for (auto receiver : transceiver->internal()->receivers()) {
4834 if (receiver->id() == receiver_id) {
4835 return receiver;
4836 }
4837 }
4838 }
4839 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004840}
4841
Steve Anton4171afb2017-11-20 10:20:22 -08004842std::vector<PeerConnection::RtpSenderInfo>*
4843PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4844 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4845 media_type == cricket::MEDIA_TYPE_VIDEO);
4846 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4847 ? &remote_audio_sender_infos_
4848 : &remote_video_sender_infos_;
4849}
4850
4851std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004852 cricket::MediaType media_type) {
4853 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4854 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004855 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4856 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004857}
4858
Steve Anton4171afb2017-11-20 10:20:22 -08004859const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4860 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004861 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004862 const std::string sender_id) const {
4863 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004864 if (sender_info.stream_id == stream_id &&
4865 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004866 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004867 }
4868 }
4869 return nullptr;
4870}
4871
4872DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4873 for (const auto& channel : sctp_data_channels_) {
4874 if (channel->id() == sid) {
4875 return channel;
4876 }
4877 }
4878 return nullptr;
4879}
4880
deadbeef91dd5672016-05-18 16:55:30 -07004881bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004882 const cricket::ServerAddresses& stun_servers,
4883 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004884 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004885 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004886 // To handle both internal and externally created port allocator, we will
4887 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004888 port_allocator_flags_ = port_allocator_->flags();
4889 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4890 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4891 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004892 // If the disable-IPv6 flag was specified, we'll not override it
4893 // by experiment.
4894 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004895 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004896 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4897 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004898 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004899 }
4900
zhihuangb09b3f92017-03-07 14:40:51 -08004901 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004902 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004903 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004904 }
4905
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004906 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004907 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004908 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004909 }
4910
honghaiz60347052016-05-31 18:29:12 -07004911 if (configuration.candidate_network_policy ==
4912 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004913 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004914 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004915 }
4916
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004917 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004918 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004919 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4920 }
4921
Qingsi Wanga2d60672018-04-11 16:57:45 -07004922 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004923 // No step delay is used while allocating ports.
4924 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4925 port_allocator_->set_candidate_filter(
4926 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004927 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004928
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004929 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004930 for (auto& turn_server : turn_servers_copy) {
4931 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004932 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004933 // Call this last since it may create pooled allocator sessions using the
4934 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004935 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004936 stun_servers, std::move(turn_servers_copy),
4937 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4938 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004939 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004940 return true;
4941}
4942
deadbeef91dd5672016-05-18 16:55:30 -07004943bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004944 const cricket::ServerAddresses& stun_servers,
4945 const std::vector<cricket::RelayServerConfig>& turn_servers,
4946 IceTransportsType type,
4947 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004948 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004949 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004950 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004951 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004952 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004953 // According to JSEP, after setLocalDescription, changing the candidate pool
4954 // size is not allowed, and changing the set of ICE servers will not result
4955 // in new candidates being gathered.
4956 if (local_description()) {
4957 port_allocator_->FreezeCandidatePool();
4958 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004959 // Add the custom tls turn servers if they exist.
4960 auto turn_servers_copy = turn_servers;
4961 for (auto& turn_server : turn_servers_copy) {
4962 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4963 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004964 // Call this last since it may create pooled allocator sessions using the
4965 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004966 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004967 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4968 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004969}
4970
Steve Antonba818672017-11-06 10:21:57 -08004971cricket::ChannelManager* PeerConnection::channel_manager() const {
4972 return factory_->channel_manager();
4973}
4974
Elad Alon99c3fe52017-10-13 16:29:40 +02004975bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004976 std::unique_ptr<RtcEventLogOutput> output,
4977 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004978 if (!event_log_) {
4979 return false;
4980 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004981 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004982}
4983
4984void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004985 if (event_log_) {
4986 event_log_->StopLogging();
4987 }
ivoc14d5dbe2016-07-04 07:06:55 -07004988}
nisseeaabdf62017-05-05 02:23:02 -07004989
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004990cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08004991 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004992 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004993 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08004994 if (channel && channel->content_name() == content_name) {
4995 return channel;
4996 }
Steve Anton75737c02017-11-06 10:37:17 -08004997 }
4998 if (rtp_data_channel() &&
4999 rtp_data_channel()->content_name() == content_name) {
5000 return rtp_data_channel();
5001 }
5002 return nullptr;
5003}
5004
5005bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005006 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005007 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005008 RTC_LOG(LS_INFO)
5009 << "Local and Remote descriptions must be applied 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 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005013 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005014 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005015 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005016 return false;
5017 }
5018
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005019 absl::optional<rtc::SSLRole> dtls_role;
5020 if (sctp_mid_) {
5021 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5022 } else if (is_caller_) {
5023 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5024 }
Zhi Huange830e682018-03-30 10:48:35 -07005025 if (dtls_role) {
5026 *role = *dtls_role;
5027 return true;
5028 }
5029 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005030}
5031
5032bool PeerConnection::GetSslRole(const std::string& content_name,
5033 rtc::SSLRole* role) {
5034 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005035 RTC_LOG(LS_INFO)
5036 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005037 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005038 return false;
5039 }
5040
Zhi Huange830e682018-03-30 10:48:35 -07005041 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5042 if (dtls_role) {
5043 *role = *dtls_role;
5044 return true;
5045 }
5046 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005047}
5048
Steve Antonf8470812017-12-04 10:46:21 -08005049void PeerConnection::SetSessionError(SessionError error,
5050 const std::string& error_desc) {
5051 RTC_DCHECK_RUN_ON(signaling_thread());
5052 if (error != session_error_) {
5053 session_error_ = error;
5054 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005055 }
5056}
5057
Zhi Huange830e682018-03-30 10:48:35 -07005058RTCError PeerConnection::UpdateSessionState(
5059 SdpType type,
5060 cricket::ContentSource source,
5061 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005062 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005063
5064 // If there's already a pending error then no state transition should happen.
5065 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005066 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005067
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005068 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005069 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005070 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005071 }
5072
5073 // Update the signaling state according to the specified state machine (see
5074 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005075 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005076 ChangeSignalingState(source == cricket::CS_LOCAL
5077 ? PeerConnectionInterface::kHaveLocalOffer
5078 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005079 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005080 ChangeSignalingState(source == cricket::CS_LOCAL
5081 ? PeerConnectionInterface::kHaveLocalPrAnswer
5082 : PeerConnectionInterface::kHaveRemotePrAnswer);
5083 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005084 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005085 ChangeSignalingState(PeerConnectionInterface::kStable);
5086 }
5087
5088 // Update internal objects according to the session description's media
5089 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005090 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005091 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005092 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005093 }
5094
Steve Anton8a006912017-12-04 15:25:56 -08005095 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005096}
5097
Steve Anton8a006912017-12-04 15:25:56 -08005098RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005099 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005100 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005101 const SessionDescriptionInterface* sdesc =
5102 (source == cricket::CS_LOCAL ? local_description()
5103 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005104 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005105
5106 // Push down the new SDP media section for each audio/video transceiver.
5107 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005108 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005109 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005110 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005111 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005112 continue;
5113 }
5114 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005115 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005116 if (!content_desc) {
5117 continue;
5118 }
5119 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005120 bool success = (source == cricket::CS_LOCAL)
5121 ? channel->SetLocalContent(content_desc, type, &error)
5122 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005123 if (!success) {
5124 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5125 }
5126 }
5127
5128 // If using the RtpDataChannel, push down the new SDP section for it too.
5129 if (rtp_data_channel_) {
5130 const ContentInfo* data_content =
5131 cricket::GetFirstDataContent(sdesc->description());
5132 if (data_content && !data_content->rejected) {
5133 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005134 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005135 if (data_desc) {
5136 std::string error;
5137 bool success =
5138 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005139 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005140 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005141 if (!success) {
5142 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5143 std::move(error));
5144 }
Steve Anton75737c02017-11-06 10:37:17 -08005145 }
5146 }
5147 }
Steve Antoned10bd92017-12-05 10:52:59 -08005148
Steve Anton75737c02017-11-06 10:37:17 -08005149 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5150 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5151 if (sctp_transport_ && local_description() && remote_description() &&
5152 cricket::GetFirstDataContent(local_description()->description()) &&
5153 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005154 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005155 RTC_FROM_HERE,
5156 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005157 if (!success) {
5158 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5159 "Failed to push down SCTP parameters.");
5160 }
Steve Anton75737c02017-11-06 10:37:17 -08005161 }
Steve Antoned10bd92017-12-05 10:52:59 -08005162
Steve Anton8a006912017-12-04 15:25:56 -08005163 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005164}
5165
5166bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5167 RTC_DCHECK(network_thread()->IsCurrent());
5168 RTC_DCHECK(local_description());
5169 RTC_DCHECK(remote_description());
5170 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5171 // When we support "max-message-size", that would also be pushed down here.
5172 return sctp_transport_->Start(
5173 GetSctpPort(local_description()->description()),
5174 GetSctpPort(remote_description()->description()));
5175}
5176
Steve Anton8a006912017-12-04 15:25:56 -08005177RTCError PeerConnection::PushdownTransportDescription(
5178 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005179 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005180 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005181
Zhi Huange830e682018-03-30 10:48:35 -07005182 if (source == cricket::CS_LOCAL) {
5183 const SessionDescriptionInterface* sdesc = local_description();
5184 RTC_DCHECK(sdesc);
5185 return transport_controller_->SetLocalDescription(type,
5186 sdesc->description());
5187 } else {
5188 const SessionDescriptionInterface* sdesc = remote_description();
5189 RTC_DCHECK(sdesc);
5190 return transport_controller_->SetRemoteDescription(type,
5191 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005192 }
Steve Anton75737c02017-11-06 10:37:17 -08005193}
5194
5195bool PeerConnection::GetTransportDescription(
5196 const SessionDescription* description,
5197 const std::string& content_name,
5198 cricket::TransportDescription* tdesc) {
5199 if (!description || !tdesc) {
5200 return false;
5201 }
5202 const TransportInfo* transport_info =
5203 description->GetTransportInfoByName(content_name);
5204 if (!transport_info) {
5205 return false;
5206 }
5207 *tdesc = transport_info->description;
5208 return true;
5209}
5210
Steve Anton75737c02017-11-06 10:37:17 -08005211cricket::IceConfig PeerConnection::ParseIceConfig(
5212 const PeerConnectionInterface::RTCConfiguration& config) const {
5213 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005214 switch (config.continual_gathering_policy) {
5215 case PeerConnectionInterface::GATHER_ONCE:
5216 gathering_policy = cricket::GATHER_ONCE;
5217 break;
5218 case PeerConnectionInterface::GATHER_CONTINUALLY:
5219 gathering_policy = cricket::GATHER_CONTINUALLY;
5220 break;
5221 default:
5222 RTC_NOTREACHED();
5223 gathering_policy = cricket::GATHER_ONCE;
5224 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005225
Steve Anton75737c02017-11-06 10:37:17 -08005226 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005227 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5228 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005229 ice_config.prioritize_most_likely_candidate_pairs =
5230 config.prioritize_most_likely_ice_candidate_pairs;
5231 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005232 RTCConfigurationToIceConfigOptionalInt(
5233 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005234 ice_config.continual_gathering_policy = gathering_policy;
5235 ice_config.presume_writable_when_fully_relayed =
5236 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005237 ice_config.ice_check_interval_strong_connectivity =
5238 config.ice_check_interval_strong_connectivity;
5239 ice_config.ice_check_interval_weak_connectivity =
5240 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005241 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005242 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005243 ice_config.regather_all_networks_interval_range =
5244 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005245 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005246 return ice_config;
5247}
5248
Steve Anton75737c02017-11-06 10:37:17 -08005249bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5250 std::string* track_id) {
5251 if (!local_description()) {
5252 return false;
5253 }
5254 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5255 track_id);
5256}
5257
5258bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5259 std::string* track_id) {
5260 if (!remote_description()) {
5261 return false;
5262 }
5263 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5264 track_id);
5265}
5266
5267bool PeerConnection::SendData(const cricket::SendDataParams& params,
5268 const rtc::CopyOnWriteBuffer& payload,
5269 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005270 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5271 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5272 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005273 return false;
5274 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005275 if (media_transport_) {
5276 SendDataParams send_params;
5277 send_params.type = ToWebrtcDataMessageType(params.type);
5278 send_params.ordered = params.ordered;
5279 if (params.max_rtx_count >= 0) {
5280 send_params.max_rtx_count = params.max_rtx_count;
5281 } else if (params.max_rtx_ms >= 0) {
5282 send_params.max_rtx_ms = params.max_rtx_ms;
5283 }
5284 return media_transport_->SendData(params.sid, send_params, payload).ok();
5285 }
Steve Anton75737c02017-11-06 10:37:17 -08005286 return rtp_data_channel_
5287 ? rtp_data_channel_->SendData(params, payload, result)
5288 : network_thread()->Invoke<bool>(
5289 RTC_FROM_HERE,
5290 Bind(&cricket::SctpTransportInternal::SendData,
5291 sctp_transport_.get(), params, payload, result));
5292}
5293
5294bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005295 RTC_DCHECK_RUN_ON(signaling_thread());
5296 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005297 // Don't log an error here, because DataChannels are expected to call
5298 // ConnectDataChannel in this state. It's the only way to initially tell
5299 // whether or not the underlying transport is ready.
5300 return false;
5301 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005302 if (media_transport_) {
5303 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5304 &DataChannel::OnChannelReady);
5305 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5306 &DataChannel::OnDataReceived);
5307 SignalMediaTransportChannelClosing_s.connect(
5308 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5309 SignalMediaTransportChannelClosed_s.connect(
5310 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5311 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005312 rtp_data_channel_->SignalReadyToSendData.connect(
5313 webrtc_data_channel, &DataChannel::OnChannelReady);
5314 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5315 &DataChannel::OnDataReceived);
5316 } else {
5317 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5318 &DataChannel::OnChannelReady);
5319 SignalSctpDataReceived.connect(webrtc_data_channel,
5320 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005321 SignalSctpClosingProcedureStartedRemotely.connect(
5322 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5323 SignalSctpClosingProcedureComplete.connect(
5324 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005325 }
5326 return true;
5327}
5328
5329void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005330 RTC_DCHECK_RUN_ON(signaling_thread());
5331 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005332 RTC_LOG(LS_ERROR)
5333 << "DisconnectDataChannel called when rtp_data_channel_ and "
5334 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005335 return;
5336 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005337 if (media_transport_) {
5338 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5339 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5340 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5341 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5342 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005343 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5344 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5345 } else {
5346 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5347 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005348 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5349 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005350 }
5351}
5352
5353void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005354 if (media_transport_) {
5355 // No-op. Media transport does not need to add streams.
5356 return;
5357 }
Steve Anton75737c02017-11-06 10:37:17 -08005358 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005359 RTC_LOG(LS_ERROR)
5360 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005361 return;
5362 }
5363 network_thread()->Invoke<void>(
5364 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5365 sctp_transport_.get(), sid));
5366}
5367
5368void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005369 if (media_transport_) {
5370 media_transport_->CloseChannel(sid);
5371 return;
5372 }
Steve Anton75737c02017-11-06 10:37:17 -08005373 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005374 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005375 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005376 return;
5377 }
5378 network_thread()->Invoke<void>(
5379 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5380 sctp_transport_.get(), sid));
5381}
5382
5383bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005384 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005385 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005386 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005387 sctp_ready_to_send_data_;
5388}
5389
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005390void PeerConnection::OnDataReceived(int channel_id,
5391 DataMessageType type,
5392 const rtc::CopyOnWriteBuffer& buffer) {
5393 cricket::ReceiveDataParams params;
5394 params.sid = channel_id;
5395 params.type = ToCricketDataMessageType(type);
5396 media_transport_invoker_->AsyncInvoke<void>(
5397 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5398 RTC_DCHECK_RUN_ON(signaling_thread());
5399 if (!HandleOpenMessage_s(params, buffer)) {
5400 SignalMediaTransportReceivedData_s(params, buffer);
5401 }
5402 });
5403}
5404
5405void PeerConnection::OnChannelClosing(int channel_id) {
5406 media_transport_invoker_->AsyncInvoke<void>(
5407 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5408 RTC_DCHECK_RUN_ON(signaling_thread());
5409 SignalMediaTransportChannelClosing_s(channel_id);
5410 });
5411}
5412
5413void PeerConnection::OnChannelClosed(int channel_id) {
5414 media_transport_invoker_->AsyncInvoke<void>(
5415 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5416 RTC_DCHECK_RUN_ON(signaling_thread());
5417 SignalMediaTransportChannelClosed_s(channel_id);
5418 });
5419}
5420
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005421absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005422 if (sctp_mid_ && transport_controller_) {
5423 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5424 if (dtls_transport) {
5425 return dtls_transport->transport_name();
5426 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005427 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005428 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005429 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005430}
5431
Qingsi Wang72a43a12018-02-20 16:03:18 -08005432cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5433 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005434 network_thread()->Invoke<void>(
5435 RTC_FROM_HERE,
5436 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5437 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005438 return candidate_states_list;
5439}
5440
Steve Anton5dfde182018-02-06 10:34:40 -08005441std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5442 const {
5443 std::map<std::string, std::string> transport_names_by_mid;
5444 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005445 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005446 if (channel) {
5447 transport_names_by_mid[channel->content_name()] =
5448 channel->transport_name();
5449 }
Steve Anton75737c02017-11-06 10:37:17 -08005450 }
Steve Anton5dfde182018-02-06 10:34:40 -08005451 if (rtp_data_channel_) {
5452 transport_names_by_mid[rtp_data_channel_->content_name()] =
5453 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005454 }
5455 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005456 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005457 RTC_DCHECK(transport_name);
5458 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005459 }
Steve Anton5dfde182018-02-06 10:34:40 -08005460 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005461}
5462
Steve Anton5dfde182018-02-06 10:34:40 -08005463std::map<std::string, cricket::TransportStats>
5464PeerConnection::GetTransportStatsByNames(
5465 const std::set<std::string>& transport_names) {
5466 if (!network_thread()->IsCurrent()) {
5467 return network_thread()
5468 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5469 RTC_FROM_HERE,
5470 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005471 }
Steve Anton5dfde182018-02-06 10:34:40 -08005472 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5473 for (const std::string& transport_name : transport_names) {
5474 cricket::TransportStats transport_stats;
5475 bool success =
5476 transport_controller_->GetStats(transport_name, &transport_stats);
5477 if (success) {
5478 transport_stats_by_name[transport_name] = std::move(transport_stats);
5479 } else {
5480 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5481 << transport_name;
5482 }
5483 }
5484 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005485}
5486
5487bool PeerConnection::GetLocalCertificate(
5488 const std::string& transport_name,
5489 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005490 if (!certificate) {
5491 return false;
5492 }
5493 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5494 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005495}
5496
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005497std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005498 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005499 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005500}
5501
5502cricket::DataChannelType PeerConnection::data_channel_type() const {
5503 return data_channel_type_;
5504}
5505
5506bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5507 return pending_ice_restarts_.find(content_name) !=
5508 pending_ice_restarts_.end();
5509}
5510
Steve Anton75737c02017-11-06 10:37:17 -08005511bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5512 return transport_controller_->NeedsIceRestart(content_name);
5513}
5514
5515void PeerConnection::OnCertificateReady(
5516 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5517 transport_controller_->SetLocalCertificate(certificate);
5518}
5519
5520void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005521 SetSessionError(SessionError::kTransport,
5522 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005523}
5524
Alex Loiko9289eda2018-11-23 16:18:59 +00005525void PeerConnection::OnTransportControllerConnectionState(
5526 cricket::IceConnectionState state) {
5527 switch (state) {
5528 case cricket::kIceConnectionConnecting:
5529 // If the current state is Connected or Completed, then there were
5530 // writable channels but now there are not, so the next state must
5531 // be Disconnected.
5532 // kIceConnectionConnecting is currently used as the default,
5533 // un-connected state by the TransportController, so its only use is
5534 // detecting disconnections.
5535 if (ice_connection_state_ ==
5536 PeerConnectionInterface::kIceConnectionConnected ||
5537 ice_connection_state_ ==
5538 PeerConnectionInterface::kIceConnectionCompleted) {
5539 SetIceConnectionState(
5540 PeerConnectionInterface::kIceConnectionDisconnected);
5541 }
5542 break;
5543 case cricket::kIceConnectionFailed:
5544 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5545 break;
5546 case cricket::kIceConnectionConnected:
5547 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5548 "all transports are writable.";
5549 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5550 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5551 break;
5552 case cricket::kIceConnectionCompleted:
5553 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5554 "all transports are complete.";
5555 if (ice_connection_state_ !=
5556 PeerConnectionInterface::kIceConnectionConnected) {
5557 // If jumping directly from "checking" to "connected",
5558 // signal "connected" first.
5559 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5560 }
5561 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5562 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5563 ReportTransportStats();
5564 break;
5565 default:
5566 RTC_NOTREACHED();
5567 }
5568}
5569
Steve Anton75737c02017-11-06 10:37:17 -08005570void PeerConnection::OnTransportControllerCandidatesGathered(
5571 const std::string& transport_name,
5572 const cricket::Candidates& candidates) {
5573 RTC_DCHECK(signaling_thread()->IsCurrent());
5574 int sdp_mline_index;
5575 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005576 RTC_LOG(LS_ERROR)
5577 << "OnTransportControllerCandidatesGathered: content name "
5578 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005579 return;
5580 }
5581
5582 for (cricket::Candidates::const_iterator citer = candidates.begin();
5583 citer != candidates.end(); ++citer) {
5584 // Use transport_name as the candidate media id.
5585 std::unique_ptr<JsepIceCandidate> candidate(
5586 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5587 if (local_description()) {
5588 mutable_local_description()->AddCandidate(candidate.get());
5589 }
5590 OnIceCandidate(std::move(candidate));
5591 }
5592}
5593
5594void PeerConnection::OnTransportControllerCandidatesRemoved(
5595 const std::vector<cricket::Candidate>& candidates) {
5596 RTC_DCHECK(signaling_thread()->IsCurrent());
5597 // Sanity check.
5598 for (const cricket::Candidate& candidate : candidates) {
5599 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005600 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005601 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005602 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005603 return;
5604 }
5605 }
5606
5607 if (local_description()) {
5608 mutable_local_description()->RemoveCandidates(candidates);
5609 }
5610 OnIceCandidatesRemoved(candidates);
5611}
5612
5613void PeerConnection::OnTransportControllerDtlsHandshakeError(
5614 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005615 RTC_HISTOGRAM_ENUMERATION(
5616 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5617 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005618}
5619
Steve Antoned10bd92017-12-05 10:52:59 -08005620void PeerConnection::EnableSending() {
5621 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005622 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005623 if (channel && !channel->enabled()) {
5624 channel->Enable(true);
5625 }
Steve Anton75737c02017-11-06 10:37:17 -08005626 }
5627
Steve Anton4171afb2017-11-20 10:20:22 -08005628 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005629 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005630 }
Steve Anton75737c02017-11-06 10:37:17 -08005631}
5632
5633// Returns the media index for a local ice candidate given the content name.
5634bool PeerConnection::GetLocalCandidateMediaIndex(
5635 const std::string& content_name,
5636 int* sdp_mline_index) {
5637 if (!local_description() || !sdp_mline_index) {
5638 return false;
5639 }
5640
5641 bool content_found = false;
5642 const ContentInfos& contents = local_description()->description()->contents();
5643 for (size_t index = 0; index < contents.size(); ++index) {
5644 if (contents[index].name == content_name) {
5645 *sdp_mline_index = static_cast<int>(index);
5646 content_found = true;
5647 break;
5648 }
5649 }
5650 return content_found;
5651}
5652
5653bool PeerConnection::UseCandidatesInSessionDescription(
5654 const SessionDescriptionInterface* remote_desc) {
5655 if (!remote_desc) {
5656 return true;
5657 }
5658 bool ret = true;
5659
5660 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5661 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5662 for (size_t n = 0; n < candidates->count(); ++n) {
5663 const IceCandidateInterface* candidate = candidates->at(n);
5664 bool valid = false;
5665 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5666 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005667 RTC_LOG(LS_INFO)
5668 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005669 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005670 }
5671 continue;
5672 }
5673 ret = UseCandidate(candidate);
5674 if (!ret) {
5675 break;
5676 }
5677 }
5678 }
5679 return ret;
5680}
5681
5682bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5683 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5684 size_t remote_content_size =
5685 remote_description()->description()->contents().size();
5686 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005687 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005688 return false;
5689 }
5690
5691 cricket::ContentInfo content =
5692 remote_description()->description()->contents()[mediacontent_index];
5693 std::vector<cricket::Candidate> candidates;
5694 candidates.push_back(candidate->candidate());
5695 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005696 RTCError error =
5697 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005698 if (error.ok()) {
5699 // Candidates successfully submitted for checking.
5700 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5701 ice_connection_state_ ==
5702 PeerConnectionInterface::kIceConnectionDisconnected) {
5703 // If state is New, then the session has just gotten its first remote ICE
5704 // candidates, so go to Checking.
5705 // If state is Disconnected, the session is re-using old candidates or
5706 // receiving additional ones, so go to Checking.
5707 // If state is Connected, stay Connected.
5708 // TODO(bemasc): If state is Connected, and the new candidates are for a
5709 // newly added transport, then the state actually _should_ move to
5710 // checking. Add a way to distinguish that case.
5711 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5712 }
5713 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005714 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005715 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005716 }
5717 return true;
5718}
5719
5720void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005721 // Destroy video channel first since it may have a pointer to the
5722 // voice channel.
5723 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005724 if (!video_info || video_info->rejected) {
5725 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005726 }
5727
Steve Anton6fec8802017-12-04 10:37:29 -08005728 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5729 if (!audio_info || audio_info->rejected) {
5730 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005731 }
5732
5733 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5734 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005735 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005736 }
5737}
5738
Steve Antondcc3c022017-12-22 16:02:54 -08005739RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5740 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005741 const cricket::ContentGroup* bundle_group = nullptr;
5742 if (configuration_.bundle_policy ==
5743 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005744 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005745 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005746 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5747 "max-bundle configured but session description "
5748 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005749 }
5750 }
Steve Antondcc3c022017-12-22 16:02:54 -08005751 return std::move(bundle_group);
5752}
5753
5754RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005755 // Creating the media channels. Transports should already have been created
5756 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005757 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005758 if (voice && !voice->rejected &&
5759 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005760 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005761 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005762 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5763 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005764 }
5765 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5766 }
5767
Steve Antondcc3c022017-12-22 16:02:54 -08005768 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005769 if (video && !video->rejected &&
5770 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005771 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005772 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005773 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5774 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005775 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005776 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005777 }
5778
Steve Antondcc3c022017-12-22 16:02:54 -08005779 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005780 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005781 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005782 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005783 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5784 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005785 }
5786 }
5787
Steve Anton8a006912017-12-04 15:25:56 -08005788 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005789}
5790
Steve Anton4171afb2017-11-20 10:20:22 -08005791// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005792cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005793 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005794 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005795 MediaTransportInterface* media_transport = nullptr;
5796 if (configuration_.use_media_transport) {
5797 media_transport = GetMediaTransport(mid);
5798 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005799
Steve Anton75737c02017-11-06 10:37:17 -08005800 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005801 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005802 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5803 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005804 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005805 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005806 }
Steve Anton75737c02017-11-06 10:37:17 -08005807 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5808 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005809 voice_channel->SignalSentPacket.connect(this,
5810 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005811 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005812
Steve Antoneda6ccd2017-12-04 10:21:55 -08005813 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005814}
5815
Steve Anton4171afb2017-11-20 10:20:22 -08005816// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005817cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005818 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005819 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5820
5821 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005822 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005823 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005824 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5825 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005826 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005827 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005828 }
Steve Anton75737c02017-11-06 10:37:17 -08005829 video_channel->SignalDtlsSrtpSetupFailure.connect(
5830 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005831 video_channel->SignalSentPacket.connect(this,
5832 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005833 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005834
Steve Antoneda6ccd2017-12-04 10:21:55 -08005835 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005836}
5837
Zhi Huange830e682018-03-30 10:48:35 -07005838bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005839 switch (data_channel_type_) {
5840 case cricket::DCT_MEDIA_TRANSPORT:
5841 if (network_thread()->Invoke<bool>(
5842 RTC_FROM_HERE,
5843 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5844 this, mid))) {
5845 for (const auto& channel : sctp_data_channels_) {
5846 channel->OnTransportChannelCreated();
5847 }
5848 return true;
5849 }
Steve Anton75737c02017-11-06 10:37:17 -08005850 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005851 case cricket::DCT_SCTP:
5852 if (!sctp_factory_) {
5853 RTC_LOG(LS_ERROR)
5854 << "Trying to create SCTP transport, but didn't compile with "
5855 "SCTP support (HAVE_SCTP)";
5856 return false;
5857 }
5858 if (!network_thread()->Invoke<bool>(
5859 RTC_FROM_HERE,
5860 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5861 return false;
5862 }
5863 for (const auto& channel : sctp_data_channels_) {
5864 channel->OnTransportChannelCreated();
5865 }
5866 return true;
5867 case cricket::DCT_RTP:
5868 default:
5869 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5870 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5871 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5872 SrtpRequired(), GetCryptoOptions());
5873 if (!rtp_data_channel_) {
5874 return false;
5875 }
5876 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5877 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5878 rtp_data_channel_->SignalSentPacket.connect(
5879 this, &PeerConnection::OnSentPacket_w);
5880 rtp_data_channel_->SetRtpTransport(rtp_transport);
5881 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005882 }
5883
Steve Anton75737c02017-11-06 10:37:17 -08005884 return true;
5885}
5886
5887Call::Stats PeerConnection::GetCallStats() {
5888 if (!worker_thread()->IsCurrent()) {
5889 return worker_thread()->Invoke<Call::Stats>(
5890 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5891 }
5892 if (call_) {
5893 return call_->GetStats();
5894 } else {
5895 return Call::Stats();
5896 }
5897}
5898
Zhi Huange830e682018-03-30 10:48:35 -07005899bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005900 RTC_DCHECK(network_thread()->IsCurrent());
5901 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005902 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005903 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005904 RTC_DCHECK(dtls_transport);
5905 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005906 RTC_DCHECK(sctp_transport_);
5907 sctp_invoker_.reset(new rtc::AsyncInvoker());
5908 sctp_transport_->SignalReadyToSendData.connect(
5909 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5910 sctp_transport_->SignalDataReceived.connect(
5911 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005912 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5913 // another thread. Would be nice if there was a helper class similar to
5914 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5915 // code.
5916 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5917 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5918 sctp_transport_->SignalClosingProcedureComplete.connect(
5919 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005920 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005921 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005922 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005923}
5924
5925void PeerConnection::DestroySctpTransport_n() {
5926 RTC_DCHECK(network_thread()->IsCurrent());
5927 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005928 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005929 sctp_invoker_.reset(nullptr);
5930 sctp_ready_to_send_data_ = false;
5931}
5932
5933void PeerConnection::OnSctpTransportReadyToSendData_n() {
5934 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5935 RTC_DCHECK(network_thread()->IsCurrent());
5936 // Note: Cannot use rtc::Bind here because it will grab a reference to
5937 // PeerConnection and potentially cause PeerConnection to live longer than
5938 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5939 // be destroyed before PeerConnection is destroyed, and at that point all
5940 // pending tasks will be cleared.
5941 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5942 OnSctpTransportReadyToSendData_s(true);
5943 });
5944}
5945
5946void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5947 RTC_DCHECK(signaling_thread()->IsCurrent());
5948 sctp_ready_to_send_data_ = ready;
5949 SignalSctpReadyToSendData(ready);
5950}
5951
5952void PeerConnection::OnSctpTransportDataReceived_n(
5953 const cricket::ReceiveDataParams& params,
5954 const rtc::CopyOnWriteBuffer& payload) {
5955 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5956 RTC_DCHECK(network_thread()->IsCurrent());
5957 // Note: Cannot use rtc::Bind here because it will grab a reference to
5958 // PeerConnection and potentially cause PeerConnection to live longer than
5959 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5960 // be destroyed before PeerConnection is destroyed, and at that point all
5961 // pending tasks will be cleared.
5962 sctp_invoker_->AsyncInvoke<void>(
5963 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5964 OnSctpTransportDataReceived_s(params, payload);
5965 });
5966}
5967
5968void PeerConnection::OnSctpTransportDataReceived_s(
5969 const cricket::ReceiveDataParams& params,
5970 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005971 RTC_DCHECK_RUN_ON(signaling_thread());
5972 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005973 SignalSctpDataReceived(params, payload);
5974 }
5975}
5976
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005977void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005978 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5979 RTC_DCHECK(network_thread()->IsCurrent());
5980 sctp_invoker_->AsyncInvoke<void>(
5981 RTC_FROM_HERE, signaling_thread(),
5982 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005983 &SignalSctpClosingProcedureStartedRemotely, sid));
5984}
5985
5986void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5987 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5988 RTC_DCHECK(network_thread()->IsCurrent());
5989 sctp_invoker_->AsyncInvoke<void>(
5990 RTC_FROM_HERE, signaling_thread(),
5991 rtc::Bind(&sigslot::signal1<int>::operator(),
5992 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005993}
5994
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005995bool PeerConnection::SetupMediaTransportForDataChannels_n(
5996 const std::string& mid) {
5997 media_transport_ = transport_controller_->GetMediaTransport(mid);
5998 if (!media_transport_) {
5999 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6000 return false;
6001 }
6002
6003 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6004 media_transport_->SetDataSink(this);
6005 media_transport_data_mid_ = mid;
6006 transport_controller_->SignalMediaTransportStateChanged.connect(
6007 this, &PeerConnection::OnMediaTransportStateChanged_n);
6008 // Check the initial state right away, in case transport is already writable.
6009 OnMediaTransportStateChanged_n();
6010 return true;
6011}
6012
6013void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6014 if (!media_transport_) {
6015 return;
6016 }
6017 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6018 media_transport_data_mid_.reset();
6019 media_transport_->SetDataSink(nullptr);
6020 media_transport_invoker_ = nullptr;
6021 media_transport_ = nullptr;
6022}
6023
6024void PeerConnection::OnMediaTransportStateChanged_n() {
6025 if (!media_transport_data_mid_ ||
6026 transport_controller_->GetMediaTransportState(
6027 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6028 return;
6029 }
6030 media_transport_invoker_->AsyncInvoke<void>(
6031 RTC_FROM_HERE, signaling_thread(), [this] {
6032 RTC_DCHECK_RUN_ON(signaling_thread());
6033 media_transport_ready_to_send_data_ = true;
6034 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6035 });
6036}
6037
Steve Anton75737c02017-11-06 10:37:17 -08006038// Returns false if bundle is enabled and rtcp_mux is disabled.
6039bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6040 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6041 if (!bundle_enabled)
6042 return true;
6043
6044 const cricket::ContentGroup* bundle_group =
6045 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6046 RTC_DCHECK(bundle_group != NULL);
6047
6048 const cricket::ContentInfos& contents = desc->contents();
6049 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6050 citer != contents.end(); ++citer) {
6051 const cricket::ContentInfo* content = (&*citer);
6052 RTC_DCHECK(content != NULL);
6053 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006054 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006055 if (!HasRtcpMuxEnabled(content))
6056 return false;
6057 }
6058 }
6059 // RTCP-MUX is enabled in all the contents.
6060 return true;
6061}
6062
6063bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006064 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006065}
6066
Steve Anton8a006912017-12-04 15:25:56 -08006067RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006068 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006069 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006070 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006071 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006072 }
6073
6074 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006075 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006076 }
6077
Steve Anton3828c062017-12-06 10:34:51 -08006078 SdpType type = sdesc->GetType();
6079 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6080 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006081 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006082 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006083 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006084 }
6085
6086 // Verify crypto settings.
6087 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006088 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6089 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006090 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006091 if (!crypto_error.ok()) {
6092 return crypto_error;
6093 }
Steve Anton75737c02017-11-06 10:37:17 -08006094 }
6095
6096 // Verify ice-ufrag and ice-pwd.
6097 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006098 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6099 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006100 }
6101
6102 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006103 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6104 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006105 }
6106
6107 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6108 // m-lines that do not rtcp-mux enabled.
6109
6110 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006111 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006112 // With an answer we want to compare the new answer session description with
6113 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006114 const cricket::SessionDescription* offer_desc =
6115 (source == cricket::CS_LOCAL) ? remote_description()->description()
6116 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006117 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6118 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6119 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006120 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6121 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006122 }
6123 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006124 // The re-offers should respect the order of m= sections in current
6125 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006126 // With a re-offer, either the current local or current remote descriptions
6127 // could be the most up to date, so we would like to check against both of
6128 // them if they exist. It could be the case that one of them has a 0 port
6129 // for a media section, but the other does not. This is important to check
6130 // against in the case that we are recycling an m= section.
6131 const cricket::SessionDescription* current_desc = nullptr;
6132 const cricket::SessionDescription* secondary_current_desc = nullptr;
6133 if (local_description()) {
6134 current_desc = local_description()->description();
6135 if (remote_description()) {
6136 secondary_current_desc = remote_description()->description();
6137 }
6138 } else if (remote_description()) {
6139 current_desc = remote_description()->description();
6140 }
Steve Anton75737c02017-11-06 10:37:17 -08006141 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006142 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6143 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006144 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6145 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006146 }
6147 }
6148
Steve Antonba42e992018-04-09 14:10:01 -07006149 if (IsUnifiedPlan()) {
6150 // Ensure that each audio and video media section has at most one
6151 // "StreamParams". This will return an error if receiving a session
6152 // description from a "Plan B" endpoint which adds multiple tracks of the
6153 // same type. With Unified Plan, there can only be at most one track per
6154 // media section.
6155 for (const ContentInfo& content : sdesc->description()->contents()) {
6156 const MediaContentDescription& desc = *content.description;
6157 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6158 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6159 desc.streams().size() > 1u) {
6160 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6161 "Media section has more than one track specified "
6162 "with a=ssrc lines which is not supported with "
6163 "Unified Plan.");
6164 }
6165 }
6166 }
6167
Steve Anton8a006912017-12-04 15:25:56 -08006168 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006169}
6170
Steve Anton3828c062017-12-06 10:34:51 -08006171bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006172 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006173 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006174 return (state == PeerConnectionInterface::kStable) ||
6175 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006176 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006177 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006178 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6179 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6180 }
6181}
6182
Steve Anton3828c062017-12-06 10:34:51 -08006183bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006184 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006185 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006186 return (state == PeerConnectionInterface::kStable) ||
6187 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006188 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006189 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006190 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6191 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6192 }
6193}
6194
Steve Antonf8470812017-12-04 10:46:21 -08006195const char* PeerConnection::SessionErrorToString(SessionError error) const {
6196 switch (error) {
6197 case SessionError::kNone:
6198 return "ERROR_NONE";
6199 case SessionError::kContent:
6200 return "ERROR_CONTENT";
6201 case SessionError::kTransport:
6202 return "ERROR_TRANSPORT";
6203 }
6204 RTC_NOTREACHED();
6205 return "";
6206}
6207
Steve Anton75737c02017-11-06 10:37:17 -08006208std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006209 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006210 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6211 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006212 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006213}
6214
Steve Anton8e20f172018-03-06 10:55:04 -08006215void PeerConnection::ReportSdpFormatReceived(
6216 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006217 int num_audio_mlines = 0;
6218 int num_video_mlines = 0;
6219 int num_audio_tracks = 0;
6220 int num_video_tracks = 0;
6221 for (const ContentInfo& content : remote_offer.description()->contents()) {
6222 cricket::MediaType media_type = content.media_description()->type();
6223 int num_tracks = std::max(
6224 1, static_cast<int>(content.media_description()->streams().size()));
6225 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6226 num_audio_mlines += 1;
6227 num_audio_tracks += num_tracks;
6228 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6229 num_video_mlines += 1;
6230 num_video_tracks += num_tracks;
6231 }
6232 }
6233 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6234 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6235 format = kSdpFormatReceivedComplexUnifiedPlan;
6236 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6237 format = kSdpFormatReceivedComplexPlanB;
6238 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6239 format = kSdpFormatReceivedSimple;
6240 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006241 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6242 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006243}
6244
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006245void PeerConnection::NoteUsageEvent(UsageEvent event) {
6246 RTC_DCHECK_RUN_ON(signaling_thread());
6247 usage_event_accumulator_ |= static_cast<int>(event);
6248}
6249
6250void PeerConnection::ReportUsagePattern() const {
6251 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006252 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6253 usage_event_accumulator_,
6254 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006255 const int bad_bits =
6256 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6257 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6258 const int good_bits =
6259 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6260 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6261 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6262 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6263 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006264 // If called after close(), we can't report, because observer may have
6265 // been deallocated, and therefore pointer is null. Write to log instead.
6266 if (observer_) {
6267 Observer()->OnInterestingUsage(usage_event_accumulator_);
6268 } else {
6269 RTC_LOG(LS_INFO) << "Interesting usage signature "
6270 << usage_event_accumulator_
6271 << " observed after observer shutdown";
6272 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006273 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006274}
6275
Steve Anton0ffaaa22018-02-23 10:31:30 -08006276void PeerConnection::ReportNegotiatedSdpSemantics(
6277 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006278 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006279 switch (answer.description()->msid_signaling()) {
6280 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006281 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006282 break;
6283 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006284 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006285 break;
6286 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006287 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006288 break;
6289 case cricket::kMsidSignalingMediaSection |
6290 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006291 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006292 break;
6293 default:
6294 RTC_NOTREACHED();
6295 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006296 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6297 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006298}
6299
Steve Anton75737c02017-11-06 10:37:17 -08006300// We need to check the local/remote description for the Transport instead of
6301// the session, because a new Transport added during renegotiation may have
6302// them unset while the session has them set from the previous negotiation.
6303// Not doing so may trigger the auto generation of transport description and
6304// mess up DTLS identity information, ICE credential, etc.
6305bool PeerConnection::ReadyToUseRemoteCandidate(
6306 const IceCandidateInterface* candidate,
6307 const SessionDescriptionInterface* remote_desc,
6308 bool* valid) {
6309 *valid = true;
6310
6311 const SessionDescriptionInterface* current_remote_desc =
6312 remote_desc ? remote_desc : remote_description();
6313
6314 if (!current_remote_desc) {
6315 return false;
6316 }
6317
6318 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6319 size_t remote_content_size =
6320 current_remote_desc->description()->contents().size();
6321 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006322 RTC_LOG(LS_ERROR)
6323 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6324 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006325
6326 *valid = false;
6327 return false;
6328 }
6329
6330 cricket::ContentInfo content =
6331 current_remote_desc->description()->contents()[mediacontent_index];
6332
6333 const std::string transport_name = GetTransportName(content.name);
6334 if (transport_name.empty()) {
6335 return false;
6336 }
Zhi Huange830e682018-03-30 10:48:35 -07006337 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006338}
6339
6340bool PeerConnection::SrtpRequired() const {
6341 return dtls_enabled_ ||
6342 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6343}
6344
6345void PeerConnection::OnTransportControllerGatheringState(
6346 cricket::IceGatheringState state) {
6347 RTC_DCHECK(signaling_thread()->IsCurrent());
6348 if (state == cricket::kIceGatheringGathering) {
6349 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6350 } else if (state == cricket::kIceGatheringComplete) {
6351 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6352 }
6353}
6354
6355void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006356 std::map<std::string, std::set<cricket::MediaType>>
6357 media_types_by_transport_name;
6358 for (auto transceiver : transceivers_) {
6359 if (transceiver->internal()->channel()) {
6360 const std::string& transport_name =
6361 transceiver->internal()->channel()->transport_name();
6362 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006363 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006364 }
Steve Anton75737c02017-11-06 10:37:17 -08006365 }
6366 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006367 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6368 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006369 }
Zhi Huange830e682018-03-30 10:48:35 -07006370
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006371 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006372 if (transport_name) {
6373 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006374 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006375 }
Zhi Huange830e682018-03-30 10:48:35 -07006376
Steve Antonc7b964c2018-02-01 14:39:45 -08006377 for (const auto& entry : media_types_by_transport_name) {
6378 const std::string& transport_name = entry.first;
6379 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006380 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006381 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006382 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006383 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006384 }
6385 }
6386}
6387// Walk through the ConnectionInfos to gather best connection usage
6388// for IPv4 and IPv6.
6389void PeerConnection::ReportBestConnectionState(
6390 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006391 for (const cricket::TransportChannelStats& channel_stats :
6392 stats.channel_stats) {
6393 for (const cricket::ConnectionInfo& connection_info :
6394 channel_stats.connection_infos) {
6395 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006396 continue;
6397 }
6398
Steve Antonc7b964c2018-02-01 14:39:45 -08006399 const cricket::Candidate& local = connection_info.local_candidate;
6400 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006401
6402 // Increment the counter for IceCandidatePairType.
6403 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6404 (local.type() == RELAY_PORT_TYPE &&
6405 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006406 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6407 GetIceCandidatePairCounter(local, remote),
6408 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006409 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006410 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6411 GetIceCandidatePairCounter(local, remote),
6412 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006413 } else {
6414 RTC_CHECK(0);
6415 }
Steve Anton75737c02017-11-06 10:37:17 -08006416
6417 // Increment the counter for IP type.
6418 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006419 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6420 kBestConnections_IPv4,
6421 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006422 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006423 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6424 kBestConnections_IPv6,
6425 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006426 } else {
6427 RTC_CHECK(0);
6428 }
6429
6430 return;
6431 }
6432 }
6433}
6434
6435void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006436 const cricket::TransportStats& stats,
6437 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006438 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6439 return;
6440 }
6441
6442 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6443 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6444 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6445 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6446 return;
6447 }
6448
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006449 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6450 for (cricket::MediaType media_type : media_types) {
6451 switch (media_type) {
6452 case cricket::MEDIA_TYPE_AUDIO:
6453 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6454 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6455 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6456 break;
6457 case cricket::MEDIA_TYPE_VIDEO:
6458 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6459 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6460 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6461 break;
6462 case cricket::MEDIA_TYPE_DATA:
6463 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6464 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6465 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6466 break;
6467 default:
6468 RTC_NOTREACHED();
6469 continue;
6470 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006471 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006472 }
6473
6474 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6475 for (cricket::MediaType media_type : media_types) {
6476 switch (media_type) {
6477 case cricket::MEDIA_TYPE_AUDIO:
6478 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6479 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6480 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6481 break;
6482 case cricket::MEDIA_TYPE_VIDEO:
6483 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6484 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6485 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6486 break;
6487 case cricket::MEDIA_TYPE_DATA:
6488 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6489 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6490 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6491 break;
6492 default:
6493 RTC_NOTREACHED();
6494 continue;
6495 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006496 }
Steve Anton75737c02017-11-06 10:37:17 -08006497 }
6498}
6499
6500void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6501 RTC_DCHECK(worker_thread()->IsCurrent());
6502 RTC_DCHECK(call_);
6503 call_->OnSentPacket(sent_packet);
6504}
6505
6506const std::string PeerConnection::GetTransportName(
6507 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006508 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006509 if (channel) {
6510 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006511 }
Steve Anton6fec8802017-12-04 10:37:29 -08006512 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006513 RTC_DCHECK(sctp_mid_);
6514 if (content_name == *sctp_mid_) {
6515 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006516 }
6517 }
6518 // Return an empty string if failed to retrieve the transport name.
6519 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006520}
6521
Steve Anton6fec8802017-12-04 10:37:29 -08006522void PeerConnection::DestroyTransceiverChannel(
6523 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6524 transceiver) {
6525 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006526
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006527 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006528 if (channel) {
6529 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006530 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006531 }
6532}
6533
6534void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006535 if (rtp_data_channel_) {
6536 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006537 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006538 rtp_data_channel_ = nullptr;
6539 }
6540
6541 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6542 // grab a reference to this PeerConnection. If this is called from the
6543 // PeerConnection destructor, the RefCountedObject vtable will have already
6544 // been destroyed (since it is a subclass of PeerConnection) and using
6545 // rtc::Bind will cause "Pure virtual function called" error to appear.
6546
6547 if (sctp_transport_) {
6548 OnDataChannelDestroyed();
6549 network_thread()->Invoke<void>(RTC_FROM_HERE,
6550 [this] { DestroySctpTransport_n(); });
6551 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006552
6553 if (media_transport_) {
6554 OnDataChannelDestroyed();
6555 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6556 RTC_DCHECK_RUN_ON(network_thread());
6557 TeardownMediaTransportForDataChannels_n();
6558 });
6559 }
Steve Anton6fec8802017-12-04 10:37:29 -08006560}
6561
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006562void PeerConnection::DestroyChannelInterface(
6563 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006564 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006565 switch (channel->media_type()) {
6566 case cricket::MEDIA_TYPE_AUDIO:
6567 channel_manager()->DestroyVoiceChannel(
6568 static_cast<cricket::VoiceChannel*>(channel));
6569 break;
6570 case cricket::MEDIA_TYPE_VIDEO:
6571 channel_manager()->DestroyVideoChannel(
6572 static_cast<cricket::VideoChannel*>(channel));
6573 break;
6574 case cricket::MEDIA_TYPE_DATA:
6575 channel_manager()->DestroyRtpDataChannel(
6576 static_cast<cricket::RtpDataChannel*>(channel));
6577 break;
6578 default:
6579 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6580 break;
6581 }
Zhi Huange830e682018-03-30 10:48:35 -07006582}
Steve Anton6fec8802017-12-04 10:37:29 -08006583
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006584bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006585 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006586 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006587 cricket::DtlsTransportInternal* dtls_transport,
6588 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006589 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006590 auto base_channel = GetChannel(mid);
6591 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006592 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006593 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006594 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006595 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006596 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006597
6598 call_->MediaTransportChange(media_transport);
6599
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006600 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006601}
6602
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006603PeerConnectionObserver* PeerConnection::Observer() const {
6604 // In earlier production code, the pointer was not cleared on close,
6605 // which might have led to undefined behavior if the observer was not
6606 // deallocated, or strange crashes if it was.
6607 // We use CHECK in order to catch such behavior if it exists.
6608 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6609 RTC_CHECK(observer_);
6610 return observer_;
6611}
6612
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006613CryptoOptions PeerConnection::GetCryptoOptions() {
6614 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6615 // after it has been removed.
6616 return configuration_.crypto_options.has_value()
6617 ? *configuration_.crypto_options
6618 : factory_->options().crypto_options;
6619}
6620
Harald Alvestrand89061872018-01-02 14:08:34 +01006621void PeerConnection::ClearStatsCache() {
6622 if (stats_collector_) {
6623 stats_collector_->ClearCachedStatsReport();
6624 }
6625}
6626
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006627void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006628 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6629 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006630}
6631
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006632} // namespace webrtc