blob: e60474ca1d34ad16f68df835ca53a63ba375ffc5 [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;
717 int ice_connection_receiving_timeout;
718 int ice_backup_candidate_pair_ping_interval;
719 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800720 bool prioritize_most_likely_ice_candidate_pairs;
721 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800722 bool prune_turn_ports;
723 bool presume_writable_when_fully_relayed;
724 bool enable_ice_renomination;
725 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200726 absl::optional<int> ice_check_interval_strong_connectivity;
727 absl::optional<int> ice_check_interval_weak_connectivity;
728 absl::optional<int> ice_check_min_interval;
729 absl::optional<int> ice_unwritable_timeout;
730 absl::optional<int> ice_unwritable_min_checks;
731 absl::optional<int> stun_candidate_keepalive_interval;
732 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200733 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800734 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700736 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700737 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700738 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700739 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100740 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800741 };
742 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
743 "Did you add something to RTCConfiguration and forget to "
744 "update operator==?");
745 return type == o.type && servers == o.servers &&
746 bundle_policy == o.bundle_policy &&
747 rtcp_mux_policy == o.rtcp_mux_policy &&
748 tcp_candidate_policy == o.tcp_candidate_policy &&
749 candidate_network_policy == o.candidate_network_policy &&
750 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
751 audio_jitter_buffer_fast_accelerate ==
752 o.audio_jitter_buffer_fast_accelerate &&
753 ice_connection_receiving_timeout ==
754 o.ice_connection_receiving_timeout &&
755 ice_backup_candidate_pair_ping_interval ==
756 o.ice_backup_candidate_pair_ping_interval &&
757 continual_gathering_policy == o.continual_gathering_policy &&
758 certificates == o.certificates &&
759 prioritize_most_likely_ice_candidate_pairs ==
760 o.prioritize_most_likely_ice_candidate_pairs &&
761 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800762 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700763 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100764 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800765 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800766 screencast_min_bitrate == o.screencast_min_bitrate &&
767 combined_audio_video_bwe == o.combined_audio_video_bwe &&
768 enable_dtls_srtp == o.enable_dtls_srtp &&
769 ice_candidate_pool_size == o.ice_candidate_pool_size &&
770 prune_turn_ports == o.prune_turn_ports &&
771 presume_writable_when_fully_relayed ==
772 o.presume_writable_when_fully_relayed &&
773 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800774 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800775 ice_check_interval_strong_connectivity ==
776 o.ice_check_interval_strong_connectivity &&
777 ice_check_interval_weak_connectivity ==
778 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700779 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700780 ice_unwritable_timeout == o.ice_unwritable_timeout &&
781 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800782 stun_candidate_keepalive_interval ==
783 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200784 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800785 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800786 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700787 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700788 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700789 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700790 use_media_transport_for_data_channels ==
791 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100792 crypto_options == o.crypto_options &&
793 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800794}
795
796bool PeerConnectionInterface::RTCConfiguration::operator!=(
797 const PeerConnectionInterface::RTCConfiguration& o) const {
798 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800799}
800
zhihuang8f65cdf2016-05-06 18:40:30 -0700801// Generate a RTCP CNAME when a PeerConnection is created.
802std::string GenerateRtcpCname() {
803 std::string cname;
804 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100805 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800806 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700807 }
808 return cname;
809}
810
zhihuang1c378ed2017-08-17 14:10:50 -0700811bool ValidateOfferAnswerOptions(
812 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
813 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
814 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700815}
816
zhihuang1c378ed2017-08-17 14:10:50 -0700817// From |rtc_options|, fill parts of |session_options| shared by all generated
818// m= sections (in other words, nothing that involves a map/array).
819void ExtractSharedMediaSessionOptions(
820 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
821 cricket::MediaSessionOptions* session_options) {
822 session_options->vad_enabled = rtc_options.voice_activity_detection;
823 session_options->bundle_enabled = rtc_options.use_rtp_mux;
824}
zhihuanga77e6bb2017-08-14 18:17:48 -0700825
zhihuang38ede132017-06-15 12:52:32 -0700826PeerConnection::PeerConnection(PeerConnectionFactory* factory,
827 std::unique_ptr<RtcEventLog> event_log,
828 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700830 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700831 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700832 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700833 remote_streams_(StreamCollection::Create()),
834 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835
836PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100837 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800838 RTC_DCHECK_RUN_ON(signaling_thread());
839
Steve Anton8af21862017-12-15 11:20:13 -0800840 // Need to stop transceivers before destroying the stats collector because
841 // AudioRtpSender has a reference to the StatsCollector it will update when
842 // stopping.
843 for (auto transceiver : transceivers_) {
844 transceiver->Stop();
845 }
Steve Anton4171afb2017-11-20 10:20:22 -0800846
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700847 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800848 if (stats_collector_) {
849 stats_collector_->WaitForPendingRequest();
850 stats_collector_ = nullptr;
851 }
Steve Anton75737c02017-11-06 10:37:17 -0800852
Steve Anton8af21862017-12-15 11:20:13 -0800853 // Don't destroy BaseChannels until after stats has been cleaned up so that
854 // the last stats request can still read from the channels.
855 DestroyAllChannels();
856
Mirko Bonadei675513b2017-11-09 11:09:25 +0100857 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800858
859 webrtc_session_desc_factory_.reset();
860 sctp_invoker_.reset();
861 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800862 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800863 transport_controller_.reset();
864
deadbeef91dd5672016-05-18 16:55:30 -0700865 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700866 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700867 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700868 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700869 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700870 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800871 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700872 event_log_.reset();
873 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874}
875
Steve Anton8af21862017-12-15 11:20:13 -0800876void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800877 // Destroy video channels first since they may have a pointer to a voice
878 // channel.
879 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800880 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800881 DestroyTransceiverChannel(transceiver);
882 }
883 }
884 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800885 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800886 DestroyTransceiverChannel(transceiver);
887 }
888 }
889 DestroyDataChannel();
890}
891
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000893 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700894 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100895 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700896
897 RTCError config_error = ValidateConfiguration(configuration);
898 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700900 return false;
901 }
902
Benjamin Wrightcab58882018-05-02 15:12:47 -0700903 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_ERROR)
905 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100906 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800907 return false;
908 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200909
Benjamin Wrightcab58882018-05-02 15:12:47 -0700910 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800911 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100912 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100913 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800914 return false;
915 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700916
Benjamin Wrightcab58882018-05-02 15:12:47 -0700917 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700918 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700919 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700920 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800921
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200922 cricket::ServerAddresses stun_servers;
923 std::vector<cricket::RelayServerConfig> turn_servers;
924
925 RTCErrorType parse_error =
926 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
927 if (parse_error != RTCErrorType::NONE) {
928 return false;
929 }
930
deadbeef91dd5672016-05-18 16:55:30 -0700931 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700932 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700933 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200934 RTC_FROM_HERE,
935 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
936 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 return false;
938 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200939 // If initialization was successful, note if STUN or TURN servers
940 // were supplied.
941 if (!stun_servers.empty()) {
942 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
943 }
944 if (!turn_servers.empty()) {
945 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
946 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700948 // Send information about IPv4/IPv6 status.
949 PeerConnectionAddressFamilyCounter address_family;
950 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
951 address_family = kPeerConnection_IPv6;
952 } else {
953 address_family = kPeerConnection_IPv4;
954 }
955 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
956 kPeerConnectionAddressFamilyCounter_Max);
957
Zhi Huange830e682018-03-30 10:48:35 -0700958 const PeerConnectionFactoryInterface::Options& options = factory_->options();
959
Steve Anton75737c02017-11-06 10:37:17 -0800960 // RFC 3264: The numeric value of the session id and version in the
961 // o line MUST be representable with a "64 bit signed integer".
962 // Due to this constraint session id |session_id_| is max limited to
963 // LLONG_MAX.
964 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700965 JsepTransportController::Config config;
966 config.redetermine_role_on_ice_restart =
967 configuration.redetermine_role_on_ice_restart;
968 config.ssl_max_version = factory_->options().ssl_max_version;
969 config.disable_encryption = options.disable_encryption;
970 config.bundle_policy = configuration.bundle_policy;
971 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700972 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
973 // stub.
974 config.crypto_options = configuration.crypto_options.has_value()
975 ? *configuration.crypto_options
976 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700977 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700978 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700979#if defined(ENABLE_EXTERNAL_AUTH)
980 config.enable_external_auth = true;
981#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700982 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700983
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700984 if (configuration.use_media_transport ||
985 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700986 if (!factory_->media_transport_factory()) {
987 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700988 << "PeerConnecton is initialized with use_media_transport = true or "
989 << "use_media_transport_for_data_channels = true "
990 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700991 return false;
992 }
993
994 config.media_transport_factory = factory_->media_transport_factory();
995 }
996
Zhi Huange830e682018-03-30 10:48:35 -0700997 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700998 signaling_thread(), network_thread(), port_allocator_.get(),
999 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001000 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001001 this, &PeerConnection::OnTransportControllerConnectionState);
1002 transport_controller_->SignalStandardizedIceConnectionState.connect(
1003 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001004 transport_controller_->SignalConnectionState.connect(
1005 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001006 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001007 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001008 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001009 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001010 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001011 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1012 transport_controller_->SignalDtlsHandshakeError.connect(
1013 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1014
1015 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001016
deadbeefab9b2d12015-10-14 11:33:11 -07001017 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001018 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019
Steve Antonba818672017-11-06 10:21:57 -08001020 configuration_ = configuration;
1021
Steve Anton75737c02017-11-06 10:37:17 -08001022 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1023 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1024 if (!configuration.certificates.empty()) {
1025 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1026 // just picking the first one. The decision should be made based on the DTLS
1027 // handshake. The DTLS negotiations need to know about all certificates.
1028 certificate = configuration.certificates[0];
1029 }
1030
Steve Antond25da372017-11-06 14:50:29 -08001031 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001032
1033 if (options.disable_encryption) {
1034 dtls_enabled_ = false;
1035 } else {
1036 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001037 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001038 // |configuration| can override the default |dtls_enabled_| value.
1039 if (configuration.enable_dtls_srtp) {
1040 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1041 }
1042 }
1043
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001044 if (configuration.use_media_transport_for_data_channels) {
1045 if (configuration.enable_rtp_data_channel) {
1046 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1047 "use_media_transport_for_data_channels are "
1048 "incompatible and cannot both be set to true";
1049 return false;
1050 }
1051 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1052 } else if (configuration.enable_rtp_data_channel) {
1053 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1054 // set. It takes precendence over the disable_sctp_data_channels
1055 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001056 data_channel_type_ = cricket::DCT_RTP;
1057 } else {
1058 // DTLS has to be enabled to use SCTP.
1059 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1060 data_channel_type_ = cricket::DCT_SCTP;
1061 }
1062 }
1063
1064 video_options_.screencast_min_bitrate_kbps =
1065 configuration.screencast_min_bitrate;
1066 audio_options_.combined_audio_video_bwe =
1067 configuration.combined_audio_video_bwe;
1068
1069 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001070 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001071
1072 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001073 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001074
1075 // Whether the certificate generator/certificate is null or not determines
1076 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1077 // the right instructions by clearing the variables if needed.
1078 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001079 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001080 certificate = nullptr;
1081 } else if (certificate) {
1082 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001083 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001084 }
1085
1086 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1087 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001088 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001089 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1090 this, &PeerConnection::OnCertificateReady);
1091
1092 if (options.disable_encryption) {
1093 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1094 }
1095
1096 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001097 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001098
Steve Anton4171afb2017-11-20 10:20:22 -08001099 // Add default audio/video transceivers for Plan B SDP.
1100 if (!IsUnifiedPlan()) {
1101 transceivers_.push_back(
1102 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1103 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1104 transceivers_.push_back(
1105 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1106 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1107 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001108 int delay_ms =
1109 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001110 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1111 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001112 return true;
1113}
1114
Steve Anton038834f2017-07-14 15:59:59 -07001115RTCError PeerConnection::ValidateConfiguration(
1116 const RTCConfiguration& config) const {
1117 if (config.ice_regather_interval_range &&
1118 config.continual_gathering_policy == GATHER_ONCE) {
1119 return RTCError(RTCErrorType::INVALID_PARAMETER,
1120 "ice_regather_interval_range specified but continual "
1121 "gathering policy is GATHER_ONCE");
1122 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001123 auto result =
1124 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1125 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001126}
1127
Yves Gerey665174f2018-06-19 15:03:05 +02001128rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001129 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1130 "Plan SdpSemantics. Please use GetSenders "
1131 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001132 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133}
1134
Yves Gerey665174f2018-06-19 15:03:05 +02001135rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001136 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1137 "Plan SdpSemantics. Please use GetReceivers "
1138 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001139 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001140}
1141
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001142bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001143 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1144 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001145 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001146 if (IsClosed()) {
1147 return false;
1148 }
deadbeefab9b2d12015-10-14 11:33:11 -07001149 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150 return false;
1151 }
deadbeefab9b2d12015-10-14 11:33:11 -07001152
1153 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001154 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1155 observer->SignalAudioTrackAdded.connect(this,
1156 &PeerConnection::OnAudioTrackAdded);
1157 observer->SignalAudioTrackRemoved.connect(
1158 this, &PeerConnection::OnAudioTrackRemoved);
1159 observer->SignalVideoTrackAdded.connect(this,
1160 &PeerConnection::OnVideoTrackAdded);
1161 observer->SignalVideoTrackRemoved.connect(
1162 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001163 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001164
deadbeefab9b2d12015-10-14 11:33:11 -07001165 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001166 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001167 }
1168 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001169 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001170 }
1171
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001172 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001173 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001174 return true;
1175}
1176
1177void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001178 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1179 "Plan SdpSemantics. Please use RemoveTrack "
1180 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001181 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001182 if (!IsClosed()) {
1183 for (const auto& track : local_stream->GetAudioTracks()) {
1184 RemoveAudioTrack(track.get(), local_stream);
1185 }
1186 for (const auto& track : local_stream->GetVideoTracks()) {
1187 RemoveVideoTrack(track.get(), local_stream);
1188 }
deadbeefab9b2d12015-10-14 11:33:11 -07001189 }
deadbeefab9b2d12015-10-14 11:33:11 -07001190 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001191 stream_observers_.erase(
1192 std::remove_if(
1193 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001194 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001195 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001196 }),
1197 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001198
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199 if (IsClosed()) {
1200 return;
1201 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001202 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203}
1204
Steve Anton2d6c76a2018-01-05 17:10:52 -08001205RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001206 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001207 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001208 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001209 if (!track) {
1210 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1211 }
1212 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1213 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1215 "Track has invalid kind: " + track->kind());
1216 }
Steve Antonf9381f02017-12-14 10:23:57 -08001217 if (IsClosed()) {
1218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1219 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001220 }
Steve Anton4171afb2017-11-20 10:20:22 -08001221 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001222 LOG_AND_RETURN_ERROR(
1223 RTCErrorType::INVALID_PARAMETER,
1224 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001225 }
Steve Antonf9381f02017-12-14 10:23:57 -08001226 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001227 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1228 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001229 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001230 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001231 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001232 }
1233 return sender_or_error;
1234}
deadbeefe1f9d832016-01-14 15:35:42 -08001235
Steve Antonf9381f02017-12-14 10:23:57 -08001236RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1237PeerConnection::AddTrackPlanB(
1238 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001239 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001240 if (stream_ids.size() > 1u) {
1241 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1242 "AddTrack with more than one stream is not "
1243 "supported with Plan B semantics.");
1244 }
1245 std::vector<std::string> adjusted_stream_ids = stream_ids;
1246 if (adjusted_stream_ids.empty()) {
1247 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1248 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001249 cricket::MediaType media_type =
1250 (track->kind() == MediaStreamTrackInterface::kAudioKind
1251 ? cricket::MEDIA_TYPE_AUDIO
1252 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001253 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001254 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001255 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001256 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001257 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001258 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001259 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001260 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001261 if (sender_info) {
1262 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001263 }
Steve Antonf9381f02017-12-14 10:23:57 -08001264 } else {
1265 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001266 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001267 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001268 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001269 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001270 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001271 if (sender_info) {
1272 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001273 }
deadbeefe1f9d832016-01-14 15:35:42 -08001274 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001275 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001276}
deadbeefe1f9d832016-01-14 15:35:42 -08001277
Steve Antonf9381f02017-12-14 10:23:57 -08001278RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1279PeerConnection::AddTrackUnifiedPlan(
1280 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001281 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001282 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1283 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001284 RTC_LOG(LS_INFO) << "Reusing an existing "
1285 << cricket::MediaTypeToString(transceiver->media_type())
1286 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001287 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001288 transceiver->internal()->set_direction(
1289 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001290 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001291 transceiver->internal()->set_direction(
1292 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001293 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001294 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001295 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001296 } else {
1297 cricket::MediaType media_type =
1298 (track->kind() == MediaStreamTrackInterface::kAudioKind
1299 ? cricket::MEDIA_TYPE_AUDIO
1300 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001301 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1302 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001303 std::string sender_id = track->id();
1304 // Avoid creating a sender with an existing ID by generating a random ID.
1305 // This can happen if this is the second time AddTrack has created a sender
1306 // for this track.
1307 if (FindSenderById(sender_id)) {
1308 sender_id = rtc::CreateRandomUuid();
1309 }
Florent Castelli892acf02018-10-01 22:47:20 +02001310 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001311 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1312 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001314 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001315 }
Steve Antonf9381f02017-12-14 10:23:57 -08001316 return transceiver->sender();
1317}
1318
1319rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1320PeerConnection::FindFirstTransceiverForAddedTrack(
1321 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1322 RTC_DCHECK(track);
1323 for (auto transceiver : transceivers_) {
1324 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001325 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001326 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001327 !transceiver->internal()->has_ever_been_used_to_send() &&
1328 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001329 return transceiver;
1330 }
1331 }
1332 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001333}
1334
1335bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1336 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001337 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001338}
1339
Steve Anton24db5732018-07-23 10:27:33 -07001340RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001341 rtc::scoped_refptr<RtpSenderInterface> sender) {
1342 if (!sender) {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1344 }
deadbeefe1f9d832016-01-14 15:35:42 -08001345 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001346 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1347 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001348 }
Steve Antonf9381f02017-12-14 10:23:57 -08001349 if (IsUnifiedPlan()) {
1350 auto transceiver = FindTransceiverBySender(sender);
1351 if (!transceiver || !sender->track()) {
1352 return RTCError::OK();
1353 }
1354 sender->SetTrack(nullptr);
1355 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001356 transceiver->internal()->set_direction(
1357 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001358 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001359 transceiver->internal()->set_direction(
1360 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001361 }
Steve Anton4171afb2017-11-20 10:20:22 -08001362 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001363 bool removed;
1364 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1365 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1366 } else {
1367 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1368 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1369 }
1370 if (!removed) {
1371 LOG_AND_RETURN_ERROR(
1372 RTCErrorType::INVALID_PARAMETER,
1373 "Couldn't find sender " + sender->id() + " to remove.");
1374 }
Steve Anton4171afb2017-11-20 10:20:22 -08001375 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001376 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001377 return RTCError::OK();
1378}
1379
1380rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1381PeerConnection::FindTransceiverBySender(
1382 rtc::scoped_refptr<RtpSenderInterface> sender) {
1383 for (auto transceiver : transceivers_) {
1384 if (transceiver->sender() == sender) {
1385 return transceiver;
1386 }
1387 }
1388 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001389}
1390
Steve Anton9158ef62017-11-27 13:01:52 -08001391RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1392PeerConnection::AddTransceiver(
1393 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1394 return AddTransceiver(track, RtpTransceiverInit());
1395}
1396
1397RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1398PeerConnection::AddTransceiver(
1399 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1400 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001401 RTC_CHECK(IsUnifiedPlan())
1402 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001403 if (!track) {
1404 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1405 }
1406 cricket::MediaType media_type;
1407 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1408 media_type = cricket::MEDIA_TYPE_AUDIO;
1409 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1410 media_type = cricket::MEDIA_TYPE_VIDEO;
1411 } else {
1412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1413 "Track kind is not audio or video");
1414 }
1415 return AddTransceiver(media_type, track, init);
1416}
1417
1418RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1419PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1420 return AddTransceiver(media_type, RtpTransceiverInit());
1421}
1422
1423RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1424PeerConnection::AddTransceiver(cricket::MediaType media_type,
1425 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001426 RTC_CHECK(IsUnifiedPlan())
1427 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001428 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1429 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1430 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1431 "media type is not audio or video");
1432 }
1433 return AddTransceiver(media_type, nullptr, init);
1434}
1435
1436RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1437PeerConnection::AddTransceiver(
1438 cricket::MediaType media_type,
1439 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001440 const RtpTransceiverInit& init,
1441 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001442 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1443 media_type == cricket::MEDIA_TYPE_VIDEO));
1444 if (track) {
1445 RTC_DCHECK_EQ(media_type,
1446 (track->kind() == MediaStreamTrackInterface::kAudioKind
1447 ? cricket::MEDIA_TYPE_AUDIO
1448 : cricket::MEDIA_TYPE_VIDEO));
1449 }
1450
1451 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001452 if (init.send_encodings.size() > 1) {
1453 LOG_AND_RETURN_ERROR(
1454 RTCErrorType::UNSUPPORTED_PARAMETER,
1455 "Attempted to create an encoder with more than 1 encoding parameter.");
1456 }
1457
1458 for (const auto& encoding : init.send_encodings) {
1459 if (encoding.ssrc.has_value()) {
1460 LOG_AND_RETURN_ERROR(
1461 RTCErrorType::UNSUPPORTED_PARAMETER,
1462 "Attempted to set an unimplemented parameter of RtpParameters.");
1463 }
1464 }
1465
1466 RtpParameters parameters;
1467 parameters.encodings = init.send_encodings;
1468 if (UnimplementedRtpParameterHasValue(parameters)) {
1469 LOG_AND_RETURN_ERROR(
1470 RTCErrorType::UNSUPPORTED_PARAMETER,
1471 "Attempted to set an unimplemented parameter of RtpParameters.");
1472 }
Steve Anton9158ef62017-11-27 13:01:52 -08001473
Steve Anton3d954a62018-04-02 11:27:23 -07001474 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1475 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001476 // Set the sender ID equal to the track ID if the track is specified unless
1477 // that sender ID is already in use.
1478 std::string sender_id =
1479 (track && !FindSenderById(track->id()) ? track->id()
1480 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001481 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1482 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001483 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1484 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1485 transceiver->internal()->set_direction(init.direction);
1486
Steve Anton22da89f2018-01-25 13:58:07 -08001487 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001488 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001489 }
Steve Antonf9381f02017-12-14 10:23:57 -08001490
1491 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1492}
1493
Steve Anton02ee47c2018-01-10 16:26:06 -08001494rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1495PeerConnection::CreateSender(
1496 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001497 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001498 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001499 const std::vector<std::string>& stream_ids,
1500 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001501 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001502 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1503 RTC_DCHECK(!track ||
1504 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1505 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1506 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001507 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001508 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001509 } else {
1510 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1511 RTC_DCHECK(!track ||
1512 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1513 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001514 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001515 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001516 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001517 bool set_track_succeeded = sender->SetTrack(track);
1518 RTC_DCHECK(set_track_succeeded);
1519 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001520 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001521 return sender;
1522}
1523
1524rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1525PeerConnection::CreateReceiver(cricket::MediaType media_type,
1526 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001527 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1528 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001529 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001530 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001531 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1532 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001533 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001534 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001535 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001536 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001537 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1538 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001539 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001540 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001541 return receiver;
1542}
1543
1544rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1545PeerConnection::CreateAndAddTransceiver(
1546 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1547 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1548 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001549 // Ensure that the new sender does not have an ID that is already in use by
1550 // another sender.
1551 // Allow receiver IDs to conflict since those come from remote SDP (which
1552 // could be invalid, but should not cause a crash).
1553 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001554 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1555 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001556 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001557 transceiver->internal()->SignalNegotiationNeeded.connect(
1558 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001559 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001560}
1561
Steve Anton52d86772018-02-20 15:48:12 -08001562void PeerConnection::OnNegotiationNeeded() {
1563 RTC_DCHECK_RUN_ON(signaling_thread());
1564 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001565 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001566}
1567
deadbeeffac06552015-11-25 11:26:01 -08001568rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001569 const std::string& kind,
1570 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001571 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1572 "Plan SdpSemantics. Please use AddTransceiver "
1573 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001574 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001575 if (IsClosed()) {
1576 return nullptr;
1577 }
Steve Anton4171afb2017-11-20 10:20:22 -08001578
Seth Hampson5b4f0752018-04-02 16:31:36 -07001579 // Internally we need to have one stream with Plan B semantics, so we
1580 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001581 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001582 if (stream_id.empty()) {
1583 stream_ids.push_back(rtc::CreateRandomUuid());
1584 RTC_LOG(LS_INFO)
1585 << "No stream_id specified for sender. Generated stream ID: "
1586 << stream_ids[0];
1587 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001588 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001589 }
1590
Steve Anton4171afb2017-11-20 10:20:22 -08001591 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001592 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001593 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001594 auto* audio_sender = new AudioRtpSender(
1595 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001596 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001597 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001598 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001599 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001600 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001601 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001602 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001603 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001604 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001605 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001606 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001607 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001608 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001609 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001610 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001611 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001612
deadbeefe1f9d832016-01-14 15:35:42 -08001613 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001614}
1615
deadbeef70ab1a12015-09-28 16:53:55 -07001616std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1617 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001618 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001619 for (auto sender : GetSendersInternal()) {
1620 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001621 }
1622 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001623}
1624
Steve Anton4171afb2017-11-20 10:20:22 -08001625std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1626PeerConnection::GetSendersInternal() const {
1627 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1628 all_senders;
1629 for (auto transceiver : transceivers_) {
1630 auto senders = transceiver->internal()->senders();
1631 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1632 }
1633 return all_senders;
1634}
1635
deadbeef70ab1a12015-09-28 16:53:55 -07001636std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1637PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001638 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001639 for (const auto& receiver : GetReceiversInternal()) {
1640 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001641 }
1642 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001643}
1644
Steve Anton4171afb2017-11-20 10:20:22 -08001645std::vector<
1646 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1647PeerConnection::GetReceiversInternal() const {
1648 std::vector<
1649 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1650 all_receivers;
1651 for (auto transceiver : transceivers_) {
1652 auto receivers = transceiver->internal()->receivers();
1653 all_receivers.insert(all_receivers.end(), receivers.begin(),
1654 receivers.end());
1655 }
1656 return all_receivers;
1657}
1658
Steve Anton9158ef62017-11-27 13:01:52 -08001659std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1660PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001661 RTC_CHECK(IsUnifiedPlan())
1662 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001663 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1664 for (auto transceiver : transceivers_) {
1665 all_transceivers.push_back(transceiver);
1666 }
1667 return all_transceivers;
1668}
1669
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001670bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001671 MediaStreamTrackInterface* track,
1672 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001673 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001674 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001675 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001676 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001677 return false;
1678 }
1679
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001680 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001681 // The StatsCollector is used to tell if a track is valid because it may
1682 // remember tracks that the PeerConnection previously removed.
1683 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001684 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1685 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001686 return false;
1687 }
Steve Antonad182762018-09-05 20:22:40 +00001688 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1689 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690 return true;
1691}
1692
hbos74e1a4f2016-09-15 23:33:01 -07001693void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001694 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001695 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001696 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001697 stats_collector_->GetStatsReport(callback);
1698}
1699
Henrik Boström1df1bf82018-03-20 13:24:20 +01001700void PeerConnection::GetStats(
1701 rtc::scoped_refptr<RtpSenderInterface> selector,
1702 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1703 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1704 RTC_DCHECK(callback);
1705 RTC_DCHECK(stats_collector_);
1706 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1707 if (selector) {
1708 for (const auto& proxy_transceiver : transceivers_) {
1709 for (const auto& proxy_sender :
1710 proxy_transceiver->internal()->senders()) {
1711 if (proxy_sender == selector) {
1712 internal_sender = proxy_sender->internal();
1713 break;
1714 }
1715 }
1716 if (internal_sender)
1717 break;
1718 }
1719 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001720 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001721 // belong to the PeerConnection (in Plan B, senders can be removed from the
1722 // PeerConnection). This means that "all the stats objects representing the
1723 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1724 // produces an empty stats report.
1725 stats_collector_->GetStatsReport(internal_sender, callback);
1726}
1727
1728void PeerConnection::GetStats(
1729 rtc::scoped_refptr<RtpReceiverInterface> selector,
1730 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1731 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1732 RTC_DCHECK(callback);
1733 RTC_DCHECK(stats_collector_);
1734 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1735 if (selector) {
1736 for (const auto& proxy_transceiver : transceivers_) {
1737 for (const auto& proxy_receiver :
1738 proxy_transceiver->internal()->receivers()) {
1739 if (proxy_receiver == selector) {
1740 internal_receiver = proxy_receiver->internal();
1741 break;
1742 }
1743 }
1744 if (internal_receiver)
1745 break;
1746 }
1747 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001748 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001749 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1750 // the PeerConnection). This means that "all the stats objects representing
1751 // the selector" is an empty set. Invoking GetStatsReport() with a null
1752 // selector produces an empty stats report.
1753 stats_collector_->GetStatsReport(internal_receiver, callback);
1754}
1755
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1757 return signaling_state_;
1758}
1759
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001760PeerConnectionInterface::IceConnectionState
1761PeerConnection::ice_connection_state() {
1762 return ice_connection_state_;
1763}
1764
Alex Loiko9289eda2018-11-23 16:18:59 +00001765PeerConnectionInterface::IceConnectionState
1766PeerConnection::standardized_ice_connection_state() {
1767 return standardized_ice_connection_state_;
1768}
1769
Jonas Olsson635474e2018-10-18 15:58:17 +02001770PeerConnectionInterface::PeerConnectionState
1771PeerConnection::peer_connection_state() {
1772 return connection_state_;
1773}
1774
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001775PeerConnectionInterface::IceGatheringState
1776PeerConnection::ice_gathering_state() {
1777 return ice_gathering_state_;
1778}
1779
Yves Gerey665174f2018-06-19 15:03:05 +02001780rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001781 const std::string& label,
1782 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001783 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001784
deadbeefab9b2d12015-10-14 11:33:11 -07001785 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001786
kwibergd1fe2812016-04-27 06:47:29 -07001787 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001788 if (config) {
1789 internal_config.reset(new InternalDataChannelInit(*config));
1790 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001791 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001792 InternalCreateDataChannel(label, internal_config.get()));
1793 if (!channel.get()) {
1794 return nullptr;
1795 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001797 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1798 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001799 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001800 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001801 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001802 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001803 return DataChannelProxy::Create(signaling_thread(), channel.get());
1804}
1805
1806void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001807 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001808 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001809
nisse7ce109a2017-01-31 00:57:56 -08001810 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001811 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001812 return;
1813 }
deadbeefab9b2d12015-10-14 11:33:11 -07001814
Steve Anton8d3444d2017-10-20 15:30:51 -07001815 if (IsClosed()) {
1816 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001817 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001818 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001819 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001820 return;
1821 }
1822
zhihuang1c378ed2017-08-17 14:10:50 -07001823 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001824 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001825 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001826 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001827 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001828 return;
1829 }
1830
Steve Anton22da89f2018-01-25 13:58:07 -08001831 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1832 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1833 if (IsUnifiedPlan()) {
1834 RTCError error = HandleLegacyOfferOptions(options);
1835 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001836 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001837 return;
1838 }
1839 }
1840
zhihuang1c378ed2017-08-17 14:10:50 -07001841 cricket::MediaSessionOptions session_options;
1842 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001843 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001844}
1845
Steve Anton22da89f2018-01-25 13:58:07 -08001846RTCError PeerConnection::HandleLegacyOfferOptions(
1847 const RTCOfferAnswerOptions& options) {
1848 RTC_DCHECK(IsUnifiedPlan());
1849
1850 if (options.offer_to_receive_audio == 0) {
1851 RemoveRecvDirectionFromReceivingTransceiversOfType(
1852 cricket::MEDIA_TYPE_AUDIO);
1853 } else if (options.offer_to_receive_audio == 1) {
1854 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1855 } else if (options.offer_to_receive_audio > 1) {
1856 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1857 "offer_to_receive_audio > 1 is not supported.");
1858 }
1859
1860 if (options.offer_to_receive_video == 0) {
1861 RemoveRecvDirectionFromReceivingTransceiversOfType(
1862 cricket::MEDIA_TYPE_VIDEO);
1863 } else if (options.offer_to_receive_video == 1) {
1864 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1865 } else if (options.offer_to_receive_video > 1) {
1866 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1867 "offer_to_receive_video > 1 is not supported.");
1868 }
1869
1870 return RTCError::OK();
1871}
1872
1873void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1874 cricket::MediaType media_type) {
1875 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001876 RtpTransceiverDirection new_direction =
1877 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1878 if (new_direction != transceiver->direction()) {
1879 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1880 << " transceiver (MID="
1881 << transceiver->mid().value_or("<not set>") << ") from "
1882 << RtpTransceiverDirectionToString(
1883 transceiver->direction())
1884 << " to "
1885 << RtpTransceiverDirectionToString(new_direction)
1886 << " since CreateOffer specified offer_to_receive=0";
1887 transceiver->internal()->set_direction(new_direction);
1888 }
Steve Anton22da89f2018-01-25 13:58:07 -08001889 }
1890}
1891
1892void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1893 cricket::MediaType media_type) {
1894 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001895 RTC_LOG(LS_INFO)
1896 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1897 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001898 RtpTransceiverInit init;
1899 init.direction = RtpTransceiverDirection::kRecvOnly;
1900 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1901 }
1902}
1903
1904std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1905PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1906 std::vector<
1907 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1908 receiving_transceivers;
1909 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001910 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001911 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1912 receiving_transceivers.push_back(transceiver);
1913 }
1914 }
1915 return receiving_transceivers;
1916}
1917
htaa2a49d92016-03-04 02:51:39 -08001918void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1919 const RTCOfferAnswerOptions& options) {
1920 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001921 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001922 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001923 return;
1924 }
1925
Steve Antondffead82018-02-06 10:31:29 -08001926 if (!(signaling_state_ == kHaveRemoteOffer ||
1927 signaling_state_ == kHaveLocalPrAnswer)) {
1928 std::string error =
1929 "PeerConnection cannot create an answer in a state other than "
1930 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001931 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001932 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001933 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001934 return;
1935 }
1936
Steve Antondffead82018-02-06 10:31:29 -08001937 // The remote description should be set if we're in the right state.
1938 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001939
Steve Anton22da89f2018-01-25 13:58:07 -08001940 if (IsUnifiedPlan()) {
1941 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1942 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1943 "supported with Unified Plan semantics. Use the "
1944 "RtpTransceiver API instead.";
1945 }
1946 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1947 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1948 "supported with Unified Plan semantics. Use the "
1949 "RtpTransceiver API instead.";
1950 }
1951 }
1952
htaa2a49d92016-03-04 02:51:39 -08001953 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001954 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001955
Steve Antond25da372017-11-06 14:50:29 -08001956 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001957}
1958
1959void PeerConnection::SetLocalDescription(
1960 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001961 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001962 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001963
Steve Anton80dd7b52018-02-16 17:08:42 -08001964 // The SetLocalDescription contract is that we take ownership of the session
1965 // description regardless of the outcome, so wrap it in a unique_ptr right
1966 // away. Ideally, SetLocalDescription's signature will be changed to take the
1967 // description as a unique_ptr argument to formalize this agreement.
1968 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1969
nisse7ce109a2017-01-31 00:57:56 -08001970 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001971 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 return;
1973 }
Steve Anton8a006912017-12-04 15:25:56 -08001974
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001976 PostSetSessionDescriptionFailure(
1977 observer,
1978 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001979 return;
1980 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001981
Steve Anton80dd7b52018-02-16 17:08:42 -08001982 // If a session error has occurred the PeerConnection is in a possibly
1983 // inconsistent state so fail right away.
1984 if (session_error() != SessionError::kNone) {
1985 std::string error_message = GetSessionErrorMsg();
1986 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001987 PostSetSessionDescriptionFailure(
1988 observer,
1989 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001990 return;
1991 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001992
Steve Anton80dd7b52018-02-16 17:08:42 -08001993 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1994 if (!error.ok()) {
1995 std::string error_message = GetSetDescriptionErrorMessage(
1996 cricket::CS_LOCAL, desc->GetType(), error);
1997 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001998 PostSetSessionDescriptionFailure(
1999 observer,
2000 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002001 return;
2002 }
2003
2004 // Grab the description type before moving ownership to ApplyLocalDescription,
2005 // which may destroy it before returning.
2006 const SdpType type = desc->GetType();
2007
2008 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002009 // |desc| may be destroyed at this point.
2010
2011 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002012 // If ApplyLocalDescription fails, the PeerConnection could be in an
2013 // inconsistent state, so act conservatively here and set the session error
2014 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2015 SetSessionError(SessionError::kContent, error.message());
2016 std::string error_message =
2017 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2018 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002019 PostSetSessionDescriptionFailure(
2020 observer,
2021 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002022 return;
2023 }
Steve Anton8a006912017-12-04 15:25:56 -08002024 RTC_DCHECK(local_description());
2025
2026 PostSetSessionDescriptionSuccess(observer);
2027
Steve Antonad182762018-09-05 20:22:40 +00002028 // MaybeStartGathering needs to be called after posting
2029 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2030 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002031 transport_controller_->MaybeStartGathering();
2032
Steve Antona3a92c22017-12-07 10:27:41 -08002033 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002034 // TODO(deadbeef): We already had to hop to the network thread for
2035 // MaybeStartGathering...
2036 network_thread()->Invoke<void>(
2037 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2038 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002039 // Make UMA notes about what was agreed to.
2040 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002041 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002042 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002043}
2044
2045RTCError PeerConnection::ApplyLocalDescription(
2046 std::unique_ptr<SessionDescriptionInterface> desc) {
2047 RTC_DCHECK_RUN_ON(signaling_thread());
2048 RTC_DCHECK(desc);
2049
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002050 // Update stats here so that we have the most recent stats for tracks and
2051 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002052 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002053
Steve Antondcc3c022017-12-22 16:02:54 -08002054 // Take a reference to the old local description since it's used below to
2055 // compare against the new local description. When setting the new local
2056 // description, grab ownership of the replaced session description in case it
2057 // is the same as |old_local_description|, to keep it alive for the duration
2058 // of the method.
2059 const SessionDescriptionInterface* old_local_description =
2060 local_description();
2061 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002062 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002063 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002064 replaced_local_description = pending_local_description_
2065 ? std::move(pending_local_description_)
2066 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002067 current_local_description_ = std::move(desc);
2068 pending_local_description_ = nullptr;
2069 current_remote_description_ = std::move(pending_remote_description_);
2070 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002071 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002072 pending_local_description_ = std::move(desc);
2073 }
2074 // The session description to apply now must be accessed by
2075 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002076 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002077
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002078 if (!is_caller_) {
2079 if (remote_description()) {
2080 // Remote description was applied first, so this PC is the callee.
2081 is_caller_ = false;
2082 } else {
2083 // Local description is applied first, so this PC is the caller.
2084 is_caller_ = true;
2085 }
2086 }
2087
Zhi Huange830e682018-03-30 10:48:35 -07002088 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2089 if (!error.ok()) {
2090 return error;
2091 }
2092
Steve Antondcc3c022017-12-22 16:02:54 -08002093 if (IsUnifiedPlan()) {
2094 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002095 cricket::CS_LOCAL, *local_description(), old_local_description,
2096 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002097 if (!error.ok()) {
2098 return error;
2099 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002100 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2101 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002102 for (auto transceiver : transceivers_) {
2103 const ContentInfo* content =
2104 FindMediaSectionForTransceiver(transceiver, local_description());
2105 if (!content) {
2106 continue;
2107 }
2108 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002109 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2110 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002111 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002112 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2113 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2114 // "recvonly", process the removal of a remote track for the media
2115 // description, given transceiver, removeList, and muteTracks.
2116 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2117 (transceiver->internal()->fired_direction() &&
2118 RtpTransceiverDirectionHasRecv(
2119 *transceiver->internal()->fired_direction()))) {
2120 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2121 &removed_streams);
2122 }
2123 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2124 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002125 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002126 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002127 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002128 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002129 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002130 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002131 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002132 }
2133 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002134 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002135 }
2136 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002137 // Media channels will be created only when offer is set. These may use new
2138 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002139 if (type == SdpType::kOffer) {
2140 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2141 // description is applied. Restore back to old description.
2142 RTCError error = CreateChannels(*local_description()->description());
2143 if (!error.ok()) {
2144 return error;
2145 }
2146 }
Steve Antondcc3c022017-12-22 16:02:54 -08002147 // Remove unused channels if MediaContentDescription is rejected.
2148 RemoveUnusedChannels(local_description()->description());
2149 }
Steve Anton8a006912017-12-04 15:25:56 -08002150
Zhi Huange830e682018-03-30 10:48:35 -07002151 error = UpdateSessionState(type, cricket::CS_LOCAL,
2152 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002153 if (!error.ok()) {
2154 return error;
2155 }
Steve Antondcc3c022017-12-22 16:02:54 -08002156
Steve Anton8a006912017-12-04 15:25:56 -08002157 if (remote_description()) {
2158 // Now that we have a local description, we can push down remote candidates.
2159 UseCandidatesInSessionDescription(remote_description());
2160 }
2161
2162 pending_ice_restarts_.clear();
2163 if (session_error() != SessionError::kNone) {
2164 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2165 }
2166
deadbeefab9b2d12015-10-14 11:33:11 -07002167 // If setting the description decided our SSL role, allocate any necessary
2168 // SCTP sids.
2169 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002170 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002171 AllocateSctpSids(role);
2172 }
2173
Steve Antond3679212018-01-17 17:41:02 -08002174 if (IsUnifiedPlan()) {
2175 for (auto transceiver : transceivers_) {
2176 const ContentInfo* content =
2177 FindMediaSectionForTransceiver(transceiver, local_description());
2178 if (!content) {
2179 continue;
2180 }
Steve Anton74255ff2018-01-24 18:32:57 -08002181 const auto& streams = content->media_description()->streams();
2182 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002183 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002184 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002185 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002186 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002187 } else {
2188 // 0 is a special value meaning "this sender has no associated send
2189 // stream". Need to call this so the sender won't attempt to configure
2190 // a no longer existing stream and run into DCHECKs in the lower
2191 // layers.
2192 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002193 }
2194 }
2195 } else {
2196 // Plan B semantics.
2197
Steve Antondcc3c022017-12-22 16:02:54 -08002198 // Update state and SSRC of local MediaStreams and DataChannels based on the
2199 // local session description.
2200 const cricket::ContentInfo* audio_content =
2201 GetFirstAudioContent(local_description()->description());
2202 if (audio_content) {
2203 if (audio_content->rejected) {
2204 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2205 } else {
2206 const cricket::AudioContentDescription* audio_desc =
2207 audio_content->media_description()->as_audio();
2208 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2209 }
deadbeeffaac4972015-11-12 15:33:07 -08002210 }
deadbeefab9b2d12015-10-14 11:33:11 -07002211
Steve Antondcc3c022017-12-22 16:02:54 -08002212 const cricket::ContentInfo* video_content =
2213 GetFirstVideoContent(local_description()->description());
2214 if (video_content) {
2215 if (video_content->rejected) {
2216 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2217 } else {
2218 const cricket::VideoContentDescription* video_desc =
2219 video_content->media_description()->as_video();
2220 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2221 }
deadbeeffaac4972015-11-12 15:33:07 -08002222 }
deadbeefab9b2d12015-10-14 11:33:11 -07002223 }
2224
2225 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002226 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002227 if (data_content) {
2228 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002229 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002230 if (rtc::starts_with(data_desc->protocol().data(),
2231 cricket::kMediaProtocolRtpPrefix)) {
2232 UpdateLocalRtpDataChannels(data_desc->streams());
2233 }
2234 }
2235
Steve Anton8a006912017-12-04 15:25:56 -08002236 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002237}
2238
2239void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002240 SetSessionDescriptionObserver* observer,
2241 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002242 SetRemoteDescription(
2243 std::unique_ptr<SessionDescriptionInterface>(desc),
2244 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2245 new SetRemoteDescriptionObserverAdapter(this, observer)));
2246}
2247
2248void PeerConnection::SetRemoteDescription(
2249 std::unique_ptr<SessionDescriptionInterface> desc,
2250 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002251 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002252
nisse7ce109a2017-01-31 00:57:56 -08002253 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002254 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002255 return;
2256 }
Steve Anton8a006912017-12-04 15:25:56 -08002257
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002258 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002259 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002260 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002261 return;
2262 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002263
Steve Anton80dd7b52018-02-16 17:08:42 -08002264 // If a session error has occurred the PeerConnection is in a possibly
2265 // inconsistent state so fail right away.
2266 if (session_error() != SessionError::kNone) {
2267 std::string error_message = GetSessionErrorMsg();
2268 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2269 observer->OnSetRemoteDescriptionComplete(
2270 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2271 return;
2272 }
Steve Anton71439a62018-02-15 11:53:06 -08002273
Steve Antonba42e992018-04-09 14:10:01 -07002274 if (desc->GetType() == SdpType::kOffer) {
2275 // Report to UMA the format of the received offer.
2276 ReportSdpFormatReceived(*desc);
2277 }
2278
Steve Anton80dd7b52018-02-16 17:08:42 -08002279 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002280 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002281 std::string error_message = GetSetDescriptionErrorMessage(
2282 cricket::CS_REMOTE, desc->GetType(), error);
2283 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002284 observer->OnSetRemoteDescriptionComplete(
2285 RTCError(error.type(), std::move(error_message)));
2286 return;
2287 }
Steve Anton71439a62018-02-15 11:53:06 -08002288
Steve Anton80dd7b52018-02-16 17:08:42 -08002289 // Grab the description type before moving ownership to
2290 // ApplyRemoteDescription, which may destroy it before returning.
2291 const SdpType type = desc->GetType();
2292
2293 error = ApplyRemoteDescription(std::move(desc));
2294 // |desc| may be destroyed at this point.
2295
2296 if (!error.ok()) {
2297 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2298 // inconsistent state, so act conservatively here and set the session error
2299 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2300 SetSessionError(SessionError::kContent, error.message());
2301 std::string error_message =
2302 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2303 RTC_LOG(LS_ERROR) << error_message;
2304 observer->OnSetRemoteDescriptionComplete(
2305 RTCError(error.type(), std::move(error_message)));
2306 return;
2307 }
2308 RTC_DCHECK(remote_description());
2309
2310 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002311 // TODO(deadbeef): We already had to hop to the network thread for
2312 // MaybeStartGathering...
2313 network_thread()->Invoke<void>(
2314 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2315 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002316 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002317 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002318 }
2319
2320 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002321 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002322}
2323
2324RTCError PeerConnection::ApplyRemoteDescription(
2325 std::unique_ptr<SessionDescriptionInterface> desc) {
2326 RTC_DCHECK_RUN_ON(signaling_thread());
2327 RTC_DCHECK(desc);
2328
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002329 // Update stats here so that we have the most recent stats for tracks and
2330 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002331 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002332
Steve Antondcc3c022017-12-22 16:02:54 -08002333 // Take a reference to the old remote description since it's used below to
2334 // compare against the new remote description. When setting the new remote
2335 // description, grab ownership of the replaced session description in case it
2336 // is the same as |old_remote_description|, to keep it alive for the duration
2337 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002338 const SessionDescriptionInterface* old_remote_description =
2339 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002340 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002341 SdpType type = desc->GetType();
2342 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002343 replaced_remote_description = pending_remote_description_
2344 ? std::move(pending_remote_description_)
2345 : std::move(current_remote_description_);
2346 current_remote_description_ = std::move(desc);
2347 pending_remote_description_ = nullptr;
2348 current_local_description_ = std::move(pending_local_description_);
2349 } else {
2350 replaced_remote_description = std::move(pending_remote_description_);
2351 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002352 }
Steve Anton8a006912017-12-04 15:25:56 -08002353 // The session description to apply now must be accessed by
2354 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002355 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002356
Zhi Huange830e682018-03-30 10:48:35 -07002357 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2358 if (!error.ok()) {
2359 return error;
2360 }
Steve Anton8a006912017-12-04 15:25:56 -08002361 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002362 if (IsUnifiedPlan()) {
2363 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002364 cricket::CS_REMOTE, *remote_description(), local_description(),
2365 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002366 if (!error.ok()) {
2367 return error;
2368 }
Steve Antondcc3c022017-12-22 16:02:54 -08002369 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002370 // Media channels will be created only when offer is set. These may use new
2371 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002372 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002373 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002374 // description is applied. Restore back to old description.
2375 RTCError error = CreateChannels(*remote_description()->description());
2376 if (!error.ok()) {
2377 return error;
2378 }
2379 }
Steve Antondcc3c022017-12-22 16:02:54 -08002380 // Remove unused channels if MediaContentDescription is rejected.
2381 RemoveUnusedChannels(remote_description()->description());
2382 }
Steve Anton8a006912017-12-04 15:25:56 -08002383
Zhi Huange830e682018-03-30 10:48:35 -07002384 // NOTE: Candidates allocation will be initiated only when
2385 // SetLocalDescription is called.
2386 error = UpdateSessionState(type, cricket::CS_REMOTE,
2387 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002388 if (!error.ok()) {
2389 return error;
2390 }
2391
2392 if (local_description() &&
2393 !UseCandidatesInSessionDescription(remote_description())) {
2394 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2395 }
2396
2397 if (old_remote_description) {
2398 for (const cricket::ContentInfo& content :
2399 old_remote_description->description()->contents()) {
2400 // Check if this new SessionDescription contains new ICE ufrag and
2401 // password that indicates the remote peer requests an ICE restart.
2402 // TODO(deadbeef): When we start storing both the current and pending
2403 // remote description, this should reset pending_ice_restarts and compare
2404 // against the current description.
2405 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2406 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002407 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002408 pending_ice_restarts_.insert(content.name);
2409 }
2410 } else {
2411 // We retain all received candidates only if ICE is not restarted.
2412 // When ICE is restarted, all previous candidates belong to an old
2413 // generation and should not be kept.
2414 // TODO(deadbeef): This goes against the W3C spec which says the remote
2415 // description should only contain candidates from the last set remote
2416 // description plus any candidates added since then. We should remove
2417 // this once we're sure it won't break anything.
2418 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2419 old_remote_description, content.name, mutable_remote_description());
2420 }
2421 }
2422 }
2423
2424 if (session_error() != SessionError::kNone) {
2425 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2426 }
2427
2428 // Set the the ICE connection state to connecting since the connection may
2429 // become writable with peer reflexive candidates before any remote candidate
2430 // is signaled.
2431 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2432 // is to have a new signal the indicates a change in checking state from the
2433 // transport and expose a new checking() member from transport that can be
2434 // read to determine the current checking state. The existing SignalConnecting
2435 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002436 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002437 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002438 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2439 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2440 }
2441
deadbeefab9b2d12015-10-14 11:33:11 -07002442 // If setting the description decided our SSL role, allocate any necessary
2443 // SCTP sids.
2444 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002445 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002446 AllocateSctpSids(role);
2447 }
2448
Steve Antondcc3c022017-12-22 16:02:54 -08002449 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002450 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002451 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002452 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002453 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002454 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002455 for (auto transceiver : transceivers_) {
2456 const ContentInfo* content =
2457 FindMediaSectionForTransceiver(transceiver, remote_description());
2458 if (!content) {
2459 continue;
2460 }
2461 const MediaContentDescription* media_desc = content->media_description();
2462 RtpTransceiverDirection local_direction =
2463 RtpTransceiverDirectionReversed(media_desc->direction());
2464 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2465 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2466 // transceiver's current direction is neither sendrecv nor recvonly,
2467 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002468 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002469 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002470 // The remote description has signaled the stream IDs.
2471 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002472 }
Steve Antondcc3c022017-12-22 16:02:54 -08002473 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002474 (!transceiver->fired_direction() ||
2475 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002476 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002477 << content->name << " (added to "
2478 << GetStreamIdsString(stream_ids) << ").";
2479
2480 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2481 for (const std::string& stream_id : stream_ids) {
2482 rtc::scoped_refptr<MediaStreamInterface> stream =
2483 remote_streams_->find(stream_id);
2484 if (!stream) {
2485 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2486 MediaStream::Create(stream_id));
2487 remote_streams_->AddStream(stream);
2488 added_streams.push_back(stream);
2489 }
2490 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002491 }
Steve Anton3172c032018-05-03 15:30:18 -07002492 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002493 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2494 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002495 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002496 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002497 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002498 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2499 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2500 // removal of a remote track for the media description, given transceiver,
2501 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002502 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002503 (transceiver->fired_direction() &&
2504 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2505 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2506 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002507 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002508 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2509 transceiver->internal()->set_fired_direction(local_direction);
2510 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2511 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002512 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002513 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2514 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002515 transceiver->internal()->set_current_direction(local_direction);
2516 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002517 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2518 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002519 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002520 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2521 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002522 transceiver->Stop();
2523 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002524 if (!content->rejected &&
2525 RtpTransceiverDirectionHasRecv(local_direction)) {
2526 // Set ssrc to 0 in the case of an unsignalled ssrc.
2527 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002528 if (!media_desc->streams().empty() &&
2529 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002530 ssrc = media_desc->streams()[0].first_ssrc();
2531 }
2532 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002533 }
Steve Antondcc3c022017-12-22 16:02:54 -08002534 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002535 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002536 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002537 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002538 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002539 observer->OnTrack(transceiver);
2540 observer->OnAddTrack(transceiver->receiver(),
2541 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002542 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002543 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002544 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002545 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002546 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002547 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002548 }
2549 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002550 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002551 }
Steve Antondcc3c022017-12-22 16:02:54 -08002552 }
2553
Henrik Boströmfdb92012017-11-09 19:55:44 +01002554 const cricket::ContentInfo* audio_content =
2555 GetFirstAudioContent(remote_description()->description());
2556 const cricket::ContentInfo* video_content =
2557 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002558 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002559 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002560 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002561 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002562 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002563 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002564
2565 // Check if the descriptions include streams, just in case the peer supports
2566 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002567 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002568 (audio_desc && !audio_desc->streams().empty()) ||
2569 (video_desc && !video_desc->streams().empty())) {
2570 remote_peer_supports_msid_ = true;
2571 }
deadbeefab9b2d12015-10-14 11:33:11 -07002572
2573 // We wait to signal new streams until we finish processing the description,
2574 // since only at that point will new streams have all their tracks.
2575 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2576
Steve Antondcc3c022017-12-22 16:02:54 -08002577 if (!IsUnifiedPlan()) {
2578 // TODO(steveanton): When removing RTP senders/receivers in response to a
2579 // rejected media section, there is some cleanup logic that expects the
2580 // voice/ video channel to still be set. But in this method the voice/video
2581 // channel would have been destroyed by the SetRemoteDescription caller
2582 // above so the cleanup that relies on them fails to run. The RemoveSenders
2583 // calls should be moved to right before the DestroyChannel calls to fix
2584 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002585
Steve Antondcc3c022017-12-22 16:02:54 -08002586 // Find all audio rtp streams and create corresponding remote AudioTracks
2587 // and MediaStreams.
2588 if (audio_content) {
2589 if (audio_content->rejected) {
2590 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2591 } else {
2592 bool default_audio_track_needed =
2593 !remote_peer_supports_msid_ &&
2594 RtpTransceiverDirectionHasSend(audio_desc->direction());
2595 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2596 default_audio_track_needed, audio_desc->type(),
2597 new_streams);
2598 }
deadbeeffaac4972015-11-12 15:33:07 -08002599 }
deadbeefab9b2d12015-10-14 11:33:11 -07002600
Steve Antondcc3c022017-12-22 16:02:54 -08002601 // Find all video rtp streams and create corresponding remote VideoTracks
2602 // and MediaStreams.
2603 if (video_content) {
2604 if (video_content->rejected) {
2605 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2606 } else {
2607 bool default_video_track_needed =
2608 !remote_peer_supports_msid_ &&
2609 RtpTransceiverDirectionHasSend(video_desc->direction());
2610 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2611 default_video_track_needed, video_desc->type(),
2612 new_streams);
2613 }
deadbeeffaac4972015-11-12 15:33:07 -08002614 }
deadbeefab9b2d12015-10-14 11:33:11 -07002615
Steve Antondcc3c022017-12-22 16:02:54 -08002616 // Update the DataChannels with the information from the remote peer.
2617 if (data_desc) {
2618 if (rtc::starts_with(data_desc->protocol().data(),
2619 cricket::kMediaProtocolRtpPrefix)) {
2620 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2621 }
deadbeefab9b2d12015-10-14 11:33:11 -07002622 }
deadbeefab9b2d12015-10-14 11:33:11 -07002623
Steve Antondcc3c022017-12-22 16:02:54 -08002624 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002625 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002626 for (size_t i = 0; i < new_streams->count(); ++i) {
2627 MediaStreamInterface* new_stream = new_streams->at(i);
2628 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002629 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002630 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2631 }
deadbeefab9b2d12015-10-14 11:33:11 -07002632
Steve Antondcc3c022017-12-22 16:02:54 -08002633 UpdateEndedRemoteMediaStreams();
2634 }
deadbeefab9b2d12015-10-14 11:33:11 -07002635
Steve Anton8a006912017-12-04 15:25:56 -08002636 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002637}
2638
Steve Anton0f5400a2018-07-17 14:25:36 -07002639void PeerConnection::ProcessRemovalOfRemoteTrack(
2640 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2641 transceiver,
2642 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2643 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2644 RTC_DCHECK(transceiver->mid());
2645 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2646 << *transceiver->mid();
2647 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2648 transceiver->internal()->receiver_internal()->streams();
2649 // This will remove the remote track from the streams.
2650 transceiver->internal()->receiver_internal()->set_stream_ids({});
2651 remove_list->push_back(transceiver);
2652 // Remove any streams that no longer have tracks.
2653 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2654 // of streams, see if the stream was removed by checking if this was the
2655 // last receiver with that stream ID.
2656 for (auto stream : media_streams) {
2657 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2658 remote_streams_->RemoveStream(stream);
2659 removed_streams->push_back(stream);
2660 }
2661 }
2662}
2663
Steve Antondcc3c022017-12-22 16:02:54 -08002664RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2665 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002666 const SessionDescriptionInterface& new_session,
2667 const SessionDescriptionInterface* old_local_description,
2668 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002669 RTC_DCHECK(IsUnifiedPlan());
2670
Steve Anton7464fca2018-01-19 11:10:37 -08002671 const cricket::ContentGroup* bundle_group = nullptr;
2672 if (new_session.GetType() == SdpType::kOffer) {
2673 auto bundle_group_or_error =
2674 GetEarlyBundleGroup(*new_session.description());
2675 if (!bundle_group_or_error.ok()) {
2676 return bundle_group_or_error.MoveError();
2677 }
2678 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002679 }
Steve Antondcc3c022017-12-22 16:02:54 -08002680
Steve Antondcc3c022017-12-22 16:02:54 -08002681 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002682 for (size_t i = 0; i < new_contents.size(); ++i) {
2683 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002684 cricket::MediaType media_type = new_content.media_description()->type();
2685 seen_mids_.insert(new_content.name);
2686 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2687 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002688 const cricket::ContentInfo* old_local_content = nullptr;
2689 if (old_local_description &&
2690 i < old_local_description->description()->contents().size()) {
2691 old_local_content =
2692 &old_local_description->description()->contents()[i];
2693 }
2694 const cricket::ContentInfo* old_remote_content = nullptr;
2695 if (old_remote_description &&
2696 i < old_remote_description->description()->contents().size()) {
2697 old_remote_content =
2698 &old_remote_description->description()->contents()[i];
2699 }
Steve Antondcc3c022017-12-22 16:02:54 -08002700 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002701 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2702 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002703 if (!transceiver_or_error.ok()) {
2704 return transceiver_or_error.MoveError();
2705 }
2706 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002707 RTCError error =
2708 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2709 if (!error.ok()) {
2710 return error;
2711 }
2712 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002713 if (GetDataMid() && new_content.name != *GetDataMid()) {
2714 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002715 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2716 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002717 continue;
2718 }
2719 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2720 if (!error.ok()) {
2721 return error;
2722 }
Steve Antondcc3c022017-12-22 16:02:54 -08002723 } else {
2724 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2725 "Unknown section type.");
2726 }
2727 }
2728
2729 return RTCError::OK();
2730}
2731
2732RTCError PeerConnection::UpdateTransceiverChannel(
2733 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2734 transceiver,
2735 const cricket::ContentInfo& content,
2736 const cricket::ContentGroup* bundle_group) {
2737 RTC_DCHECK(IsUnifiedPlan());
2738 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002739 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002740 if (content.rejected) {
2741 if (channel) {
2742 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002743 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002744 }
2745 } else {
2746 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002747 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002748 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002749 } else {
Steve Anton69470252018-02-09 11:43:08 -08002750 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002751 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002752 }
2753 if (!channel) {
2754 LOG_AND_RETURN_ERROR(
2755 RTCErrorType::INTERNAL_ERROR,
2756 "Failed to create channel for mid=" + content.name);
2757 }
2758 transceiver->internal()->SetChannel(channel);
2759 }
2760 }
2761 return RTCError::OK();
2762}
2763
Steve Antonfa2260d2017-12-28 16:38:23 -08002764RTCError PeerConnection::UpdateDataChannel(
2765 cricket::ContentSource source,
2766 const cricket::ContentInfo& content,
2767 const cricket::ContentGroup* bundle_group) {
2768 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002769 // If data channels are disabled, ignore this media section. CreateAnswer
2770 // will take care of rejecting it.
2771 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002772 }
2773 if (content.rejected) {
2774 DestroyDataChannel();
2775 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002776 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002777 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002778 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2779 "Failed to create data channel.");
2780 }
2781 }
2782 if (source == cricket::CS_REMOTE) {
2783 const MediaContentDescription* data_desc = content.media_description();
2784 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2785 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2786 }
2787 }
2788 }
2789 return RTCError::OK();
2790}
2791
Steve Antondcc3c022017-12-22 16:02:54 -08002792RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2793PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002794 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002795 size_t mline_index,
2796 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002797 const ContentInfo* old_local_content,
2798 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002799 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002800 // If this is an offer then the m= section might be recycled. If the m=
2801 // section is being recycled (defined as: rejected in the current local or
2802 // remote description and not rejected in new description), dissociate the
2803 // currently associated RtpTransceiver by setting its mid property to null,
2804 // and discard the mapping between the transceiver and its m= section index.
2805 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2806 old_remote_content)) {
2807 // We want to dissociate the transceiver that has the rejected mid.
2808 const std::string& old_mid =
2809 (old_local_content && old_local_content->rejected)
2810 ? old_local_content->name
2811 : old_remote_content->name;
2812 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002813 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002814 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2815 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002816 old_transceiver->internal()->set_mid(absl::nullopt);
2817 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002818 }
2819 }
2820 const MediaContentDescription* media_desc = content.media_description();
2821 auto transceiver = GetAssociatedTransceiver(content.name);
2822 if (source == cricket::CS_LOCAL) {
2823 // Find the RtpTransceiver that corresponds to this m= section, using the
2824 // mapping between transceivers and m= section indices established when
2825 // creating the offer.
2826 if (!transceiver) {
2827 transceiver = GetTransceiverByMLineIndex(mline_index);
2828 }
2829 if (!transceiver) {
2830 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2831 "Unknown transceiver");
2832 }
2833 } else {
2834 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2835 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2836 // of the same type...
2837 if (!transceiver &&
2838 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2839 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2840 }
2841 // If no RtpTransceiver was found in the previous step, create one with a
2842 // recvonly direction.
2843 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002844 RTC_LOG(LS_INFO) << "Adding "
2845 << cricket::MediaTypeToString(media_desc->type())
2846 << " transceiver for MID=" << content.name
2847 << " at i=" << mline_index
2848 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002849 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002850 auto sender =
2851 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002852 std::string receiver_id;
2853 if (!media_desc->streams().empty()) {
2854 receiver_id = media_desc->streams()[0].id;
2855 } else {
2856 receiver_id = rtc::CreateRandomUuid();
2857 }
2858 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002859 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002860 transceiver->internal()->set_direction(
2861 RtpTransceiverDirection::kRecvOnly);
2862 }
2863 }
2864 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002865 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002866 LOG_AND_RETURN_ERROR(
2867 RTCErrorType::INVALID_PARAMETER,
2868 "Transceiver type does not match media description type.");
2869 }
2870 // Associate the found or created RtpTransceiver with the m= section by
2871 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2872 // section, and establish a mapping between the transceiver and the index of
2873 // the m= section.
2874 transceiver->internal()->set_mid(content.name);
2875 transceiver->internal()->set_mline_index(mline_index);
2876 return std::move(transceiver);
2877}
2878
2879rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2880PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2881 RTC_DCHECK(IsUnifiedPlan());
2882 for (auto transceiver : transceivers_) {
2883 if (transceiver->mid() == mid) {
2884 return transceiver;
2885 }
2886 }
2887 return nullptr;
2888}
2889
2890rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2891PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2892 RTC_DCHECK(IsUnifiedPlan());
2893 for (auto transceiver : transceivers_) {
2894 if (transceiver->internal()->mline_index() == mline_index) {
2895 return transceiver;
2896 }
2897 }
2898 return nullptr;
2899}
2900
2901rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2902PeerConnection::FindAvailableTransceiverToReceive(
2903 cricket::MediaType media_type) const {
2904 RTC_DCHECK(IsUnifiedPlan());
2905 // From JSEP section 5.10 (Applying a Remote Description):
2906 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2907 // the same type that were added to the PeerConnection by addTrack and are not
2908 // associated with any m= section and are not stopped, find the first such
2909 // RtpTransceiver.
2910 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002911 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002912 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2913 !transceiver->stopped()) {
2914 return transceiver;
2915 }
2916 }
2917 return nullptr;
2918}
2919
Steve Antoned10bd92017-12-05 10:52:59 -08002920const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2921 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2922 transceiver,
2923 const SessionDescriptionInterface* sdesc) const {
2924 RTC_DCHECK(transceiver);
2925 RTC_DCHECK(sdesc);
2926 if (IsUnifiedPlan()) {
2927 if (!transceiver->internal()->mid()) {
2928 // This transceiver is not associated with a media section yet.
2929 return nullptr;
2930 }
2931 return sdesc->description()->GetContentByName(
2932 *transceiver->internal()->mid());
2933 } else {
2934 // Plan B only allows at most one audio and one video section, so use the
2935 // first media section of that type.
2936 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002937 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002938 }
2939}
2940
deadbeef46c73892016-11-16 19:42:04 -08002941PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2942 return configuration_;
2943}
2944
deadbeef293e9262017-01-11 12:28:30 -08002945bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2946 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002947 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002948 if (IsClosed()) {
2949 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2950 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2951 }
2952
Qingsi Wanga2d60672018-04-11 16:57:45 -07002953 // According to JSEP, after setLocalDescription, changing the candidate pool
2954 // size is not allowed, and changing the set of ICE servers will not result
2955 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002956 if (local_description() && configuration.ice_candidate_pool_size !=
2957 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002958 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2959 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002960 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002961 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002962
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002963 if (local_description() &&
2964 configuration.use_media_transport != configuration_.use_media_transport) {
2965 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2966 "SetLocalDescription.";
2967 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2968 }
2969
2970 if (remote_description() &&
2971 configuration.use_media_transport != configuration_.use_media_transport) {
2972 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2973 "SetRemoteDescription.";
2974 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2975 }
2976
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002977 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002978 configuration.use_media_transport_for_data_channels !=
2979 configuration_.use_media_transport_for_data_channels) {
2980 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2981 "after calling SetLocalDescription.";
2982 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2983 }
2984
2985 if (remote_description() &&
2986 configuration.use_media_transport_for_data_channels !=
2987 configuration_.use_media_transport_for_data_channels) {
2988 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2989 "after calling SetRemoteDescription.";
2990 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2991 }
2992
2993 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002994 configuration.crypto_options != configuration_.crypto_options) {
2995 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2996 "SetLocalDescription.";
2997 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2998 }
2999
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003000 if (configuration.use_media_transport_for_data_channels ||
3001 configuration.use_media_transport) {
3002 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3003 << "Media transport requires MaxBundle policy.";
3004 }
3005
deadbeef293e9262017-01-11 12:28:30 -08003006 // The simplest (and most future-compatible) way to tell if the config was
3007 // modified in an invalid way is to copy each property we do support
3008 // modifying, then use operator==. There are far more properties we don't
3009 // support modifying than those we do, and more could be added.
3010 RTCConfiguration modified_config = configuration_;
3011 modified_config.servers = configuration.servers;
3012 modified_config.type = configuration.type;
3013 modified_config.ice_candidate_pool_size =
3014 configuration.ice_candidate_pool_size;
3015 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003016 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003017 modified_config.ice_check_interval_strong_connectivity =
3018 configuration.ice_check_interval_strong_connectivity;
3019 modified_config.ice_check_interval_weak_connectivity =
3020 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003021 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3022 modified_config.ice_unwritable_min_checks =
3023 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003024 modified_config.stun_candidate_keepalive_interval =
3025 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003026 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003027 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003028 modified_config.active_reset_srtp_params =
3029 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003030 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003031 modified_config.use_media_transport_for_data_channels =
3032 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003033 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003034 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003035 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3036 }
3037
Steve Anton038834f2017-07-14 15:59:59 -07003038 // Validate the modified configuration.
3039 RTCError validate_error = ValidateConfiguration(modified_config);
3040 if (!validate_error.ok()) {
3041 return SafeSetError(std::move(validate_error), error);
3042 }
3043
deadbeef293e9262017-01-11 12:28:30 -08003044 // Note that this isn't possible through chromium, since it's an unsigned
3045 // short in WebIDL.
3046 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003047 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003048 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3049 }
3050
3051 // Parse ICE servers before hopping to network thread.
3052 cricket::ServerAddresses stun_servers;
3053 std::vector<cricket::RelayServerConfig> turn_servers;
3054 RTCErrorType parse_error =
3055 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3056 if (parse_error != RTCErrorType::NONE) {
3057 return SafeSetError(parse_error, error);
3058 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003059 // Note if STUN or TURN servers were supplied.
3060 if (!stun_servers.empty()) {
3061 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3062 }
3063 if (!turn_servers.empty()) {
3064 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3065 }
deadbeef293e9262017-01-11 12:28:30 -08003066
3067 // In theory this shouldn't fail.
3068 if (!network_thread()->Invoke<bool>(
3069 RTC_FROM_HERE,
3070 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3071 stun_servers, turn_servers, modified_config.type,
3072 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003073 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003074 modified_config.turn_customizer,
3075 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003076 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003077 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3078 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003079
deadbeefd1a38b52016-12-10 13:15:33 -08003080 // As described in JSEP, calling setConfiguration with new ICE servers or
3081 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3082 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003083 if (modified_config.servers != configuration_.servers ||
3084 modified_config.type != configuration_.type ||
3085 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003086 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003087 }
skvladd1f5fda2017-02-03 16:54:05 -08003088
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003089 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003090 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003091 modified_config.use_media_transport ||
3092 modified_config.use_media_transport_for_data_channels
3093 ? factory_->media_transport_factory()
3094 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003095
Zhi Huangb57e1692018-06-12 11:41:11 -07003096 if (configuration_.active_reset_srtp_params !=
3097 modified_config.active_reset_srtp_params) {
3098 transport_controller_->SetActiveResetSrtpParams(
3099 modified_config.active_reset_srtp_params);
3100 }
3101
deadbeef293e9262017-01-11 12:28:30 -08003102 configuration_ = modified_config;
3103 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003104}
3105
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003106bool PeerConnection::AddIceCandidate(
3107 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003108 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003109 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003110 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003111 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003112 return false;
3113 }
Steve Antond25da372017-11-06 14:50:29 -08003114
3115 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003116 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003117 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003118 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003119 return false;
3120 }
3121
3122 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003123 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003124 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003125 return false;
3126 }
3127
3128 bool valid = false;
3129 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3130 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003131 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003132 return false;
3133 }
3134
3135 // Add this candidate to the remote session description.
3136 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003137 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003138 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003139 return false;
3140 }
3141
3142 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003143 bool result = UseCandidate(ice_candidate);
3144 if (result) {
3145 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3146 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3147 } else {
3148 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3149 }
3150 return result;
Steve Antond25da372017-11-06 14:50:29 -08003151 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003152 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003153 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003154 return true;
3155 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003156}
3157
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003158bool PeerConnection::RemoveIceCandidates(
3159 const std::vector<cricket::Candidate>& candidates) {
3160 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003161 if (IsClosed()) {
3162 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3163 return false;
3164 }
3165
Steve Antond25da372017-11-06 14:50:29 -08003166 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003167 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3168 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003169 return false;
3170 }
3171
3172 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003173 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003174 return false;
3175 }
3176
3177 size_t number_removed =
3178 mutable_remote_description()->RemoveCandidates(candidates);
3179 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003180 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003181 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003182 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003183 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003184 }
3185
3186 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003187 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3188 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003189 RTC_LOG(LS_ERROR)
3190 << "RemoveIceCandidates: Error when removing remote candidates: "
3191 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003192 }
3193 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003194}
3195
Niels Möller0c4f7be2018-05-07 14:01:37 +02003196RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003197 if (!worker_thread()->IsCurrent()) {
3198 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003199 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003200 }
3201
Niels Möller0c4f7be2018-05-07 14:01:37 +02003202 const bool has_min = bitrate.min_bitrate_bps.has_value();
3203 const bool has_start = bitrate.start_bitrate_bps.has_value();
3204 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003205 if (has_min && *bitrate.min_bitrate_bps < 0) {
3206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3207 "min_bitrate_bps <= 0");
3208 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003209 if (has_start) {
3210 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003211 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003212 "start_bitrate_bps < min_bitrate_bps");
3213 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3215 "curent_bitrate_bps < 0");
3216 }
3217 }
3218 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003219 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003221 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003222 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3223 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3224 "max_bitrate_bps < min_bitrate_bps");
3225 } else if (*bitrate.max_bitrate_bps < 0) {
3226 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3227 "max_bitrate_bps < 0");
3228 }
3229 }
3230
zstein4b979802017-06-02 14:37:37 -07003231 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003232 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003233
3234 return RTCError::OK();
3235}
3236
Alex Narest78609d52017-10-20 10:37:47 +02003237void PeerConnection::SetBitrateAllocationStrategy(
3238 std::unique_ptr<rtc::BitrateAllocationStrategy>
3239 bitrate_allocation_strategy) {
3240 rtc::Thread* worker_thread = factory_->worker_thread();
3241 if (!worker_thread->IsCurrent()) {
3242 rtc::BitrateAllocationStrategy* strategy_raw =
3243 bitrate_allocation_strategy.release();
3244 auto functor = [this, strategy_raw]() {
3245 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003246 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003247 };
3248 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3249 return;
3250 }
3251 RTC_DCHECK(call_.get());
3252 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3253}
3254
henrika5f6bf242017-11-01 11:06:56 +01003255void PeerConnection::SetAudioPlayout(bool playout) {
3256 if (!worker_thread()->IsCurrent()) {
3257 worker_thread()->Invoke<void>(
3258 RTC_FROM_HERE,
3259 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3260 return;
3261 }
3262 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003263 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003264 audio_state->SetPlayout(playout);
3265}
3266
3267void PeerConnection::SetAudioRecording(bool recording) {
3268 if (!worker_thread()->IsCurrent()) {
3269 worker_thread()->Invoke<void>(
3270 RTC_FROM_HERE,
3271 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3272 return;
3273 }
3274 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003275 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003276 audio_state->SetRecording(recording);
3277}
3278
Steve Anton8c0f7a72017-10-03 10:03:10 -07003279std::unique_ptr<rtc::SSLCertificate>
3280PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003281 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3282 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003283 return nullptr;
3284 }
Steve Antonf25303e2018-10-16 15:23:31 -07003285 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003286}
3287
Zhi Huang70b820f2018-01-27 14:16:15 -08003288std::unique_ptr<rtc::SSLCertChain>
3289PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003290 auto audio_transceiver = GetFirstAudioTransceiver();
3291 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003292 return nullptr;
3293 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003294 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003295 audio_transceiver->internal()->channel()->transport_name());
3296}
3297
3298rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3299PeerConnection::GetFirstAudioTransceiver() const {
3300 for (auto transceiver : transceivers_) {
3301 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3302 return transceiver;
3303 }
3304 }
3305 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003306}
3307
ivoc14d5dbe2016-07-04 07:06:55 -07003308bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3309 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003310 // TODO(eladalon): It would be better to not allow negative values into PC.
3311 const size_t max_size = (max_size_bytes < 0)
3312 ? RtcEventLog::kUnlimitedOutput
3313 : rtc::saturated_cast<size_t>(max_size_bytes);
3314 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003315 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003316 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003317}
3318
Bjorn Tereliusde939432017-11-20 17:38:14 +01003319bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3320 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003321 // TODO(eladalon): In C++14, this can be done with a lambda.
3322 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003323 bool operator()() {
3324 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3325 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003326 PeerConnection* const pc;
3327 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003328 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003329 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003330 return worker_thread()->Invoke<bool>(
3331 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003332}
3333
3334void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003335 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003336 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3337}
3338
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003340 return pending_local_description_ ? pending_local_description_.get()
3341 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003342}
3343
3344const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003345 return pending_remote_description_ ? pending_remote_description_.get()
3346 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003347}
3348
deadbeeffe4a8a42016-12-20 17:56:17 -08003349const SessionDescriptionInterface* PeerConnection::current_local_description()
3350 const {
Steve Anton75737c02017-11-06 10:37:17 -08003351 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003352}
3353
3354const SessionDescriptionInterface* PeerConnection::current_remote_description()
3355 const {
Steve Anton75737c02017-11-06 10:37:17 -08003356 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003357}
3358
3359const SessionDescriptionInterface* PeerConnection::pending_local_description()
3360 const {
Steve Anton75737c02017-11-06 10:37:17 -08003361 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003362}
3363
3364const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3365 const {
Steve Anton75737c02017-11-06 10:37:17 -08003366 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003367}
3368
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003369void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003370 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003371 // Update stats here so that we have the most recent stats for tracks and
3372 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003373 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003374
Steve Anton75737c02017-11-06 10:37:17 -08003375 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003376 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003377
Steve Anton8af21862017-12-15 11:20:13 -08003378 for (auto transceiver : transceivers_) {
3379 transceiver->Stop();
3380 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003381
3382 // Ensure that all asynchronous stats requests are completed before destroying
3383 // the transport controller below.
3384 if (stats_collector_) {
3385 stats_collector_->WaitForPendingRequest();
3386 }
3387
3388 // Don't destroy BaseChannels until after stats has been cleaned up so that
3389 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003390 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003391
Qingsi Wang93a84392018-01-30 17:13:09 -08003392 // The event log is used in the transport controller, which must be outlived
3393 // by the former. CreateOffer by the peer connection is implemented
3394 // asynchronously and if the peer connection is closed without resetting the
3395 // WebRTC session description factory, the session description factory would
3396 // call the transport controller.
3397 webrtc_session_desc_factory_.reset();
3398 transport_controller_.reset();
3399
deadbeef42a42632017-03-10 15:18:00 -08003400 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003401 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3402 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003403
Steve Anton978b8762017-09-29 12:15:02 -07003404 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003405 call_.reset();
3406 // The event log must outlive call (and any other object that uses it).
3407 event_log_.reset();
3408 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003409 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003410 // The .h file says that observer can be discarded after close() returns.
3411 // Make sure this is true.
3412 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003413}
3414
Steve Antonad182762018-09-05 20:22:40 +00003415void PeerConnection::OnMessage(rtc::Message* msg) {
3416 switch (msg->message_id) {
3417 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3418 SetSessionDescriptionMsg* param =
3419 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3420 param->observer->OnSuccess();
3421 delete param;
3422 break;
3423 }
3424 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3425 SetSessionDescriptionMsg* param =
3426 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3427 param->observer->OnFailure(std::move(param->error));
3428 delete param;
3429 break;
3430 }
3431 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3432 CreateSessionDescriptionMsg* param =
3433 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3434 param->observer->OnFailure(std::move(param->error));
3435 delete param;
3436 break;
3437 }
3438 case MSG_GETSTATS: {
3439 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3440 StatsReports reports;
3441 stats_->GetStats(param->track, &reports);
3442 param->observer->OnComplete(reports);
3443 delete param;
3444 break;
3445 }
3446 case MSG_FREE_DATACHANNELS: {
3447 sctp_data_channels_to_free_.clear();
3448 break;
3449 }
3450 case MSG_REPORT_USAGE_PATTERN: {
3451 ReportUsagePattern();
3452 break;
3453 }
3454 default:
3455 RTC_NOTREACHED() << "Not implemented";
3456 break;
3457 }
3458}
3459
Steve Antonafb0bb72018-02-20 11:35:37 -08003460cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3461 RTC_DCHECK(!IsUnifiedPlan());
3462 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3463 GetAudioTransceiver()->internal()->channel());
3464 if (voice_channel) {
3465 return voice_channel->media_channel();
3466 } else {
3467 return nullptr;
3468 }
3469}
3470
3471cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3472 RTC_DCHECK(!IsUnifiedPlan());
3473 auto* video_channel = static_cast<cricket::VideoChannel*>(
3474 GetVideoTransceiver()->internal()->channel());
3475 if (video_channel) {
3476 return video_channel->media_channel();
3477 } else {
3478 return nullptr;
3479 }
3480}
3481
Steve Anton4171afb2017-11-20 10:20:22 -08003482void PeerConnection::CreateAudioReceiver(
3483 MediaStreamInterface* stream,
3484 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003485 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3486 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003487 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3488 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003489 auto* audio_receiver = new AudioRtpReceiver(
3490 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003491 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003492 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3493 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3494 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003495 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003496 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003497 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003498}
3499
Steve Anton4171afb2017-11-20 10:20:22 -08003500void PeerConnection::CreateVideoReceiver(
3501 MediaStreamInterface* stream,
3502 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003503 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3504 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003505 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3506 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003507 auto* video_receiver = new VideoRtpReceiver(
3508 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003509 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003510 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3511 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3512 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003513 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003514 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003515 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003516}
3517
deadbeef70ab1a12015-09-28 16:53:55 -07003518// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3519// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003520rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003521 const RtpSenderInfo& remote_sender_info) {
3522 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3523 if (!receiver) {
3524 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3525 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003526 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003527 }
Steve Anton4171afb2017-11-20 10:20:22 -08003528 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3529 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3530 } else {
3531 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3532 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003533 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003534}
3535
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003536void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3537 MediaStreamInterface* stream) {
3538 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003539 RTC_DCHECK(track);
3540 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003541 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003542 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003543 // We already have a sender for this track, so just change the stream_id
3544 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003545 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003546 return;
3547 }
3548
3549 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003550 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003551 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003552 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003553 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003554 // If the sender has already been configured in SDP, we call SetSsrc,
3555 // which will connect the sender to the underlying transport. This can
3556 // occur if a local session description that contains the ID of the sender
3557 // is set before AddStream is called. It can also occur if the local
3558 // session description is not changed and RemoveStream is called, and
3559 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003560 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003561 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003562 if (sender_info) {
3563 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003564 }
3565}
3566
3567// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3568// indefinitely, when we have unified plan SDP.
3569void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3570 MediaStreamInterface* stream) {
3571 RTC_DCHECK(!IsClosed());
3572 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003573 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003574 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3575 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003576 return;
3577 }
Steve Anton4171afb2017-11-20 10:20:22 -08003578 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003579}
3580
3581void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3582 MediaStreamInterface* stream) {
3583 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003584 RTC_DCHECK(track);
3585 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003586 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003587 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003588 // We already have a sender for this track, so just change the stream_id
3589 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003590 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003591 return;
3592 }
3593
3594 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003595 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003596 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003597 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003598 GetVideoTransceiver()->internal()->AddSender(new_sender);
3599 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003600 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003601 if (sender_info) {
3602 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003603 }
3604}
3605
3606void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3607 MediaStreamInterface* stream) {
3608 RTC_DCHECK(!IsClosed());
3609 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003610 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003611 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3612 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003613 return;
3614 }
Steve Anton4171afb2017-11-20 10:20:22 -08003615 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003616}
3617
Steve Antonba818672017-11-06 10:21:57 -08003618void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003619 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003620 if (ice_connection_state_ == new_state) {
3621 return;
3622 }
3623
deadbeefcbecd352015-09-23 11:50:27 -07003624 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003625 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003626 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003627 return;
3628 }
Steve Antonba818672017-11-06 10:21:57 -08003629
Mirko Bonadei675513b2017-11-09 11:09:25 +01003630 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3631 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003632 RTC_DCHECK(ice_connection_state_ !=
3633 PeerConnectionInterface::kIceConnectionClosed);
3634
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003635 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003636 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003637}
3638
Alex Loiko9289eda2018-11-23 16:18:59 +00003639void PeerConnection::SetStandardizedIceConnectionState(
3640 PeerConnectionInterface::IceConnectionState new_state) {
3641 RTC_DCHECK(signaling_thread()->IsCurrent());
3642 if (standardized_ice_connection_state_ == new_state)
3643 return;
3644 if (IsClosed())
3645 return;
3646 standardized_ice_connection_state_ = new_state;
3647 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3648 // the old one once disconnects are handled properly.
3649}
3650
Jonas Olsson635474e2018-10-18 15:58:17 +02003651void PeerConnection::SetConnectionState(
3652 PeerConnectionInterface::PeerConnectionState new_state) {
3653 RTC_DCHECK(signaling_thread()->IsCurrent());
3654 if (connection_state_ == new_state)
3655 return;
3656 if (IsClosed())
3657 return;
3658 connection_state_ = new_state;
3659 Observer()->OnConnectionChange(new_state);
3660}
3661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003662void PeerConnection::OnIceGatheringChange(
3663 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003664 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003665 if (IsClosed()) {
3666 return;
3667 }
3668 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003669 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003670}
3671
jbauch81bf7b02017-03-25 08:31:12 -07003672void PeerConnection::OnIceCandidate(
3673 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003674 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003675 if (IsClosed()) {
3676 return;
3677 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003678 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003679 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3680 candidate->candidate().address().IsPrivateIP()) {
3681 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3682 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003683 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003684}
3685
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003686void PeerConnection::OnIceCandidatesRemoved(
3687 const std::vector<cricket::Candidate>& candidates) {
3688 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003689 if (IsClosed()) {
3690 return;
3691 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003692 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003693}
3694
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003695void PeerConnection::ChangeSignalingState(
3696 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003697 RTC_DCHECK(signaling_thread()->IsCurrent());
3698 if (signaling_state_ == signaling_state) {
3699 return;
3700 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003701 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3702 << GetSignalingStateString(signaling_state_)
3703 << " New state: "
3704 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003705 signaling_state_ = signaling_state;
3706 if (signaling_state == kClosed) {
3707 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003708 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003709 standardized_ice_connection_state_ =
3710 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003711 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3712 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003713 if (ice_gathering_state_ != kIceGatheringComplete) {
3714 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003715 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003716 }
3717 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003718 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003719}
3720
deadbeefeb459812015-12-15 19:24:43 -08003721void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3722 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003723 if (IsClosed()) {
3724 return;
3725 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003726 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003727 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003728}
3729
deadbeefeb459812015-12-15 19:24:43 -08003730void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3731 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003732 if (IsClosed()) {
3733 return;
3734 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003735 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003736 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003737}
3738
3739void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3740 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003741 if (IsClosed()) {
3742 return;
3743 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003744 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003745 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003746}
3747
3748void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3749 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003750 if (IsClosed()) {
3751 return;
3752 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003753 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003754 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003755}
3756
Henrik Boström31638672017-11-23 17:48:32 +01003757void PeerConnection::PostSetSessionDescriptionSuccess(
3758 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003759 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3760 signaling_thread()->Post(RTC_FROM_HERE, this,
3761 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003762}
3763
deadbeefab9b2d12015-10-14 11:33:11 -07003764void PeerConnection::PostSetSessionDescriptionFailure(
3765 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003766 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003767 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003768 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3769 msg->error = std::move(error);
3770 signaling_thread()->Post(RTC_FROM_HERE, this,
3771 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003772}
3773
3774void PeerConnection::PostCreateSessionDescriptionFailure(
3775 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003776 RTCError error) {
3777 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003778 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3779 msg->error = std::move(error);
3780 signaling_thread()->Post(RTC_FROM_HERE, this,
3781 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003782}
3783
zhihuang1c378ed2017-08-17 14:10:50 -07003784void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003785 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003786 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003787 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003788
Steve Antondcc3c022017-12-22 16:02:54 -08003789 if (IsUnifiedPlan()) {
3790 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3791 } else {
3792 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3793 }
3794
Steve Antonfa2260d2017-12-28 16:38:23 -08003795 // Intentionally unset the data channel type for RTP data channel with the
3796 // second condition. Otherwise the RTP data channels would be successfully
3797 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3798 // when building with chromium. We want to leave RTP data channels broken, so
3799 // people won't try to use them.
3800 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3801 session_options->data_channel_type = data_channel_type();
3802 }
3803
Steve Antondcc3c022017-12-22 16:02:54 -08003804 // Apply ICE restart flag and renomination flag.
3805 for (auto& options : session_options->media_description_options) {
3806 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3807 options.transport_options.enable_ice_renomination =
3808 configuration_.enable_ice_renomination;
3809 }
3810
3811 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003812 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08003813 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003814 session_options->pooled_ice_credentials =
3815 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3816 RTC_FROM_HERE,
3817 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3818 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003819 session_options->offer_extmap_allow_mixed =
3820 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003821}
3822
3823void PeerConnection::GetOptionsForPlanBOffer(
3824 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3825 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003826 // Figure out transceiver directional preferences.
3827 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3828 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3829
3830 // By default, generate sendrecv/recvonly m= sections.
3831 bool recv_audio = true;
3832 bool recv_video = true;
3833
3834 // By default, only offer a new m= section if we have media to send with it.
3835 bool offer_new_audio_description = send_audio;
3836 bool offer_new_video_description = send_video;
3837 bool offer_new_data_description = HasDataChannels();
3838
3839 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003840 if (offer_answer_options.offer_to_receive_audio !=
3841 RTCOfferAnswerOptions::kUndefined) {
3842 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003843 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003844 offer_new_audio_description ||
3845 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003846 }
Steve Antondcc3c022017-12-22 16:02:54 -08003847 if (offer_answer_options.offer_to_receive_video !=
3848 RTCOfferAnswerOptions::kUndefined) {
3849 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003850 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003851 offer_new_video_description ||
3852 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003853 }
3854
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003855 absl::optional<size_t> audio_index;
3856 absl::optional<size_t> video_index;
3857 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003858 // If a current description exists, generate m= sections in the same order,
3859 // using the first audio/video/data section that appears and rejecting
3860 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003861 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003862 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003863 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003864 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3865 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3866 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003867 }
3868
zhihuang1c378ed2017-08-17 14:10:50 -07003869 // Add audio/video/data m= sections to the end if needed.
3870 if (!audio_index && offer_new_audio_description) {
3871 session_options->media_description_options.push_back(
3872 cricket::MediaDescriptionOptions(
3873 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003874 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3875 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003876 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003877 }
zhihuang1c378ed2017-08-17 14:10:50 -07003878 if (!video_index && offer_new_video_description) {
3879 session_options->media_description_options.push_back(
3880 cricket::MediaDescriptionOptions(
3881 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003882 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3883 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003884 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003885 }
zhihuang1c378ed2017-08-17 14:10:50 -07003886 if (!data_index && offer_new_data_description) {
3887 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003888 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003889 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003890 }
3891
3892 cricket::MediaDescriptionOptions* audio_media_description_options =
3893 !audio_index ? nullptr
3894 : &session_options->media_description_options[*audio_index];
3895 cricket::MediaDescriptionOptions* video_media_description_options =
3896 !video_index ? nullptr
3897 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003898
Steve Anton4171afb2017-11-20 10:20:22 -08003899 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003900 video_media_description_options,
3901 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003902}
3903
3904// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3905// and return a reference to it.
3906// Generated MIDs should be no more than 3 bytes long to take up less space in
3907// the RTP packet.
3908static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3909 RTC_DCHECK(used_mids);
3910 // We're boring: just generate MIDs 0, 1, 2, ...
3911 size_t i = 0;
3912 std::set<std::string>::iterator it;
3913 bool inserted;
3914 do {
3915 std::string mid = rtc::ToString(i++);
3916 auto insert_result = used_mids->insert(mid);
3917 it = insert_result.first;
3918 inserted = insert_result.second;
3919 } while (!inserted);
3920 return *it;
3921}
3922
3923static cricket::MediaDescriptionOptions
3924GetMediaDescriptionOptionsForTransceiver(
3925 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3926 transceiver,
3927 const std::string& mid) {
3928 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003929 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003930 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003931 // This behavior is specified in JSEP. The gist is that:
3932 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3933 // sendrecv.
3934 // 2. If the MSID is included, then it must be included in any subsequent
3935 // offer/answer exactly the same until the RtpTransceiver is stopped.
3936 if (!transceiver->stopped() &&
3937 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3938 transceiver->internal()->has_ever_been_used_to_send())) {
3939 cricket::SenderOptions sender_options;
3940 sender_options.track_id = transceiver->sender()->id();
3941 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003942 int num_send_encoding_layers =
3943 transceiver->sender()->init_send_encodings().size();
3944 sender_options.num_sim_layers =
3945 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003946 media_description_options.sender_options.push_back(sender_options);
3947 }
Steve Antondcc3c022017-12-22 16:02:54 -08003948 return media_description_options;
3949}
3950
3951void PeerConnection::GetOptionsForUnifiedPlanOffer(
3952 const RTCOfferAnswerOptions& offer_answer_options,
3953 cricket::MediaSessionOptions* session_options) {
3954 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3955 // Offers) and 5.2.2 (Subsequent Offers).
3956 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3957 const ContentInfos& local_contents =
3958 (local_description() ? local_description()->description()->contents()
3959 : ContentInfos());
3960 const ContentInfos& remote_contents =
3961 (remote_description() ? remote_description()->description()->contents()
3962 : ContentInfos());
3963 // The mline indices that can be recycled. New transceivers should reuse these
3964 // slots first.
3965 std::queue<size_t> recycleable_mline_indices;
3966 // Track the MIDs used in previous offer/answer exchanges and the current
3967 // offer so that new, unique MIDs are generated.
3968 std::set<std::string> used_mids = seen_mids_;
3969 // First, go through each media section that exists in either the local or
3970 // remote description and generate a media section in this offer for the
3971 // associated transceiver. If a media section can be recycled, generate a
3972 // default, rejected media section here that can be later overwritten.
3973 for (size_t i = 0;
3974 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3975 // Either |local_content| or |remote_content| is non-null.
3976 const ContentInfo* local_content =
3977 (i < local_contents.size() ? &local_contents[i] : nullptr);
3978 const ContentInfo* remote_content =
3979 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3980 bool had_been_rejected = (local_content && local_content->rejected) ||
3981 (remote_content && remote_content->rejected);
3982 const std::string& mid =
3983 (local_content ? local_content->name : remote_content->name);
3984 cricket::MediaType media_type =
3985 (local_content ? local_content->media_description()->type()
3986 : remote_content->media_description()->type());
3987 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3988 media_type == cricket::MEDIA_TYPE_VIDEO) {
3989 auto transceiver = GetAssociatedTransceiver(mid);
3990 RTC_CHECK(transceiver);
3991 // A media section is considered eligible for recycling if it is marked as
3992 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003993 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003994 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003995 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3996 RtpTransceiverDirection::kInactive,
3997 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003998 recycleable_mline_indices.push(i);
3999 } else {
4000 session_options->media_description_options.push_back(
4001 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4002 // CreateOffer shouldn't really cause any state changes in
4003 // PeerConnection, but we need a way to match new transceivers to new
4004 // media sections in SetLocalDescription and JSEP specifies this is done
4005 // by recording the index of the media section generated for the
4006 // transceiver in the offer.
4007 transceiver->internal()->set_mline_index(i);
4008 }
4009 } else {
4010 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004011 RTC_CHECK(GetDataMid());
4012 if (had_been_rejected || mid != *GetDataMid()) {
4013 session_options->media_description_options.push_back(
4014 GetMediaDescriptionOptionsForRejectedData(mid));
4015 } else {
4016 session_options->media_description_options.push_back(
4017 GetMediaDescriptionOptionsForActiveData(mid));
4018 }
Steve Antondcc3c022017-12-22 16:02:54 -08004019 }
4020 }
4021 // Next, look for transceivers that are newly added (that is, are not stopped
4022 // and not associated). Reuse media sections marked as recyclable first,
4023 // otherwise append to the end of the offer. New media sections should be
4024 // added in the order they were added to the PeerConnection.
4025 for (auto transceiver : transceivers_) {
4026 if (transceiver->mid() || transceiver->stopped()) {
4027 continue;
4028 }
4029 size_t mline_index;
4030 if (!recycleable_mline_indices.empty()) {
4031 mline_index = recycleable_mline_indices.front();
4032 recycleable_mline_indices.pop();
4033 session_options->media_description_options[mline_index] =
4034 GetMediaDescriptionOptionsForTransceiver(transceiver,
4035 AllocateMid(&used_mids));
4036 } else {
4037 mline_index = session_options->media_description_options.size();
4038 session_options->media_description_options.push_back(
4039 GetMediaDescriptionOptionsForTransceiver(transceiver,
4040 AllocateMid(&used_mids)));
4041 }
4042 // See comment above for why CreateOffer changes the transceiver's state.
4043 transceiver->internal()->set_mline_index(mline_index);
4044 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004045 // Lastly, add a m-section if we have local data channels and an m section
4046 // does not already exist.
4047 if (!GetDataMid() && HasDataChannels()) {
4048 session_options->media_description_options.push_back(
4049 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4050 }
Steve Antondcc3c022017-12-22 16:02:54 -08004051}
4052
4053void PeerConnection::GetOptionsForAnswer(
4054 const RTCOfferAnswerOptions& offer_answer_options,
4055 cricket::MediaSessionOptions* session_options) {
4056 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4057
4058 if (IsUnifiedPlan()) {
4059 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4060 } else {
4061 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4062 }
4063
Steve Antonfa2260d2017-12-28 16:38:23 -08004064 // Intentionally unset the data channel type for RTP data channel. Otherwise
4065 // the RTP data channels would be successfully negotiated by default and the
4066 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4067 // We want to leave RTP data channels broken, so people won't try to use them.
4068 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4069 session_options->data_channel_type = data_channel_type();
4070 }
4071
Steve Antondcc3c022017-12-22 16:02:54 -08004072 // Apply ICE renomination flag.
4073 for (auto& options : session_options->media_description_options) {
4074 options.transport_options.enable_ice_renomination =
4075 configuration_.enable_ice_renomination;
4076 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004077
4078 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004079 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08004080 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004081 session_options->pooled_ice_credentials =
4082 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4083 RTC_FROM_HERE,
4084 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4085 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004086}
4087
Steve Antondcc3c022017-12-22 16:02:54 -08004088void PeerConnection::GetOptionsForPlanBAnswer(
4089 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004090 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004091 // Figure out transceiver directional preferences.
4092 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4093 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4094
4095 // By default, generate sendrecv/recvonly m= sections. The direction is also
4096 // restricted by the direction in the offer.
4097 bool recv_audio = true;
4098 bool recv_video = true;
4099
4100 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004101 if (offer_answer_options.offer_to_receive_audio !=
4102 RTCOfferAnswerOptions::kUndefined) {
4103 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004104 }
Steve Antondcc3c022017-12-22 16:02:54 -08004105 if (offer_answer_options.offer_to_receive_video !=
4106 RTCOfferAnswerOptions::kUndefined) {
4107 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004108 }
4109
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004110 absl::optional<size_t> audio_index;
4111 absl::optional<size_t> video_index;
4112 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004113
4114 // Generate m= sections that match those in the offer.
4115 // Note that mediasession.cc will handle intersection our preferred
4116 // direction with the offered direction.
4117 GenerateMediaDescriptionOptions(
4118 remote_description(),
4119 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4120 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4121 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004122
4123 cricket::MediaDescriptionOptions* audio_media_description_options =
4124 !audio_index ? nullptr
4125 : &session_options->media_description_options[*audio_index];
4126 cricket::MediaDescriptionOptions* video_media_description_options =
4127 !video_index ? nullptr
4128 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004129
Steve Anton4171afb2017-11-20 10:20:22 -08004130 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004131 video_media_description_options,
4132 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004133}
zhihuangaf388472016-11-02 16:49:48 -07004134
Steve Antondcc3c022017-12-22 16:02:54 -08004135void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4136 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4137 cricket::MediaSessionOptions* session_options) {
4138 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4139 // Answers) and 5.3.2 (Subsequent Answers).
4140 RTC_DCHECK(remote_description());
4141 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4142 for (const ContentInfo& content :
4143 remote_description()->description()->contents()) {
4144 cricket::MediaType media_type = content.media_description()->type();
4145 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4146 media_type == cricket::MEDIA_TYPE_VIDEO) {
4147 auto transceiver = GetAssociatedTransceiver(content.name);
4148 RTC_CHECK(transceiver);
4149 session_options->media_description_options.push_back(
4150 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4151 } else {
4152 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004153 // Reject all data sections if data channels are disabled.
4154 // Reject a data section if it has already been rejected.
4155 // Reject all data sections except for the first one.
4156 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4157 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004158 session_options->media_description_options.push_back(
4159 GetMediaDescriptionOptionsForRejectedData(content.name));
4160 } else {
4161 session_options->media_description_options.push_back(
4162 GetMediaDescriptionOptionsForActiveData(content.name));
4163 }
Steve Antondcc3c022017-12-22 16:02:54 -08004164 }
4165 }
htaa2a49d92016-03-04 02:51:39 -08004166}
4167
zhihuang1c378ed2017-08-17 14:10:50 -07004168void PeerConnection::GenerateMediaDescriptionOptions(
4169 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004170 RtpTransceiverDirection audio_direction,
4171 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004172 absl::optional<size_t>* audio_index,
4173 absl::optional<size_t>* video_index,
4174 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004175 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004176 for (const cricket::ContentInfo& content :
4177 session_desc->description()->contents()) {
4178 if (IsAudioContent(&content)) {
4179 // If we already have an audio m= section, reject this extra one.
4180 if (*audio_index) {
4181 session_options->media_description_options.push_back(
4182 cricket::MediaDescriptionOptions(
4183 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004184 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004185 } else {
4186 session_options->media_description_options.push_back(
4187 cricket::MediaDescriptionOptions(
4188 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004189 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004190 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004191 }
4192 } else if (IsVideoContent(&content)) {
4193 // If we already have an video m= section, reject this extra one.
4194 if (*video_index) {
4195 session_options->media_description_options.push_back(
4196 cricket::MediaDescriptionOptions(
4197 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004198 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004199 } else {
4200 session_options->media_description_options.push_back(
4201 cricket::MediaDescriptionOptions(
4202 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004203 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004204 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004205 }
4206 } else {
4207 RTC_DCHECK(IsDataContent(&content));
4208 // If we already have an data m= section, reject this extra one.
4209 if (*data_index) {
4210 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004211 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004212 } else {
4213 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004214 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004215 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004216 }
4217 }
htaa2a49d92016-03-04 02:51:39 -08004218 }
deadbeefab9b2d12015-10-14 11:33:11 -07004219}
4220
Steve Antonfa2260d2017-12-28 16:38:23 -08004221cricket::MediaDescriptionOptions
4222PeerConnection::GetMediaDescriptionOptionsForActiveData(
4223 const std::string& mid) const {
4224 // Direction for data sections is meaningless, but legacy endpoints might
4225 // expect sendrecv.
4226 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4227 RtpTransceiverDirection::kSendRecv,
4228 /*stopped=*/false);
4229 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4230 return options;
4231}
4232
4233cricket::MediaDescriptionOptions
4234PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4235 const std::string& mid) const {
4236 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4237 RtpTransceiverDirection::kInactive,
4238 /*stopped=*/true);
4239 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4240 return options;
4241}
4242
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004243absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004244 switch (data_channel_type_) {
4245 case cricket::DCT_RTP:
4246 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004247 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004248 }
4249 return rtp_data_channel_->content_name();
4250 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004251 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004252 case cricket::DCT_MEDIA_TRANSPORT:
4253 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004254 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004255 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004256 }
4257}
4258
Steve Anton4171afb2017-11-20 10:20:22 -08004259void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4260 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4261 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004262 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004263}
4264
Steve Anton4171afb2017-11-20 10:20:22 -08004265void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004266 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004267 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004268 cricket::MediaType media_type,
4269 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004270 RTC_DCHECK(!IsUnifiedPlan());
4271
Steve Anton4171afb2017-11-20 10:20:22 -08004272 std::vector<RtpSenderInfo>* current_senders =
4273 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004274
Steve Anton4171afb2017-11-20 10:20:22 -08004275 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004276 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004277 for (auto sender_it = current_senders->begin();
4278 sender_it != current_senders->end();
4279 /* incremented manually */) {
4280 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004281 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004282 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004283 std::string params_stream_id;
4284 if (params) {
4285 params_stream_id =
4286 (!params->first_stream_id().empty() ? params->first_stream_id()
4287 : kDefaultStreamId);
4288 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004289 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004290 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004291 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004292 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004293 sender_exists) {
4294 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004295 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004296 OnRemoteSenderRemoved(info, media_type);
4297 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004298 }
4299 }
4300
Steve Anton4171afb2017-11-20 10:20:22 -08004301 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004302 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004303 if (!params.has_ssrcs()) {
4304 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4305 // sender, this means it is coming from a Unified Plan endpoint,so we just
4306 // create a default.
4307 default_sender_needed = true;
4308 break;
4309 }
4310
Seth Hampson845e8782018-03-02 11:34:10 -08004311 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004312 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004313 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4314 // not supported in Plan B, we just take the first here and create the
4315 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004316 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004317 (!params.first_stream_id().empty() ? params.first_stream_id()
4318 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004319 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004320 uint32_t ssrc = params.first_ssrc();
4321
4322 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004323 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004324 if (!stream) {
4325 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004326 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004327 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004328 remote_streams_->AddStream(stream);
4329 new_streams->AddStream(stream);
4330 }
4331
Steve Anton4171afb2017-11-20 10:20:22 -08004332 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004333 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004334 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004335 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004336 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004337 }
4338 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004339
Steve Anton4171afb2017-11-20 10:20:22 -08004340 // Add default sender if necessary.
4341 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004342 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004343 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004344 if (!default_stream) {
4345 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004346 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004347 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004348 remote_streams_->AddStream(default_stream);
4349 new_streams->AddStream(default_stream);
4350 }
Steve Anton4171afb2017-11-20 10:20:22 -08004351 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4352 ? kDefaultAudioSenderId
4353 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004354 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004355 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004356 if (!default_sender_info) {
4357 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004358 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004359 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004360 }
4361 }
deadbeefab9b2d12015-10-14 11:33:11 -07004362}
4363
Steve Anton4171afb2017-11-20 10:20:22 -08004364void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4365 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004366 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4367 << " receiver for track_id=" << sender_info.sender_id
4368 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004369
Steve Anton3d954a62018-04-02 11:27:23 -07004370 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004371 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004372 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004373 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004374 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004375 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004376 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004377 }
4378}
4379
Steve Anton4171afb2017-11-20 10:20:22 -08004380void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4381 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004382 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4383 << " receiver for track_id=" << sender_info.sender_id
4384 << " and stream_id=" << sender_info.stream_id;
4385
Seth Hampson845e8782018-03-02 11:34:10 -08004386 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004387
Henrik Boström933d8b02017-10-10 10:05:16 -07004388 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004389 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004390 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4391 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004392 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004393 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004394 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004395 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004396 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004397 }
4398 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004399 // Stopping or destroying a VideoRtpReceiver will end the
4400 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004401 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004402 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004403 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004404 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004405 // There's no guarantee the track is still available, e.g. the track may
4406 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004407 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004408 }
4409 } else {
nisseede5da42017-01-12 05:15:36 -08004410 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004411 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004412 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004413 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004414 }
deadbeefab9b2d12015-10-14 11:33:11 -07004415}
4416
4417void PeerConnection::UpdateEndedRemoteMediaStreams() {
4418 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4419 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4420 MediaStreamInterface* stream = remote_streams_->at(i);
4421 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4422 streams_to_remove.push_back(stream);
4423 }
4424 }
4425
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004426 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004427 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004428 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004429 }
4430}
4431
Steve Anton4171afb2017-11-20 10:20:22 -08004432void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004433 const std::vector<cricket::StreamParams>& streams,
4434 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004435 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004436
Seth Hampson845e8782018-03-02 11:34:10 -08004437 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004438 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004439 for (auto sender_it = current_senders->begin();
4440 sender_it != current_senders->end();
4441 /* incremented manually */) {
4442 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004443 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004444 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4445 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004446 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004447 OnLocalSenderRemoved(info, media_type);
4448 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004449 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004450 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004451 }
4452 }
4453
Steve Anton4171afb2017-11-20 10:20:22 -08004454 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004455 for (const cricket::StreamParams& params : streams) {
4456 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004457 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004458 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004459 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004460 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004461 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004462 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004463 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004464 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004465 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004466 }
4467 }
4468}
4469
Steve Anton4171afb2017-11-20 10:20:22 -08004470void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4471 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004472 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004473 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004474 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004475 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4476 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004477 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004478 return;
4479 }
4480
deadbeeffac06552015-11-25 11:26:01 -08004481 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004482 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004483 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004484 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004485 }
deadbeeffac06552015-11-25 11:26:01 -08004486
Seth Hampson5b4f0752018-04-02 16:31:36 -07004487 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004488 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004489}
4490
Steve Anton4171afb2017-11-20 10:20:22 -08004491void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4492 cricket::MediaType media_type) {
4493 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004494 if (!sender) {
4495 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004496 // SessionDescriptions has been renegotiated.
4497 return;
4498 }
deadbeeffac06552015-11-25 11:26:01 -08004499
4500 // A sender has been removed from the SessionDescription but it's still
4501 // associated with the PeerConnection. This only occurs if the SDP doesn't
4502 // match with the calls to CreateSender, AddStream and RemoveStream.
4503 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004504 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004505 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004506 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004507 }
deadbeeffac06552015-11-25 11:26:01 -08004508
Steve Anton4171afb2017-11-20 10:20:22 -08004509 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004510}
4511
4512void PeerConnection::UpdateLocalRtpDataChannels(
4513 const cricket::StreamParamsVec& streams) {
4514 std::vector<std::string> existing_channels;
4515
4516 // Find new and active data channels.
4517 for (const cricket::StreamParams& params : streams) {
4518 // |it->sync_label| is actually the data channel label. The reason is that
4519 // we use the same naming of data channels as we do for
4520 // MediaStreams and Tracks.
4521 // For MediaStreams, the sync_label is the MediaStream label and the
4522 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004523 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004524 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004525 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004526 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004527 continue;
4528 }
4529 // Set the SSRC the data channel should use for sending.
4530 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4531 existing_channels.push_back(data_channel_it->first);
4532 }
4533
4534 UpdateClosingRtpDataChannels(existing_channels, true);
4535}
4536
4537void PeerConnection::UpdateRemoteRtpDataChannels(
4538 const cricket::StreamParamsVec& streams) {
4539 std::vector<std::string> existing_channels;
4540
4541 // Find new and active data channels.
4542 for (const cricket::StreamParams& params : streams) {
4543 // The data channel label is either the mslabel or the SSRC if the mslabel
4544 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004545 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004546 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004547 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004548 auto data_channel_it = rtp_data_channels_.find(label);
4549 if (data_channel_it == rtp_data_channels_.end()) {
4550 // This is a new data channel.
4551 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4552 } else {
4553 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4554 }
4555 existing_channels.push_back(label);
4556 }
4557
4558 UpdateClosingRtpDataChannels(existing_channels, false);
4559}
4560
4561void PeerConnection::UpdateClosingRtpDataChannels(
4562 const std::vector<std::string>& active_channels,
4563 bool is_local_update) {
4564 auto it = rtp_data_channels_.begin();
4565 while (it != rtp_data_channels_.end()) {
4566 DataChannel* data_channel = it->second;
4567 if (std::find(active_channels.begin(), active_channels.end(),
4568 data_channel->label()) != active_channels.end()) {
4569 ++it;
4570 continue;
4571 }
4572
4573 if (is_local_update) {
4574 data_channel->SetSendSsrc(0);
4575 } else {
4576 data_channel->RemotePeerRequestClose();
4577 }
4578
4579 if (data_channel->state() == DataChannel::kClosed) {
4580 rtp_data_channels_.erase(it);
4581 it = rtp_data_channels_.begin();
4582 } else {
4583 ++it;
4584 }
4585 }
4586}
4587
4588void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4589 uint32_t remote_ssrc) {
4590 rtc::scoped_refptr<DataChannel> channel(
4591 InternalCreateDataChannel(label, nullptr));
4592 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004593 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004594 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004595 return;
4596 }
4597 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004598 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4599 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004600 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004601}
4602
4603rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4604 const std::string& label,
4605 const InternalDataChannelInit* config) {
4606 if (IsClosed()) {
4607 return nullptr;
4608 }
Steve Anton75737c02017-11-06 10:37:17 -08004609 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004610 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004611 << "InternalCreateDataChannel: Data is not supported in this call.";
4612 return nullptr;
4613 }
4614 InternalDataChannelInit new_config =
4615 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004616 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004617 if (new_config.id < 0) {
4618 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004619 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004620 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004621 RTC_LOG(LS_ERROR)
4622 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004623 return nullptr;
4624 }
4625 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004626 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004627 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004628 return nullptr;
4629 }
4630 }
4631
Steve Anton75737c02017-11-06 10:37:17 -08004632 rtc::scoped_refptr<DataChannel> channel(
4633 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004634 if (!channel) {
4635 sid_allocator_.ReleaseSid(new_config.id);
4636 return nullptr;
4637 }
4638
4639 if (channel->data_channel_type() == cricket::DCT_RTP) {
4640 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004641 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4642 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004643 return nullptr;
4644 }
4645 rtp_data_channels_[channel->label()] = channel;
4646 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004647 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004648 sctp_data_channels_.push_back(channel);
4649 channel->SignalClosed.connect(this,
4650 &PeerConnection::OnSctpDataChannelClosed);
4651 }
4652
Steve Anton2d8609c2018-01-23 16:38:46 -08004653 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004654 return channel;
4655}
4656
4657bool PeerConnection::HasDataChannels() const {
4658 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4659}
4660
4661void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4662 for (const auto& channel : sctp_data_channels_) {
4663 if (channel->id() < 0) {
4664 int sid;
4665 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004666 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004667 continue;
4668 }
4669 channel->SetSctpSid(sid);
4670 }
4671 }
4672}
4673
4674void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004675 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004676 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4677 ++it) {
4678 if (it->get() == channel) {
4679 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004680 // After the closing procedure is done, it's safe to use this ID for
4681 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004682 sid_allocator_.ReleaseSid(channel->id());
4683 }
deadbeefbd292462015-12-14 18:15:29 -08004684 // Since this method is triggered by a signal from the DataChannel,
4685 // we can't free it directly here; we need to free it asynchronously.
4686 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004687 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004688 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4689 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004690 return;
4691 }
4692 }
4693}
4694
deadbeefab9b2d12015-10-14 11:33:11 -07004695void PeerConnection::OnDataChannelDestroyed() {
4696 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4697 // DataChannel may callback to us and try to modify the list.
4698 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4699 temp_rtp_dcs.swap(rtp_data_channels_);
4700 for (const auto& kv : temp_rtp_dcs) {
4701 kv.second->OnTransportChannelDestroyed();
4702 }
4703
4704 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4705 temp_sctp_dcs.swap(sctp_data_channels_);
4706 for (const auto& channel : temp_sctp_dcs) {
4707 channel->OnTransportChannelDestroyed();
4708 }
4709}
4710
4711void PeerConnection::OnDataChannelOpenMessage(
4712 const std::string& label,
4713 const InternalDataChannelInit& config) {
4714 rtc::scoped_refptr<DataChannel> channel(
4715 InternalCreateDataChannel(label, &config));
4716 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004717 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004718 return;
4719 }
4720
deadbeefa601f5c2016-06-06 14:27:39 -07004721 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4722 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004723 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004724 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004725}
4726
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004727bool PeerConnection::HandleOpenMessage_s(
4728 const cricket::ReceiveDataParams& params,
4729 const rtc::CopyOnWriteBuffer& buffer) {
4730 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4731 // Received OPEN message; parse and signal that a new data channel should
4732 // be created.
4733 std::string label;
4734 InternalDataChannelInit config;
4735 config.id = params.ssrc;
4736 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4737 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4738 << params.ssrc;
4739 return true;
4740 }
4741 config.open_handshake_role = InternalDataChannelInit::kAcker;
4742 OnDataChannelOpenMessage(label, config);
4743 return true;
4744 }
4745 return false;
4746}
4747
Steve Anton4171afb2017-11-20 10:20:22 -08004748rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4749PeerConnection::GetAudioTransceiver() const {
4750 // This method only works with Plan B SDP, where there is a single
4751 // audio/video transceiver.
4752 RTC_DCHECK(!IsUnifiedPlan());
4753 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004754 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004755 return transceiver;
4756 }
4757 }
4758 RTC_NOTREACHED();
4759 return nullptr;
4760}
4761
4762rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4763PeerConnection::GetVideoTransceiver() const {
4764 // This method only works with Plan B SDP, where there is a single
4765 // audio/video transceiver.
4766 RTC_DCHECK(!IsUnifiedPlan());
4767 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004768 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004769 return transceiver;
4770 }
4771 }
4772 RTC_NOTREACHED();
4773 return nullptr;
4774}
4775
4776// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4777// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004778bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004779 switch (type) {
4780 case cricket::MEDIA_TYPE_AUDIO:
4781 return !GetAudioTransceiver()->internal()->senders().empty();
4782 case cricket::MEDIA_TYPE_VIDEO:
4783 return !GetVideoTransceiver()->internal()->senders().empty();
4784 case cricket::MEDIA_TYPE_DATA:
4785 return false;
4786 }
4787 RTC_NOTREACHED();
4788 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004789}
4790
Steve Anton4171afb2017-11-20 10:20:22 -08004791rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4792PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4793 for (auto transceiver : transceivers_) {
4794 for (auto sender : transceiver->internal()->senders()) {
4795 if (sender->track() == track) {
4796 return sender;
4797 }
4798 }
4799 }
4800 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004801}
4802
Steve Anton4171afb2017-11-20 10:20:22 -08004803rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4804PeerConnection::FindSenderById(const std::string& sender_id) const {
4805 for (auto transceiver : transceivers_) {
4806 for (auto sender : transceiver->internal()->senders()) {
4807 if (sender->id() == sender_id) {
4808 return sender;
4809 }
4810 }
4811 }
4812 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004813}
4814
Steve Anton4171afb2017-11-20 10:20:22 -08004815rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4816PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4817 for (auto transceiver : transceivers_) {
4818 for (auto receiver : transceiver->internal()->receivers()) {
4819 if (receiver->id() == receiver_id) {
4820 return receiver;
4821 }
4822 }
4823 }
4824 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004825}
4826
Steve Anton4171afb2017-11-20 10:20:22 -08004827std::vector<PeerConnection::RtpSenderInfo>*
4828PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4829 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4830 media_type == cricket::MEDIA_TYPE_VIDEO);
4831 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4832 ? &remote_audio_sender_infos_
4833 : &remote_video_sender_infos_;
4834}
4835
4836std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004837 cricket::MediaType media_type) {
4838 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4839 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004840 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4841 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004842}
4843
Steve Anton4171afb2017-11-20 10:20:22 -08004844const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4845 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004846 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004847 const std::string sender_id) const {
4848 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004849 if (sender_info.stream_id == stream_id &&
4850 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004851 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004852 }
4853 }
4854 return nullptr;
4855}
4856
4857DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4858 for (const auto& channel : sctp_data_channels_) {
4859 if (channel->id() == sid) {
4860 return channel;
4861 }
4862 }
4863 return nullptr;
4864}
4865
deadbeef91dd5672016-05-18 16:55:30 -07004866bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004867 const cricket::ServerAddresses& stun_servers,
4868 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004869 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004870 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004871 // To handle both internal and externally created port allocator, we will
4872 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004873 port_allocator_flags_ = port_allocator_->flags();
4874 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4875 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4876 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004877 // If the disable-IPv6 flag was specified, we'll not override it
4878 // by experiment.
4879 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004880 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004881 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4882 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004883 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004884 }
4885
zhihuangb09b3f92017-03-07 14:40:51 -08004886 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004887 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004888 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004889 }
4890
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004891 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004892 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004893 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004894 }
4895
honghaiz60347052016-05-31 18:29:12 -07004896 if (configuration.candidate_network_policy ==
4897 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004898 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004899 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004900 }
4901
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004902 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004903 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004904 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4905 }
4906
Qingsi Wanga2d60672018-04-11 16:57:45 -07004907 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004908 // No step delay is used while allocating ports.
4909 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4910 port_allocator_->set_candidate_filter(
4911 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004912 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004913
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004914 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004915 for (auto& turn_server : turn_servers_copy) {
4916 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004917 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004918 // Call this last since it may create pooled allocator sessions using the
4919 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004920 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004921 stun_servers, std::move(turn_servers_copy),
4922 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4923 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004924 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004925 return true;
4926}
4927
deadbeef91dd5672016-05-18 16:55:30 -07004928bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004929 const cricket::ServerAddresses& stun_servers,
4930 const std::vector<cricket::RelayServerConfig>& turn_servers,
4931 IceTransportsType type,
4932 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004933 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004934 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004935 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004936 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004937 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004938 // According to JSEP, after setLocalDescription, changing the candidate pool
4939 // size is not allowed, and changing the set of ICE servers will not result
4940 // in new candidates being gathered.
4941 if (local_description()) {
4942 port_allocator_->FreezeCandidatePool();
4943 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004944 // Add the custom tls turn servers if they exist.
4945 auto turn_servers_copy = turn_servers;
4946 for (auto& turn_server : turn_servers_copy) {
4947 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4948 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004949 // Call this last since it may create pooled allocator sessions using the
4950 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004951 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004952 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4953 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004954}
4955
Steve Antonba818672017-11-06 10:21:57 -08004956cricket::ChannelManager* PeerConnection::channel_manager() const {
4957 return factory_->channel_manager();
4958}
4959
Elad Alon99c3fe52017-10-13 16:29:40 +02004960bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004961 std::unique_ptr<RtcEventLogOutput> output,
4962 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004963 if (!event_log_) {
4964 return false;
4965 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004966 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004967}
4968
4969void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004970 if (event_log_) {
4971 event_log_->StopLogging();
4972 }
ivoc14d5dbe2016-07-04 07:06:55 -07004973}
nisseeaabdf62017-05-05 02:23:02 -07004974
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004975cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08004976 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004977 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004978 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08004979 if (channel && channel->content_name() == content_name) {
4980 return channel;
4981 }
Steve Anton75737c02017-11-06 10:37:17 -08004982 }
4983 if (rtp_data_channel() &&
4984 rtp_data_channel()->content_name() == content_name) {
4985 return rtp_data_channel();
4986 }
4987 return nullptr;
4988}
4989
4990bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004991 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004992 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004993 RTC_LOG(LS_INFO)
4994 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004995 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004996 return false;
4997 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004998 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004999 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005000 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005001 return false;
5002 }
5003
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005004 absl::optional<rtc::SSLRole> dtls_role;
5005 if (sctp_mid_) {
5006 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5007 } else if (is_caller_) {
5008 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5009 }
Zhi Huange830e682018-03-30 10:48:35 -07005010 if (dtls_role) {
5011 *role = *dtls_role;
5012 return true;
5013 }
5014 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005015}
5016
5017bool PeerConnection::GetSslRole(const std::string& content_name,
5018 rtc::SSLRole* role) {
5019 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005020 RTC_LOG(LS_INFO)
5021 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005022 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005023 return false;
5024 }
5025
Zhi Huange830e682018-03-30 10:48:35 -07005026 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5027 if (dtls_role) {
5028 *role = *dtls_role;
5029 return true;
5030 }
5031 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005032}
5033
Steve Antonf8470812017-12-04 10:46:21 -08005034void PeerConnection::SetSessionError(SessionError error,
5035 const std::string& error_desc) {
5036 RTC_DCHECK_RUN_ON(signaling_thread());
5037 if (error != session_error_) {
5038 session_error_ = error;
5039 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005040 }
5041}
5042
Zhi Huange830e682018-03-30 10:48:35 -07005043RTCError PeerConnection::UpdateSessionState(
5044 SdpType type,
5045 cricket::ContentSource source,
5046 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005047 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005048
5049 // If there's already a pending error then no state transition should happen.
5050 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005051 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005052
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005053 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005054 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005055 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005056 }
5057
5058 // Update the signaling state according to the specified state machine (see
5059 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005060 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005061 ChangeSignalingState(source == cricket::CS_LOCAL
5062 ? PeerConnectionInterface::kHaveLocalOffer
5063 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005064 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005065 ChangeSignalingState(source == cricket::CS_LOCAL
5066 ? PeerConnectionInterface::kHaveLocalPrAnswer
5067 : PeerConnectionInterface::kHaveRemotePrAnswer);
5068 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005069 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005070 ChangeSignalingState(PeerConnectionInterface::kStable);
5071 }
5072
5073 // Update internal objects according to the session description's media
5074 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005075 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005076 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005077 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005078 }
5079
Steve Anton8a006912017-12-04 15:25:56 -08005080 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005081}
5082
Steve Anton8a006912017-12-04 15:25:56 -08005083RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005084 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005085 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005086 const SessionDescriptionInterface* sdesc =
5087 (source == cricket::CS_LOCAL ? local_description()
5088 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005089 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005090
5091 // Push down the new SDP media section for each audio/video transceiver.
5092 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005093 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005094 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005095 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005096 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005097 continue;
5098 }
5099 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005100 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005101 if (!content_desc) {
5102 continue;
5103 }
5104 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005105 bool success = (source == cricket::CS_LOCAL)
5106 ? channel->SetLocalContent(content_desc, type, &error)
5107 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005108 if (!success) {
5109 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5110 }
5111 }
5112
5113 // If using the RtpDataChannel, push down the new SDP section for it too.
5114 if (rtp_data_channel_) {
5115 const ContentInfo* data_content =
5116 cricket::GetFirstDataContent(sdesc->description());
5117 if (data_content && !data_content->rejected) {
5118 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005119 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005120 if (data_desc) {
5121 std::string error;
5122 bool success =
5123 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005124 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005125 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005126 if (!success) {
5127 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5128 std::move(error));
5129 }
Steve Anton75737c02017-11-06 10:37:17 -08005130 }
5131 }
5132 }
Steve Antoned10bd92017-12-05 10:52:59 -08005133
Steve Anton75737c02017-11-06 10:37:17 -08005134 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5135 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5136 if (sctp_transport_ && local_description() && remote_description() &&
5137 cricket::GetFirstDataContent(local_description()->description()) &&
5138 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005139 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005140 RTC_FROM_HERE,
5141 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005142 if (!success) {
5143 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5144 "Failed to push down SCTP parameters.");
5145 }
Steve Anton75737c02017-11-06 10:37:17 -08005146 }
Steve Antoned10bd92017-12-05 10:52:59 -08005147
Steve Anton8a006912017-12-04 15:25:56 -08005148 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005149}
5150
5151bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5152 RTC_DCHECK(network_thread()->IsCurrent());
5153 RTC_DCHECK(local_description());
5154 RTC_DCHECK(remote_description());
5155 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5156 // When we support "max-message-size", that would also be pushed down here.
5157 return sctp_transport_->Start(
5158 GetSctpPort(local_description()->description()),
5159 GetSctpPort(remote_description()->description()));
5160}
5161
Steve Anton8a006912017-12-04 15:25:56 -08005162RTCError PeerConnection::PushdownTransportDescription(
5163 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005164 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005165 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005166
Zhi Huange830e682018-03-30 10:48:35 -07005167 if (source == cricket::CS_LOCAL) {
5168 const SessionDescriptionInterface* sdesc = local_description();
5169 RTC_DCHECK(sdesc);
5170 return transport_controller_->SetLocalDescription(type,
5171 sdesc->description());
5172 } else {
5173 const SessionDescriptionInterface* sdesc = remote_description();
5174 RTC_DCHECK(sdesc);
5175 return transport_controller_->SetRemoteDescription(type,
5176 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005177 }
Steve Anton75737c02017-11-06 10:37:17 -08005178}
5179
5180bool PeerConnection::GetTransportDescription(
5181 const SessionDescription* description,
5182 const std::string& content_name,
5183 cricket::TransportDescription* tdesc) {
5184 if (!description || !tdesc) {
5185 return false;
5186 }
5187 const TransportInfo* transport_info =
5188 description->GetTransportInfoByName(content_name);
5189 if (!transport_info) {
5190 return false;
5191 }
5192 *tdesc = transport_info->description;
5193 return true;
5194}
5195
Steve Anton75737c02017-11-06 10:37:17 -08005196cricket::IceConfig PeerConnection::ParseIceConfig(
5197 const PeerConnectionInterface::RTCConfiguration& config) const {
5198 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005199 switch (config.continual_gathering_policy) {
5200 case PeerConnectionInterface::GATHER_ONCE:
5201 gathering_policy = cricket::GATHER_ONCE;
5202 break;
5203 case PeerConnectionInterface::GATHER_CONTINUALLY:
5204 gathering_policy = cricket::GATHER_CONTINUALLY;
5205 break;
5206 default:
5207 RTC_NOTREACHED();
5208 gathering_policy = cricket::GATHER_ONCE;
5209 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005210
Steve Anton75737c02017-11-06 10:37:17 -08005211 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005212 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5213 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005214 ice_config.prioritize_most_likely_candidate_pairs =
5215 config.prioritize_most_likely_ice_candidate_pairs;
5216 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005217 RTCConfigurationToIceConfigOptionalInt(
5218 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005219 ice_config.continual_gathering_policy = gathering_policy;
5220 ice_config.presume_writable_when_fully_relayed =
5221 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005222 ice_config.ice_check_interval_strong_connectivity =
5223 config.ice_check_interval_strong_connectivity;
5224 ice_config.ice_check_interval_weak_connectivity =
5225 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005226 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005227 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005228 ice_config.regather_all_networks_interval_range =
5229 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005230 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005231 return ice_config;
5232}
5233
Steve Anton75737c02017-11-06 10:37:17 -08005234bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5235 std::string* track_id) {
5236 if (!local_description()) {
5237 return false;
5238 }
5239 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5240 track_id);
5241}
5242
5243bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5244 std::string* track_id) {
5245 if (!remote_description()) {
5246 return false;
5247 }
5248 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5249 track_id);
5250}
5251
5252bool PeerConnection::SendData(const cricket::SendDataParams& params,
5253 const rtc::CopyOnWriteBuffer& payload,
5254 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005255 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5256 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5257 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005258 return false;
5259 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005260 if (media_transport_) {
5261 SendDataParams send_params;
5262 send_params.type = ToWebrtcDataMessageType(params.type);
5263 send_params.ordered = params.ordered;
5264 if (params.max_rtx_count >= 0) {
5265 send_params.max_rtx_count = params.max_rtx_count;
5266 } else if (params.max_rtx_ms >= 0) {
5267 send_params.max_rtx_ms = params.max_rtx_ms;
5268 }
5269 return media_transport_->SendData(params.sid, send_params, payload).ok();
5270 }
Steve Anton75737c02017-11-06 10:37:17 -08005271 return rtp_data_channel_
5272 ? rtp_data_channel_->SendData(params, payload, result)
5273 : network_thread()->Invoke<bool>(
5274 RTC_FROM_HERE,
5275 Bind(&cricket::SctpTransportInternal::SendData,
5276 sctp_transport_.get(), params, payload, result));
5277}
5278
5279bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005280 RTC_DCHECK_RUN_ON(signaling_thread());
5281 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005282 // Don't log an error here, because DataChannels are expected to call
5283 // ConnectDataChannel in this state. It's the only way to initially tell
5284 // whether or not the underlying transport is ready.
5285 return false;
5286 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005287 if (media_transport_) {
5288 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5289 &DataChannel::OnChannelReady);
5290 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5291 &DataChannel::OnDataReceived);
5292 SignalMediaTransportChannelClosing_s.connect(
5293 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5294 SignalMediaTransportChannelClosed_s.connect(
5295 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5296 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005297 rtp_data_channel_->SignalReadyToSendData.connect(
5298 webrtc_data_channel, &DataChannel::OnChannelReady);
5299 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5300 &DataChannel::OnDataReceived);
5301 } else {
5302 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5303 &DataChannel::OnChannelReady);
5304 SignalSctpDataReceived.connect(webrtc_data_channel,
5305 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005306 SignalSctpClosingProcedureStartedRemotely.connect(
5307 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5308 SignalSctpClosingProcedureComplete.connect(
5309 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005310 }
5311 return true;
5312}
5313
5314void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005315 RTC_DCHECK_RUN_ON(signaling_thread());
5316 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005317 RTC_LOG(LS_ERROR)
5318 << "DisconnectDataChannel called when rtp_data_channel_ and "
5319 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005320 return;
5321 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005322 if (media_transport_) {
5323 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5324 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5325 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5326 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5327 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005328 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5329 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5330 } else {
5331 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5332 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005333 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5334 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005335 }
5336}
5337
5338void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005339 if (media_transport_) {
5340 // No-op. Media transport does not need to add streams.
5341 return;
5342 }
Steve Anton75737c02017-11-06 10:37:17 -08005343 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005344 RTC_LOG(LS_ERROR)
5345 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005346 return;
5347 }
5348 network_thread()->Invoke<void>(
5349 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5350 sctp_transport_.get(), sid));
5351}
5352
5353void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005354 if (media_transport_) {
5355 media_transport_->CloseChannel(sid);
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) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005360 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005361 return;
5362 }
5363 network_thread()->Invoke<void>(
5364 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5365 sctp_transport_.get(), sid));
5366}
5367
5368bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005369 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005370 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005371 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005372 sctp_ready_to_send_data_;
5373}
5374
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005375void PeerConnection::OnDataReceived(int channel_id,
5376 DataMessageType type,
5377 const rtc::CopyOnWriteBuffer& buffer) {
5378 cricket::ReceiveDataParams params;
5379 params.sid = channel_id;
5380 params.type = ToCricketDataMessageType(type);
5381 media_transport_invoker_->AsyncInvoke<void>(
5382 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5383 RTC_DCHECK_RUN_ON(signaling_thread());
5384 if (!HandleOpenMessage_s(params, buffer)) {
5385 SignalMediaTransportReceivedData_s(params, buffer);
5386 }
5387 });
5388}
5389
5390void PeerConnection::OnChannelClosing(int channel_id) {
5391 media_transport_invoker_->AsyncInvoke<void>(
5392 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5393 RTC_DCHECK_RUN_ON(signaling_thread());
5394 SignalMediaTransportChannelClosing_s(channel_id);
5395 });
5396}
5397
5398void PeerConnection::OnChannelClosed(int channel_id) {
5399 media_transport_invoker_->AsyncInvoke<void>(
5400 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5401 RTC_DCHECK_RUN_ON(signaling_thread());
5402 SignalMediaTransportChannelClosed_s(channel_id);
5403 });
5404}
5405
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005406absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005407 if (sctp_mid_ && transport_controller_) {
5408 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5409 if (dtls_transport) {
5410 return dtls_transport->transport_name();
5411 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005412 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005413 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005414 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005415}
5416
Qingsi Wang72a43a12018-02-20 16:03:18 -08005417cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5418 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005419 network_thread()->Invoke<void>(
5420 RTC_FROM_HERE,
5421 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5422 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005423 return candidate_states_list;
5424}
5425
Steve Anton5dfde182018-02-06 10:34:40 -08005426std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5427 const {
5428 std::map<std::string, std::string> transport_names_by_mid;
5429 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005430 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005431 if (channel) {
5432 transport_names_by_mid[channel->content_name()] =
5433 channel->transport_name();
5434 }
Steve Anton75737c02017-11-06 10:37:17 -08005435 }
Steve Anton5dfde182018-02-06 10:34:40 -08005436 if (rtp_data_channel_) {
5437 transport_names_by_mid[rtp_data_channel_->content_name()] =
5438 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005439 }
5440 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005441 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005442 RTC_DCHECK(transport_name);
5443 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005444 }
Steve Anton5dfde182018-02-06 10:34:40 -08005445 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005446}
5447
Steve Anton5dfde182018-02-06 10:34:40 -08005448std::map<std::string, cricket::TransportStats>
5449PeerConnection::GetTransportStatsByNames(
5450 const std::set<std::string>& transport_names) {
5451 if (!network_thread()->IsCurrent()) {
5452 return network_thread()
5453 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5454 RTC_FROM_HERE,
5455 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005456 }
Steve Anton5dfde182018-02-06 10:34:40 -08005457 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5458 for (const std::string& transport_name : transport_names) {
5459 cricket::TransportStats transport_stats;
5460 bool success =
5461 transport_controller_->GetStats(transport_name, &transport_stats);
5462 if (success) {
5463 transport_stats_by_name[transport_name] = std::move(transport_stats);
5464 } else {
5465 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5466 << transport_name;
5467 }
5468 }
5469 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005470}
5471
5472bool PeerConnection::GetLocalCertificate(
5473 const std::string& transport_name,
5474 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005475 if (!certificate) {
5476 return false;
5477 }
5478 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5479 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005480}
5481
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005482std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005483 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005484 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005485}
5486
5487cricket::DataChannelType PeerConnection::data_channel_type() const {
5488 return data_channel_type_;
5489}
5490
5491bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5492 return pending_ice_restarts_.find(content_name) !=
5493 pending_ice_restarts_.end();
5494}
5495
Steve Anton75737c02017-11-06 10:37:17 -08005496bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5497 return transport_controller_->NeedsIceRestart(content_name);
5498}
5499
5500void PeerConnection::OnCertificateReady(
5501 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5502 transport_controller_->SetLocalCertificate(certificate);
5503}
5504
5505void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005506 SetSessionError(SessionError::kTransport,
5507 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005508}
5509
Alex Loiko9289eda2018-11-23 16:18:59 +00005510void PeerConnection::OnTransportControllerConnectionState(
5511 cricket::IceConnectionState state) {
5512 switch (state) {
5513 case cricket::kIceConnectionConnecting:
5514 // If the current state is Connected or Completed, then there were
5515 // writable channels but now there are not, so the next state must
5516 // be Disconnected.
5517 // kIceConnectionConnecting is currently used as the default,
5518 // un-connected state by the TransportController, so its only use is
5519 // detecting disconnections.
5520 if (ice_connection_state_ ==
5521 PeerConnectionInterface::kIceConnectionConnected ||
5522 ice_connection_state_ ==
5523 PeerConnectionInterface::kIceConnectionCompleted) {
5524 SetIceConnectionState(
5525 PeerConnectionInterface::kIceConnectionDisconnected);
5526 }
5527 break;
5528 case cricket::kIceConnectionFailed:
5529 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5530 break;
5531 case cricket::kIceConnectionConnected:
5532 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5533 "all transports are writable.";
5534 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5535 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5536 break;
5537 case cricket::kIceConnectionCompleted:
5538 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5539 "all transports are complete.";
5540 if (ice_connection_state_ !=
5541 PeerConnectionInterface::kIceConnectionConnected) {
5542 // If jumping directly from "checking" to "connected",
5543 // signal "connected" first.
5544 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5545 }
5546 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5547 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5548 ReportTransportStats();
5549 break;
5550 default:
5551 RTC_NOTREACHED();
5552 }
5553}
5554
Steve Anton75737c02017-11-06 10:37:17 -08005555void PeerConnection::OnTransportControllerCandidatesGathered(
5556 const std::string& transport_name,
5557 const cricket::Candidates& candidates) {
5558 RTC_DCHECK(signaling_thread()->IsCurrent());
5559 int sdp_mline_index;
5560 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005561 RTC_LOG(LS_ERROR)
5562 << "OnTransportControllerCandidatesGathered: content name "
5563 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005564 return;
5565 }
5566
5567 for (cricket::Candidates::const_iterator citer = candidates.begin();
5568 citer != candidates.end(); ++citer) {
5569 // Use transport_name as the candidate media id.
5570 std::unique_ptr<JsepIceCandidate> candidate(
5571 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5572 if (local_description()) {
5573 mutable_local_description()->AddCandidate(candidate.get());
5574 }
5575 OnIceCandidate(std::move(candidate));
5576 }
5577}
5578
5579void PeerConnection::OnTransportControllerCandidatesRemoved(
5580 const std::vector<cricket::Candidate>& candidates) {
5581 RTC_DCHECK(signaling_thread()->IsCurrent());
5582 // Sanity check.
5583 for (const cricket::Candidate& candidate : candidates) {
5584 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005585 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005586 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005587 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005588 return;
5589 }
5590 }
5591
5592 if (local_description()) {
5593 mutable_local_description()->RemoveCandidates(candidates);
5594 }
5595 OnIceCandidatesRemoved(candidates);
5596}
5597
5598void PeerConnection::OnTransportControllerDtlsHandshakeError(
5599 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005600 RTC_HISTOGRAM_ENUMERATION(
5601 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5602 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005603}
5604
Steve Antoned10bd92017-12-05 10:52:59 -08005605void PeerConnection::EnableSending() {
5606 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005607 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005608 if (channel && !channel->enabled()) {
5609 channel->Enable(true);
5610 }
Steve Anton75737c02017-11-06 10:37:17 -08005611 }
5612
Steve Anton4171afb2017-11-20 10:20:22 -08005613 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005614 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005615 }
Steve Anton75737c02017-11-06 10:37:17 -08005616}
5617
5618// Returns the media index for a local ice candidate given the content name.
5619bool PeerConnection::GetLocalCandidateMediaIndex(
5620 const std::string& content_name,
5621 int* sdp_mline_index) {
5622 if (!local_description() || !sdp_mline_index) {
5623 return false;
5624 }
5625
5626 bool content_found = false;
5627 const ContentInfos& contents = local_description()->description()->contents();
5628 for (size_t index = 0; index < contents.size(); ++index) {
5629 if (contents[index].name == content_name) {
5630 *sdp_mline_index = static_cast<int>(index);
5631 content_found = true;
5632 break;
5633 }
5634 }
5635 return content_found;
5636}
5637
5638bool PeerConnection::UseCandidatesInSessionDescription(
5639 const SessionDescriptionInterface* remote_desc) {
5640 if (!remote_desc) {
5641 return true;
5642 }
5643 bool ret = true;
5644
5645 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5646 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5647 for (size_t n = 0; n < candidates->count(); ++n) {
5648 const IceCandidateInterface* candidate = candidates->at(n);
5649 bool valid = false;
5650 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5651 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005652 RTC_LOG(LS_INFO)
5653 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005654 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005655 }
5656 continue;
5657 }
5658 ret = UseCandidate(candidate);
5659 if (!ret) {
5660 break;
5661 }
5662 }
5663 }
5664 return ret;
5665}
5666
5667bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5668 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5669 size_t remote_content_size =
5670 remote_description()->description()->contents().size();
5671 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005672 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005673 return false;
5674 }
5675
5676 cricket::ContentInfo content =
5677 remote_description()->description()->contents()[mediacontent_index];
5678 std::vector<cricket::Candidate> candidates;
5679 candidates.push_back(candidate->candidate());
5680 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005681 RTCError error =
5682 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005683 if (error.ok()) {
5684 // Candidates successfully submitted for checking.
5685 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5686 ice_connection_state_ ==
5687 PeerConnectionInterface::kIceConnectionDisconnected) {
5688 // If state is New, then the session has just gotten its first remote ICE
5689 // candidates, so go to Checking.
5690 // If state is Disconnected, the session is re-using old candidates or
5691 // receiving additional ones, so go to Checking.
5692 // If state is Connected, stay Connected.
5693 // TODO(bemasc): If state is Connected, and the new candidates are for a
5694 // newly added transport, then the state actually _should_ move to
5695 // checking. Add a way to distinguish that case.
5696 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5697 }
5698 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005699 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005700 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
5702 return true;
5703}
5704
5705void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005706 // Destroy video channel first since it may have a pointer to the
5707 // voice channel.
5708 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005709 if (!video_info || video_info->rejected) {
5710 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005711 }
5712
Steve Anton6fec8802017-12-04 10:37:29 -08005713 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5714 if (!audio_info || audio_info->rejected) {
5715 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005716 }
5717
5718 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5719 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005720 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005721 }
5722}
5723
Steve Antondcc3c022017-12-22 16:02:54 -08005724RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5725 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005726 const cricket::ContentGroup* bundle_group = nullptr;
5727 if (configuration_.bundle_policy ==
5728 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005729 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005730 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005731 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5732 "max-bundle configured but session description "
5733 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005734 }
5735 }
Steve Antondcc3c022017-12-22 16:02:54 -08005736 return std::move(bundle_group);
5737}
5738
5739RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005740 // Creating the media channels. Transports should already have been created
5741 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005742 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005743 if (voice && !voice->rejected &&
5744 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005745 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005746 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005747 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5748 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005749 }
5750 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5751 }
5752
Steve Antondcc3c022017-12-22 16:02:54 -08005753 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005754 if (video && !video->rejected &&
5755 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005756 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005757 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005758 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5759 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005761 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005762 }
5763
Steve Antondcc3c022017-12-22 16:02:54 -08005764 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005765 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005766 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005767 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005768 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5769 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005770 }
5771 }
5772
Steve Anton8a006912017-12-04 15:25:56 -08005773 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005774}
5775
Steve Anton4171afb2017-11-20 10:20:22 -08005776// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005777cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005778 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005779 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005780 MediaTransportInterface* media_transport = nullptr;
5781 if (configuration_.use_media_transport) {
5782 media_transport = GetMediaTransport(mid);
5783 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005784
Steve Anton75737c02017-11-06 10:37:17 -08005785 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005786 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005787 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5788 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005789 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005790 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005791 }
Steve Anton75737c02017-11-06 10:37:17 -08005792 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5793 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005794 voice_channel->SignalSentPacket.connect(this,
5795 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005796 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005797
Steve Antoneda6ccd2017-12-04 10:21:55 -08005798 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005799}
5800
Steve Anton4171afb2017-11-20 10:20:22 -08005801// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005802cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005803 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005804 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5805
5806 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005807 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005808 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005809 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5810 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005811 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005812 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005813 }
Steve Anton75737c02017-11-06 10:37:17 -08005814 video_channel->SignalDtlsSrtpSetupFailure.connect(
5815 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005816 video_channel->SignalSentPacket.connect(this,
5817 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005818 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005819
Steve Antoneda6ccd2017-12-04 10:21:55 -08005820 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005821}
5822
Zhi Huange830e682018-03-30 10:48:35 -07005823bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005824 switch (data_channel_type_) {
5825 case cricket::DCT_MEDIA_TRANSPORT:
5826 if (network_thread()->Invoke<bool>(
5827 RTC_FROM_HERE,
5828 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5829 this, mid))) {
5830 for (const auto& channel : sctp_data_channels_) {
5831 channel->OnTransportChannelCreated();
5832 }
5833 return true;
5834 }
Steve Anton75737c02017-11-06 10:37:17 -08005835 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005836 case cricket::DCT_SCTP:
5837 if (!sctp_factory_) {
5838 RTC_LOG(LS_ERROR)
5839 << "Trying to create SCTP transport, but didn't compile with "
5840 "SCTP support (HAVE_SCTP)";
5841 return false;
5842 }
5843 if (!network_thread()->Invoke<bool>(
5844 RTC_FROM_HERE,
5845 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5846 return false;
5847 }
5848 for (const auto& channel : sctp_data_channels_) {
5849 channel->OnTransportChannelCreated();
5850 }
5851 return true;
5852 case cricket::DCT_RTP:
5853 default:
5854 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5855 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5856 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5857 SrtpRequired(), GetCryptoOptions());
5858 if (!rtp_data_channel_) {
5859 return false;
5860 }
5861 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5862 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5863 rtp_data_channel_->SignalSentPacket.connect(
5864 this, &PeerConnection::OnSentPacket_w);
5865 rtp_data_channel_->SetRtpTransport(rtp_transport);
5866 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005867 }
5868
Steve Anton75737c02017-11-06 10:37:17 -08005869 return true;
5870}
5871
5872Call::Stats PeerConnection::GetCallStats() {
5873 if (!worker_thread()->IsCurrent()) {
5874 return worker_thread()->Invoke<Call::Stats>(
5875 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5876 }
5877 if (call_) {
5878 return call_->GetStats();
5879 } else {
5880 return Call::Stats();
5881 }
5882}
5883
Zhi Huange830e682018-03-30 10:48:35 -07005884bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005885 RTC_DCHECK(network_thread()->IsCurrent());
5886 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005887 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005888 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005889 RTC_DCHECK(dtls_transport);
5890 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005891 RTC_DCHECK(sctp_transport_);
5892 sctp_invoker_.reset(new rtc::AsyncInvoker());
5893 sctp_transport_->SignalReadyToSendData.connect(
5894 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5895 sctp_transport_->SignalDataReceived.connect(
5896 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005897 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5898 // another thread. Would be nice if there was a helper class similar to
5899 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5900 // code.
5901 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5902 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5903 sctp_transport_->SignalClosingProcedureComplete.connect(
5904 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005905 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005906 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005907 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005908}
5909
5910void PeerConnection::DestroySctpTransport_n() {
5911 RTC_DCHECK(network_thread()->IsCurrent());
5912 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005913 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005914 sctp_invoker_.reset(nullptr);
5915 sctp_ready_to_send_data_ = false;
5916}
5917
5918void PeerConnection::OnSctpTransportReadyToSendData_n() {
5919 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5920 RTC_DCHECK(network_thread()->IsCurrent());
5921 // Note: Cannot use rtc::Bind here because it will grab a reference to
5922 // PeerConnection and potentially cause PeerConnection to live longer than
5923 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5924 // be destroyed before PeerConnection is destroyed, and at that point all
5925 // pending tasks will be cleared.
5926 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5927 OnSctpTransportReadyToSendData_s(true);
5928 });
5929}
5930
5931void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5932 RTC_DCHECK(signaling_thread()->IsCurrent());
5933 sctp_ready_to_send_data_ = ready;
5934 SignalSctpReadyToSendData(ready);
5935}
5936
5937void PeerConnection::OnSctpTransportDataReceived_n(
5938 const cricket::ReceiveDataParams& params,
5939 const rtc::CopyOnWriteBuffer& payload) {
5940 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5941 RTC_DCHECK(network_thread()->IsCurrent());
5942 // Note: Cannot use rtc::Bind here because it will grab a reference to
5943 // PeerConnection and potentially cause PeerConnection to live longer than
5944 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5945 // be destroyed before PeerConnection is destroyed, and at that point all
5946 // pending tasks will be cleared.
5947 sctp_invoker_->AsyncInvoke<void>(
5948 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5949 OnSctpTransportDataReceived_s(params, payload);
5950 });
5951}
5952
5953void PeerConnection::OnSctpTransportDataReceived_s(
5954 const cricket::ReceiveDataParams& params,
5955 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005956 RTC_DCHECK_RUN_ON(signaling_thread());
5957 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005958 SignalSctpDataReceived(params, payload);
5959 }
5960}
5961
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005962void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005963 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5964 RTC_DCHECK(network_thread()->IsCurrent());
5965 sctp_invoker_->AsyncInvoke<void>(
5966 RTC_FROM_HERE, signaling_thread(),
5967 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005968 &SignalSctpClosingProcedureStartedRemotely, sid));
5969}
5970
5971void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5972 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5973 RTC_DCHECK(network_thread()->IsCurrent());
5974 sctp_invoker_->AsyncInvoke<void>(
5975 RTC_FROM_HERE, signaling_thread(),
5976 rtc::Bind(&sigslot::signal1<int>::operator(),
5977 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005978}
5979
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005980bool PeerConnection::SetupMediaTransportForDataChannels_n(
5981 const std::string& mid) {
5982 media_transport_ = transport_controller_->GetMediaTransport(mid);
5983 if (!media_transport_) {
5984 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
5985 return false;
5986 }
5987
5988 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
5989 media_transport_->SetDataSink(this);
5990 media_transport_data_mid_ = mid;
5991 transport_controller_->SignalMediaTransportStateChanged.connect(
5992 this, &PeerConnection::OnMediaTransportStateChanged_n);
5993 // Check the initial state right away, in case transport is already writable.
5994 OnMediaTransportStateChanged_n();
5995 return true;
5996}
5997
5998void PeerConnection::TeardownMediaTransportForDataChannels_n() {
5999 if (!media_transport_) {
6000 return;
6001 }
6002 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6003 media_transport_data_mid_.reset();
6004 media_transport_->SetDataSink(nullptr);
6005 media_transport_invoker_ = nullptr;
6006 media_transport_ = nullptr;
6007}
6008
6009void PeerConnection::OnMediaTransportStateChanged_n() {
6010 if (!media_transport_data_mid_ ||
6011 transport_controller_->GetMediaTransportState(
6012 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6013 return;
6014 }
6015 media_transport_invoker_->AsyncInvoke<void>(
6016 RTC_FROM_HERE, signaling_thread(), [this] {
6017 RTC_DCHECK_RUN_ON(signaling_thread());
6018 media_transport_ready_to_send_data_ = true;
6019 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6020 });
6021}
6022
Steve Anton75737c02017-11-06 10:37:17 -08006023// Returns false if bundle is enabled and rtcp_mux is disabled.
6024bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6025 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6026 if (!bundle_enabled)
6027 return true;
6028
6029 const cricket::ContentGroup* bundle_group =
6030 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6031 RTC_DCHECK(bundle_group != NULL);
6032
6033 const cricket::ContentInfos& contents = desc->contents();
6034 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6035 citer != contents.end(); ++citer) {
6036 const cricket::ContentInfo* content = (&*citer);
6037 RTC_DCHECK(content != NULL);
6038 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006039 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006040 if (!HasRtcpMuxEnabled(content))
6041 return false;
6042 }
6043 }
6044 // RTCP-MUX is enabled in all the contents.
6045 return true;
6046}
6047
6048bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006049 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006050}
6051
Steve Anton8a006912017-12-04 15:25:56 -08006052RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006053 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006054 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006055 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006056 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006057 }
6058
6059 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006060 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006061 }
6062
Steve Anton3828c062017-12-06 10:34:51 -08006063 SdpType type = sdesc->GetType();
6064 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6065 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006066 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006067 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006068 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006069 }
6070
6071 // Verify crypto settings.
6072 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006073 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6074 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006075 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006076 if (!crypto_error.ok()) {
6077 return crypto_error;
6078 }
Steve Anton75737c02017-11-06 10:37:17 -08006079 }
6080
6081 // Verify ice-ufrag and ice-pwd.
6082 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006083 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6084 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006085 }
6086
6087 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006088 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6089 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006090 }
6091
6092 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6093 // m-lines that do not rtcp-mux enabled.
6094
6095 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006096 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006097 // With an answer we want to compare the new answer session description with
6098 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006099 const cricket::SessionDescription* offer_desc =
6100 (source == cricket::CS_LOCAL) ? remote_description()->description()
6101 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006102 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6103 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6104 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006105 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6106 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006107 }
6108 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006109 // The re-offers should respect the order of m= sections in current
6110 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006111 // With a re-offer, either the current local or current remote descriptions
6112 // could be the most up to date, so we would like to check against both of
6113 // them if they exist. It could be the case that one of them has a 0 port
6114 // for a media section, but the other does not. This is important to check
6115 // against in the case that we are recycling an m= section.
6116 const cricket::SessionDescription* current_desc = nullptr;
6117 const cricket::SessionDescription* secondary_current_desc = nullptr;
6118 if (local_description()) {
6119 current_desc = local_description()->description();
6120 if (remote_description()) {
6121 secondary_current_desc = remote_description()->description();
6122 }
6123 } else if (remote_description()) {
6124 current_desc = remote_description()->description();
6125 }
Steve Anton75737c02017-11-06 10:37:17 -08006126 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006127 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6128 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006129 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6130 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006131 }
6132 }
6133
Steve Antonba42e992018-04-09 14:10:01 -07006134 if (IsUnifiedPlan()) {
6135 // Ensure that each audio and video media section has at most one
6136 // "StreamParams". This will return an error if receiving a session
6137 // description from a "Plan B" endpoint which adds multiple tracks of the
6138 // same type. With Unified Plan, there can only be at most one track per
6139 // media section.
6140 for (const ContentInfo& content : sdesc->description()->contents()) {
6141 const MediaContentDescription& desc = *content.description;
6142 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6143 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6144 desc.streams().size() > 1u) {
6145 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6146 "Media section has more than one track specified "
6147 "with a=ssrc lines which is not supported with "
6148 "Unified Plan.");
6149 }
6150 }
6151 }
6152
Steve Anton8a006912017-12-04 15:25:56 -08006153 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006154}
6155
Steve Anton3828c062017-12-06 10:34:51 -08006156bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006157 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006158 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006159 return (state == PeerConnectionInterface::kStable) ||
6160 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006161 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006162 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006163 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6164 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6165 }
6166}
6167
Steve Anton3828c062017-12-06 10:34:51 -08006168bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006169 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006170 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006171 return (state == PeerConnectionInterface::kStable) ||
6172 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006173 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006174 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006175 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6176 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6177 }
6178}
6179
Steve Antonf8470812017-12-04 10:46:21 -08006180const char* PeerConnection::SessionErrorToString(SessionError error) const {
6181 switch (error) {
6182 case SessionError::kNone:
6183 return "ERROR_NONE";
6184 case SessionError::kContent:
6185 return "ERROR_CONTENT";
6186 case SessionError::kTransport:
6187 return "ERROR_TRANSPORT";
6188 }
6189 RTC_NOTREACHED();
6190 return "";
6191}
6192
Steve Anton75737c02017-11-06 10:37:17 -08006193std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006194 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006195 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6196 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006197 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006198}
6199
Steve Anton8e20f172018-03-06 10:55:04 -08006200void PeerConnection::ReportSdpFormatReceived(
6201 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006202 int num_audio_mlines = 0;
6203 int num_video_mlines = 0;
6204 int num_audio_tracks = 0;
6205 int num_video_tracks = 0;
6206 for (const ContentInfo& content : remote_offer.description()->contents()) {
6207 cricket::MediaType media_type = content.media_description()->type();
6208 int num_tracks = std::max(
6209 1, static_cast<int>(content.media_description()->streams().size()));
6210 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6211 num_audio_mlines += 1;
6212 num_audio_tracks += num_tracks;
6213 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6214 num_video_mlines += 1;
6215 num_video_tracks += num_tracks;
6216 }
6217 }
6218 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6219 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6220 format = kSdpFormatReceivedComplexUnifiedPlan;
6221 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6222 format = kSdpFormatReceivedComplexPlanB;
6223 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6224 format = kSdpFormatReceivedSimple;
6225 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006226 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6227 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006228}
6229
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006230void PeerConnection::NoteUsageEvent(UsageEvent event) {
6231 RTC_DCHECK_RUN_ON(signaling_thread());
6232 usage_event_accumulator_ |= static_cast<int>(event);
6233}
6234
6235void PeerConnection::ReportUsagePattern() const {
6236 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006237 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6238 usage_event_accumulator_,
6239 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006240 const int bad_bits =
6241 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6242 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6243 const int good_bits =
6244 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6245 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6246 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6247 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6248 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006249 // If called after close(), we can't report, because observer may have
6250 // been deallocated, and therefore pointer is null. Write to log instead.
6251 if (observer_) {
6252 Observer()->OnInterestingUsage(usage_event_accumulator_);
6253 } else {
6254 RTC_LOG(LS_INFO) << "Interesting usage signature "
6255 << usage_event_accumulator_
6256 << " observed after observer shutdown";
6257 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006258 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006259}
6260
Steve Anton0ffaaa22018-02-23 10:31:30 -08006261void PeerConnection::ReportNegotiatedSdpSemantics(
6262 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006263 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006264 switch (answer.description()->msid_signaling()) {
6265 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006266 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006267 break;
6268 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006269 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006270 break;
6271 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006272 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006273 break;
6274 case cricket::kMsidSignalingMediaSection |
6275 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006276 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006277 break;
6278 default:
6279 RTC_NOTREACHED();
6280 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006281 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6282 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006283}
6284
Steve Anton75737c02017-11-06 10:37:17 -08006285// We need to check the local/remote description for the Transport instead of
6286// the session, because a new Transport added during renegotiation may have
6287// them unset while the session has them set from the previous negotiation.
6288// Not doing so may trigger the auto generation of transport description and
6289// mess up DTLS identity information, ICE credential, etc.
6290bool PeerConnection::ReadyToUseRemoteCandidate(
6291 const IceCandidateInterface* candidate,
6292 const SessionDescriptionInterface* remote_desc,
6293 bool* valid) {
6294 *valid = true;
6295
6296 const SessionDescriptionInterface* current_remote_desc =
6297 remote_desc ? remote_desc : remote_description();
6298
6299 if (!current_remote_desc) {
6300 return false;
6301 }
6302
6303 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6304 size_t remote_content_size =
6305 current_remote_desc->description()->contents().size();
6306 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006307 RTC_LOG(LS_ERROR)
6308 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6309 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006310
6311 *valid = false;
6312 return false;
6313 }
6314
6315 cricket::ContentInfo content =
6316 current_remote_desc->description()->contents()[mediacontent_index];
6317
6318 const std::string transport_name = GetTransportName(content.name);
6319 if (transport_name.empty()) {
6320 return false;
6321 }
Zhi Huange830e682018-03-30 10:48:35 -07006322 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006323}
6324
6325bool PeerConnection::SrtpRequired() const {
6326 return dtls_enabled_ ||
6327 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6328}
6329
6330void PeerConnection::OnTransportControllerGatheringState(
6331 cricket::IceGatheringState state) {
6332 RTC_DCHECK(signaling_thread()->IsCurrent());
6333 if (state == cricket::kIceGatheringGathering) {
6334 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6335 } else if (state == cricket::kIceGatheringComplete) {
6336 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6337 }
6338}
6339
6340void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006341 std::map<std::string, std::set<cricket::MediaType>>
6342 media_types_by_transport_name;
6343 for (auto transceiver : transceivers_) {
6344 if (transceiver->internal()->channel()) {
6345 const std::string& transport_name =
6346 transceiver->internal()->channel()->transport_name();
6347 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006348 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006349 }
Steve Anton75737c02017-11-06 10:37:17 -08006350 }
6351 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006352 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6353 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006354 }
Zhi Huange830e682018-03-30 10:48:35 -07006355
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006356 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006357 if (transport_name) {
6358 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006359 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006360 }
Zhi Huange830e682018-03-30 10:48:35 -07006361
Steve Antonc7b964c2018-02-01 14:39:45 -08006362 for (const auto& entry : media_types_by_transport_name) {
6363 const std::string& transport_name = entry.first;
6364 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006365 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006366 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006367 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006368 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006369 }
6370 }
6371}
6372// Walk through the ConnectionInfos to gather best connection usage
6373// for IPv4 and IPv6.
6374void PeerConnection::ReportBestConnectionState(
6375 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006376 for (const cricket::TransportChannelStats& channel_stats :
6377 stats.channel_stats) {
6378 for (const cricket::ConnectionInfo& connection_info :
6379 channel_stats.connection_infos) {
6380 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006381 continue;
6382 }
6383
Steve Antonc7b964c2018-02-01 14:39:45 -08006384 const cricket::Candidate& local = connection_info.local_candidate;
6385 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006386
6387 // Increment the counter for IceCandidatePairType.
6388 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6389 (local.type() == RELAY_PORT_TYPE &&
6390 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006391 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6392 GetIceCandidatePairCounter(local, remote),
6393 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006394 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006395 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6396 GetIceCandidatePairCounter(local, remote),
6397 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006398 } else {
6399 RTC_CHECK(0);
6400 }
Steve Anton75737c02017-11-06 10:37:17 -08006401
6402 // Increment the counter for IP type.
6403 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006404 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6405 kBestConnections_IPv4,
6406 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006407 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006408 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6409 kBestConnections_IPv6,
6410 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006411 } else {
6412 RTC_CHECK(0);
6413 }
6414
6415 return;
6416 }
6417 }
6418}
6419
6420void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006421 const cricket::TransportStats& stats,
6422 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006423 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6424 return;
6425 }
6426
6427 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6428 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6429 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6430 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6431 return;
6432 }
6433
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006434 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6435 for (cricket::MediaType media_type : media_types) {
6436 switch (media_type) {
6437 case cricket::MEDIA_TYPE_AUDIO:
6438 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6439 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6440 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6441 break;
6442 case cricket::MEDIA_TYPE_VIDEO:
6443 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6444 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6445 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6446 break;
6447 case cricket::MEDIA_TYPE_DATA:
6448 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6449 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6450 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6451 break;
6452 default:
6453 RTC_NOTREACHED();
6454 continue;
6455 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006456 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006457 }
6458
6459 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6460 for (cricket::MediaType media_type : media_types) {
6461 switch (media_type) {
6462 case cricket::MEDIA_TYPE_AUDIO:
6463 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6464 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6465 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6466 break;
6467 case cricket::MEDIA_TYPE_VIDEO:
6468 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6469 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6470 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6471 break;
6472 case cricket::MEDIA_TYPE_DATA:
6473 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6474 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6475 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6476 break;
6477 default:
6478 RTC_NOTREACHED();
6479 continue;
6480 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006481 }
Steve Anton75737c02017-11-06 10:37:17 -08006482 }
6483}
6484
6485void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6486 RTC_DCHECK(worker_thread()->IsCurrent());
6487 RTC_DCHECK(call_);
6488 call_->OnSentPacket(sent_packet);
6489}
6490
6491const std::string PeerConnection::GetTransportName(
6492 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006493 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006494 if (channel) {
6495 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006496 }
Steve Anton6fec8802017-12-04 10:37:29 -08006497 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006498 RTC_DCHECK(sctp_mid_);
6499 if (content_name == *sctp_mid_) {
6500 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006501 }
6502 }
6503 // Return an empty string if failed to retrieve the transport name.
6504 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006505}
6506
Steve Anton6fec8802017-12-04 10:37:29 -08006507void PeerConnection::DestroyTransceiverChannel(
6508 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6509 transceiver) {
6510 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006511
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006512 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006513 if (channel) {
6514 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006515 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006516 }
6517}
6518
6519void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006520 if (rtp_data_channel_) {
6521 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006522 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006523 rtp_data_channel_ = nullptr;
6524 }
6525
6526 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6527 // grab a reference to this PeerConnection. If this is called from the
6528 // PeerConnection destructor, the RefCountedObject vtable will have already
6529 // been destroyed (since it is a subclass of PeerConnection) and using
6530 // rtc::Bind will cause "Pure virtual function called" error to appear.
6531
6532 if (sctp_transport_) {
6533 OnDataChannelDestroyed();
6534 network_thread()->Invoke<void>(RTC_FROM_HERE,
6535 [this] { DestroySctpTransport_n(); });
6536 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006537
6538 if (media_transport_) {
6539 OnDataChannelDestroyed();
6540 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6541 RTC_DCHECK_RUN_ON(network_thread());
6542 TeardownMediaTransportForDataChannels_n();
6543 });
6544 }
Steve Anton6fec8802017-12-04 10:37:29 -08006545}
6546
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006547void PeerConnection::DestroyChannelInterface(
6548 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006549 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006550 switch (channel->media_type()) {
6551 case cricket::MEDIA_TYPE_AUDIO:
6552 channel_manager()->DestroyVoiceChannel(
6553 static_cast<cricket::VoiceChannel*>(channel));
6554 break;
6555 case cricket::MEDIA_TYPE_VIDEO:
6556 channel_manager()->DestroyVideoChannel(
6557 static_cast<cricket::VideoChannel*>(channel));
6558 break;
6559 case cricket::MEDIA_TYPE_DATA:
6560 channel_manager()->DestroyRtpDataChannel(
6561 static_cast<cricket::RtpDataChannel*>(channel));
6562 break;
6563 default:
6564 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6565 break;
6566 }
Zhi Huange830e682018-03-30 10:48:35 -07006567}
Steve Anton6fec8802017-12-04 10:37:29 -08006568
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006569bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006570 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006571 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006572 cricket::DtlsTransportInternal* dtls_transport,
6573 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006574 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006575 auto base_channel = GetChannel(mid);
6576 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006577 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006578 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006579 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006580 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006581 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006582
6583 call_->MediaTransportChange(media_transport);
6584
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006585 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006586}
6587
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006588PeerConnectionObserver* PeerConnection::Observer() const {
6589 // In earlier production code, the pointer was not cleared on close,
6590 // which might have led to undefined behavior if the observer was not
6591 // deallocated, or strange crashes if it was.
6592 // We use CHECK in order to catch such behavior if it exists.
6593 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6594 RTC_CHECK(observer_);
6595 return observer_;
6596}
6597
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006598CryptoOptions PeerConnection::GetCryptoOptions() {
6599 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6600 // after it has been removed.
6601 return configuration_.crypto_options.has_value()
6602 ? *configuration_.crypto_options
6603 : factory_->options().crypto_options;
6604}
6605
Harald Alvestrand89061872018-01-02 14:08:34 +01006606void PeerConnection::ClearStatsCache() {
6607 if (stats_collector_) {
6608 stats_collector_->ClearCachedStatsReport();
6609 }
6610}
6611
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006612void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006613 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6614 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006615}
6616
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006617} // namespace webrtc