blob: 47ecb4e1c10b99b07c4a91c1281c95adf2d348d1 [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(
Steve Anton75737c02017-11-06 10:37:17 -08001001 this, &PeerConnection::OnTransportControllerConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001002 transport_controller_->SignalStandardizedIceConnectionState.connect(
1003 this, &PeerConnection::SetStandardizedIceConnectionState);
1004 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 }
1720 // If there is no |internal_sender| then |selector| is either null or does not
1721 // 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 }
1748 // If there is no |internal_receiver| then |selector| is either null or does
1749 // 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
Jonas Olsson635474e2018-10-18 15:58:17 +02001765PeerConnectionInterface::IceConnectionState
1766PeerConnection::standardized_ice_connection_state() {
1767 return standardized_ice_connection_state_;
1768}
1769
1770PeerConnectionInterface::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
deadbeef293e9262017-01-11 12:28:30 -08003000 // The simplest (and most future-compatible) way to tell if the config was
3001 // modified in an invalid way is to copy each property we do support
3002 // modifying, then use operator==. There are far more properties we don't
3003 // support modifying than those we do, and more could be added.
3004 RTCConfiguration modified_config = configuration_;
3005 modified_config.servers = configuration.servers;
3006 modified_config.type = configuration.type;
3007 modified_config.ice_candidate_pool_size =
3008 configuration.ice_candidate_pool_size;
3009 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003010 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003011 modified_config.ice_check_interval_strong_connectivity =
3012 configuration.ice_check_interval_strong_connectivity;
3013 modified_config.ice_check_interval_weak_connectivity =
3014 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003015 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3016 modified_config.ice_unwritable_min_checks =
3017 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003018 modified_config.stun_candidate_keepalive_interval =
3019 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003020 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003021 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003022 modified_config.active_reset_srtp_params =
3023 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003024 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003025 modified_config.use_media_transport_for_data_channels =
3026 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003027 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003028 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003029 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3030 }
3031
Steve Anton038834f2017-07-14 15:59:59 -07003032 // Validate the modified configuration.
3033 RTCError validate_error = ValidateConfiguration(modified_config);
3034 if (!validate_error.ok()) {
3035 return SafeSetError(std::move(validate_error), error);
3036 }
3037
deadbeef293e9262017-01-11 12:28:30 -08003038 // Note that this isn't possible through chromium, since it's an unsigned
3039 // short in WebIDL.
3040 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003041 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003042 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3043 }
3044
3045 // Parse ICE servers before hopping to network thread.
3046 cricket::ServerAddresses stun_servers;
3047 std::vector<cricket::RelayServerConfig> turn_servers;
3048 RTCErrorType parse_error =
3049 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3050 if (parse_error != RTCErrorType::NONE) {
3051 return SafeSetError(parse_error, error);
3052 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003053 // Note if STUN or TURN servers were supplied.
3054 if (!stun_servers.empty()) {
3055 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3056 }
3057 if (!turn_servers.empty()) {
3058 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3059 }
deadbeef293e9262017-01-11 12:28:30 -08003060
3061 // In theory this shouldn't fail.
3062 if (!network_thread()->Invoke<bool>(
3063 RTC_FROM_HERE,
3064 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3065 stun_servers, turn_servers, modified_config.type,
3066 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003067 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003068 modified_config.turn_customizer,
3069 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003070 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003071 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3072 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003073
deadbeefd1a38b52016-12-10 13:15:33 -08003074 // As described in JSEP, calling setConfiguration with new ICE servers or
3075 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3076 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003077 if (modified_config.servers != configuration_.servers ||
3078 modified_config.type != configuration_.type ||
3079 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003080 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003081 }
skvladd1f5fda2017-02-03 16:54:05 -08003082
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003083 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003084 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003085 modified_config.use_media_transport ||
3086 modified_config.use_media_transport_for_data_channels
3087 ? factory_->media_transport_factory()
3088 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003089
Zhi Huangb57e1692018-06-12 11:41:11 -07003090 if (configuration_.active_reset_srtp_params !=
3091 modified_config.active_reset_srtp_params) {
3092 transport_controller_->SetActiveResetSrtpParams(
3093 modified_config.active_reset_srtp_params);
3094 }
3095
deadbeef293e9262017-01-11 12:28:30 -08003096 configuration_ = modified_config;
3097 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003098}
3099
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100bool PeerConnection::AddIceCandidate(
3101 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003102 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003103 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003104 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003105 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003106 return false;
3107 }
Steve Antond25da372017-11-06 14:50:29 -08003108
3109 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003110 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003111 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003112 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003113 return false;
3114 }
3115
3116 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003117 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003118 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003119 return false;
3120 }
3121
3122 bool valid = false;
3123 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3124 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003125 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003126 return false;
3127 }
3128
3129 // Add this candidate to the remote session description.
3130 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003131 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003132 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003133 return false;
3134 }
3135
3136 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003137 bool result = UseCandidate(ice_candidate);
3138 if (result) {
3139 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3140 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3141 } else {
3142 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3143 }
3144 return result;
Steve Antond25da372017-11-06 14:50:29 -08003145 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003146 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003147 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003148 return true;
3149 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003150}
3151
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003152bool PeerConnection::RemoveIceCandidates(
3153 const std::vector<cricket::Candidate>& candidates) {
3154 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003155 if (IsClosed()) {
3156 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3157 return false;
3158 }
3159
Steve Antond25da372017-11-06 14:50:29 -08003160 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003161 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3162 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003163 return false;
3164 }
3165
3166 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003167 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003168 return false;
3169 }
3170
3171 size_t number_removed =
3172 mutable_remote_description()->RemoveCandidates(candidates);
3173 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003174 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003175 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003176 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003177 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003178 }
3179
3180 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003181 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3182 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003183 RTC_LOG(LS_ERROR)
3184 << "RemoveIceCandidates: Error when removing remote candidates: "
3185 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003186 }
3187 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003188}
3189
Niels Möller0c4f7be2018-05-07 14:01:37 +02003190RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003191 if (!worker_thread()->IsCurrent()) {
3192 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003193 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003194 }
3195
Niels Möller0c4f7be2018-05-07 14:01:37 +02003196 const bool has_min = bitrate.min_bitrate_bps.has_value();
3197 const bool has_start = bitrate.start_bitrate_bps.has_value();
3198 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003199 if (has_min && *bitrate.min_bitrate_bps < 0) {
3200 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3201 "min_bitrate_bps <= 0");
3202 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003203 if (has_start) {
3204 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003205 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003206 "start_bitrate_bps < min_bitrate_bps");
3207 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3209 "curent_bitrate_bps < 0");
3210 }
3211 }
3212 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003213 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003214 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003215 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003216 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3218 "max_bitrate_bps < min_bitrate_bps");
3219 } else if (*bitrate.max_bitrate_bps < 0) {
3220 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3221 "max_bitrate_bps < 0");
3222 }
3223 }
3224
zstein4b979802017-06-02 14:37:37 -07003225 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003226 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003227
3228 return RTCError::OK();
3229}
3230
Alex Narest78609d52017-10-20 10:37:47 +02003231void PeerConnection::SetBitrateAllocationStrategy(
3232 std::unique_ptr<rtc::BitrateAllocationStrategy>
3233 bitrate_allocation_strategy) {
3234 rtc::Thread* worker_thread = factory_->worker_thread();
3235 if (!worker_thread->IsCurrent()) {
3236 rtc::BitrateAllocationStrategy* strategy_raw =
3237 bitrate_allocation_strategy.release();
3238 auto functor = [this, strategy_raw]() {
3239 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003240 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003241 };
3242 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3243 return;
3244 }
3245 RTC_DCHECK(call_.get());
3246 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3247}
3248
henrika5f6bf242017-11-01 11:06:56 +01003249void PeerConnection::SetAudioPlayout(bool playout) {
3250 if (!worker_thread()->IsCurrent()) {
3251 worker_thread()->Invoke<void>(
3252 RTC_FROM_HERE,
3253 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3254 return;
3255 }
3256 auto audio_state =
3257 factory_->channel_manager()->media_engine()->GetAudioState();
3258 audio_state->SetPlayout(playout);
3259}
3260
3261void PeerConnection::SetAudioRecording(bool recording) {
3262 if (!worker_thread()->IsCurrent()) {
3263 worker_thread()->Invoke<void>(
3264 RTC_FROM_HERE,
3265 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3266 return;
3267 }
3268 auto audio_state =
3269 factory_->channel_manager()->media_engine()->GetAudioState();
3270 audio_state->SetRecording(recording);
3271}
3272
Steve Anton8c0f7a72017-10-03 10:03:10 -07003273std::unique_ptr<rtc::SSLCertificate>
3274PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003275 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3276 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003277 return nullptr;
3278 }
Steve Antonf25303e2018-10-16 15:23:31 -07003279 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003280}
3281
Zhi Huang70b820f2018-01-27 14:16:15 -08003282std::unique_ptr<rtc::SSLCertChain>
3283PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003284 auto audio_transceiver = GetFirstAudioTransceiver();
3285 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003286 return nullptr;
3287 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003288 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003289 audio_transceiver->internal()->channel()->transport_name());
3290}
3291
3292rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3293PeerConnection::GetFirstAudioTransceiver() const {
3294 for (auto transceiver : transceivers_) {
3295 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3296 return transceiver;
3297 }
3298 }
3299 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003300}
3301
ivoc14d5dbe2016-07-04 07:06:55 -07003302bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3303 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003304 // TODO(eladalon): It would be better to not allow negative values into PC.
3305 const size_t max_size = (max_size_bytes < 0)
3306 ? RtcEventLog::kUnlimitedOutput
3307 : rtc::saturated_cast<size_t>(max_size_bytes);
3308 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003309 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003310 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003311}
3312
Bjorn Tereliusde939432017-11-20 17:38:14 +01003313bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3314 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003315 // TODO(eladalon): In C++14, this can be done with a lambda.
3316 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003317 bool operator()() {
3318 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3319 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003320 PeerConnection* const pc;
3321 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003322 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003323 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003324 return worker_thread()->Invoke<bool>(
3325 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003326}
3327
3328void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003329 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003330 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3331}
3332
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003333const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003334 return pending_local_description_ ? pending_local_description_.get()
3335 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003336}
3337
3338const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003339 return pending_remote_description_ ? pending_remote_description_.get()
3340 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003341}
3342
deadbeeffe4a8a42016-12-20 17:56:17 -08003343const SessionDescriptionInterface* PeerConnection::current_local_description()
3344 const {
Steve Anton75737c02017-11-06 10:37:17 -08003345 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003346}
3347
3348const SessionDescriptionInterface* PeerConnection::current_remote_description()
3349 const {
Steve Anton75737c02017-11-06 10:37:17 -08003350 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003351}
3352
3353const SessionDescriptionInterface* PeerConnection::pending_local_description()
3354 const {
Steve Anton75737c02017-11-06 10:37:17 -08003355 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003356}
3357
3358const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3359 const {
Steve Anton75737c02017-11-06 10:37:17 -08003360 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003361}
3362
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003363void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003364 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003365 // Update stats here so that we have the most recent stats for tracks and
3366 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003367 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003368
Steve Anton75737c02017-11-06 10:37:17 -08003369 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003370 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003371
Steve Anton8af21862017-12-15 11:20:13 -08003372 for (auto transceiver : transceivers_) {
3373 transceiver->Stop();
3374 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003375
3376 // Ensure that all asynchronous stats requests are completed before destroying
3377 // the transport controller below.
3378 if (stats_collector_) {
3379 stats_collector_->WaitForPendingRequest();
3380 }
3381
3382 // Don't destroy BaseChannels until after stats has been cleaned up so that
3383 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003384 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003385
Qingsi Wang93a84392018-01-30 17:13:09 -08003386 // The event log is used in the transport controller, which must be outlived
3387 // by the former. CreateOffer by the peer connection is implemented
3388 // asynchronously and if the peer connection is closed without resetting the
3389 // WebRTC session description factory, the session description factory would
3390 // call the transport controller.
3391 webrtc_session_desc_factory_.reset();
3392 transport_controller_.reset();
3393
deadbeef42a42632017-03-10 15:18:00 -08003394 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003395 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3396 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003397
Steve Anton978b8762017-09-29 12:15:02 -07003398 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003399 call_.reset();
3400 // The event log must outlive call (and any other object that uses it).
3401 event_log_.reset();
3402 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003403 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003404 // The .h file says that observer can be discarded after close() returns.
3405 // Make sure this is true.
3406 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003407}
3408
Steve Antonad182762018-09-05 20:22:40 +00003409void PeerConnection::OnMessage(rtc::Message* msg) {
3410 switch (msg->message_id) {
3411 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3412 SetSessionDescriptionMsg* param =
3413 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3414 param->observer->OnSuccess();
3415 delete param;
3416 break;
3417 }
3418 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3419 SetSessionDescriptionMsg* param =
3420 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3421 param->observer->OnFailure(std::move(param->error));
3422 delete param;
3423 break;
3424 }
3425 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3426 CreateSessionDescriptionMsg* param =
3427 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3428 param->observer->OnFailure(std::move(param->error));
3429 delete param;
3430 break;
3431 }
3432 case MSG_GETSTATS: {
3433 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3434 StatsReports reports;
3435 stats_->GetStats(param->track, &reports);
3436 param->observer->OnComplete(reports);
3437 delete param;
3438 break;
3439 }
3440 case MSG_FREE_DATACHANNELS: {
3441 sctp_data_channels_to_free_.clear();
3442 break;
3443 }
3444 case MSG_REPORT_USAGE_PATTERN: {
3445 ReportUsagePattern();
3446 break;
3447 }
3448 default:
3449 RTC_NOTREACHED() << "Not implemented";
3450 break;
3451 }
3452}
3453
Steve Antonafb0bb72018-02-20 11:35:37 -08003454cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3455 RTC_DCHECK(!IsUnifiedPlan());
3456 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3457 GetAudioTransceiver()->internal()->channel());
3458 if (voice_channel) {
3459 return voice_channel->media_channel();
3460 } else {
3461 return nullptr;
3462 }
3463}
3464
3465cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3466 RTC_DCHECK(!IsUnifiedPlan());
3467 auto* video_channel = static_cast<cricket::VideoChannel*>(
3468 GetVideoTransceiver()->internal()->channel());
3469 if (video_channel) {
3470 return video_channel->media_channel();
3471 } else {
3472 return nullptr;
3473 }
3474}
3475
Steve Anton4171afb2017-11-20 10:20:22 -08003476void PeerConnection::CreateAudioReceiver(
3477 MediaStreamInterface* stream,
3478 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003479 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3480 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003481 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3482 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003483 auto* audio_receiver = new AudioRtpReceiver(
3484 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003485 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003486 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3487 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3488 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003489 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003490 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003491 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003492}
3493
Steve Anton4171afb2017-11-20 10:20:22 -08003494void PeerConnection::CreateVideoReceiver(
3495 MediaStreamInterface* stream,
3496 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003497 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3498 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003499 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3500 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003501 auto* video_receiver = new VideoRtpReceiver(
3502 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003503 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003504 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3505 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3506 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003507 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003508 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003509 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003510}
3511
deadbeef70ab1a12015-09-28 16:53:55 -07003512// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3513// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003514rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003515 const RtpSenderInfo& remote_sender_info) {
3516 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3517 if (!receiver) {
3518 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3519 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003520 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003521 }
Steve Anton4171afb2017-11-20 10:20:22 -08003522 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3523 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3524 } else {
3525 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3526 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003527 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003528}
3529
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003530void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3531 MediaStreamInterface* stream) {
3532 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003533 RTC_DCHECK(track);
3534 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003535 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003536 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003537 // We already have a sender for this track, so just change the stream_id
3538 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003539 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003540 return;
3541 }
3542
3543 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003544 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003545 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003546 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003547 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003548 // If the sender has already been configured in SDP, we call SetSsrc,
3549 // which will connect the sender to the underlying transport. This can
3550 // occur if a local session description that contains the ID of the sender
3551 // is set before AddStream is called. It can also occur if the local
3552 // session description is not changed and RemoveStream is called, and
3553 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003554 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003555 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003556 if (sender_info) {
3557 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003558 }
3559}
3560
3561// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3562// indefinitely, when we have unified plan SDP.
3563void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3564 MediaStreamInterface* stream) {
3565 RTC_DCHECK(!IsClosed());
3566 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003567 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003568 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3569 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003570 return;
3571 }
Steve Anton4171afb2017-11-20 10:20:22 -08003572 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003573}
3574
3575void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3576 MediaStreamInterface* stream) {
3577 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003578 RTC_DCHECK(track);
3579 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003580 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003581 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003582 // We already have a sender for this track, so just change the stream_id
3583 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003584 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003585 return;
3586 }
3587
3588 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003589 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003590 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003591 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003592 GetVideoTransceiver()->internal()->AddSender(new_sender);
3593 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003594 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003595 if (sender_info) {
3596 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003597 }
3598}
3599
3600void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3601 MediaStreamInterface* stream) {
3602 RTC_DCHECK(!IsClosed());
3603 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003604 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003605 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3606 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003607 return;
3608 }
Steve Anton4171afb2017-11-20 10:20:22 -08003609 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003610}
3611
Steve Antonba818672017-11-06 10:21:57 -08003612void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003613 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003614 if (ice_connection_state_ == new_state) {
3615 return;
3616 }
3617
deadbeefcbecd352015-09-23 11:50:27 -07003618 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003619 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003620 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003621 return;
3622 }
Steve Antonba818672017-11-06 10:21:57 -08003623
Mirko Bonadei675513b2017-11-09 11:09:25 +01003624 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3625 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003626 RTC_DCHECK(ice_connection_state_ !=
3627 PeerConnectionInterface::kIceConnectionClosed);
3628
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003629 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003630 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003631}
3632
Jonas Olsson635474e2018-10-18 15:58:17 +02003633void PeerConnection::SetStandardizedIceConnectionState(
3634 PeerConnectionInterface::IceConnectionState new_state) {
3635 RTC_DCHECK(signaling_thread()->IsCurrent());
3636 if (standardized_ice_connection_state_ == new_state)
3637 return;
3638 if (IsClosed())
3639 return;
3640 standardized_ice_connection_state_ = new_state;
3641 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3642 // the old one once disconnects are handled properly.
3643}
3644
3645void PeerConnection::SetConnectionState(
3646 PeerConnectionInterface::PeerConnectionState new_state) {
3647 RTC_DCHECK(signaling_thread()->IsCurrent());
3648 if (connection_state_ == new_state)
3649 return;
3650 if (IsClosed())
3651 return;
3652 connection_state_ = new_state;
3653 Observer()->OnConnectionChange(new_state);
3654}
3655
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003656void PeerConnection::OnIceGatheringChange(
3657 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003658 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003659 if (IsClosed()) {
3660 return;
3661 }
3662 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003663 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003664}
3665
jbauch81bf7b02017-03-25 08:31:12 -07003666void PeerConnection::OnIceCandidate(
3667 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003668 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003669 if (IsClosed()) {
3670 return;
3671 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003672 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003673 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3674 candidate->candidate().address().IsPrivateIP()) {
3675 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3676 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003677 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003678}
3679
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003680void PeerConnection::OnIceCandidatesRemoved(
3681 const std::vector<cricket::Candidate>& candidates) {
3682 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003683 if (IsClosed()) {
3684 return;
3685 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003686 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003687}
3688
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003689void PeerConnection::ChangeSignalingState(
3690 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003691 RTC_DCHECK(signaling_thread()->IsCurrent());
3692 if (signaling_state_ == signaling_state) {
3693 return;
3694 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003695 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3696 << GetSignalingStateString(signaling_state_)
3697 << " New state: "
3698 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003699 signaling_state_ = signaling_state;
3700 if (signaling_state == kClosed) {
3701 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003702 Observer()->OnIceConnectionChange(ice_connection_state_);
Jonas Olsson635474e2018-10-18 15:58:17 +02003703 standardized_ice_connection_state_ =
3704 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
3705 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3706 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003707 if (ice_gathering_state_ != kIceGatheringComplete) {
3708 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003709 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003710 }
3711 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003712 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003713}
3714
deadbeefeb459812015-12-15 19:24:43 -08003715void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3716 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003717 if (IsClosed()) {
3718 return;
3719 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003720 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003721 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003722}
3723
deadbeefeb459812015-12-15 19:24:43 -08003724void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3725 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003726 if (IsClosed()) {
3727 return;
3728 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003729 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003730 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003731}
3732
3733void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3734 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003735 if (IsClosed()) {
3736 return;
3737 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003738 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003739 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003740}
3741
3742void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3743 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003744 if (IsClosed()) {
3745 return;
3746 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003747 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003748 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003749}
3750
Henrik Boström31638672017-11-23 17:48:32 +01003751void PeerConnection::PostSetSessionDescriptionSuccess(
3752 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003753 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3754 signaling_thread()->Post(RTC_FROM_HERE, this,
3755 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003756}
3757
deadbeefab9b2d12015-10-14 11:33:11 -07003758void PeerConnection::PostSetSessionDescriptionFailure(
3759 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003760 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003761 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003762 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3763 msg->error = std::move(error);
3764 signaling_thread()->Post(RTC_FROM_HERE, this,
3765 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003766}
3767
3768void PeerConnection::PostCreateSessionDescriptionFailure(
3769 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003770 RTCError error) {
3771 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003772 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3773 msg->error = std::move(error);
3774 signaling_thread()->Post(RTC_FROM_HERE, this,
3775 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003776}
3777
zhihuang1c378ed2017-08-17 14:10:50 -07003778void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003779 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003780 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003781 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003782
Steve Antondcc3c022017-12-22 16:02:54 -08003783 if (IsUnifiedPlan()) {
3784 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3785 } else {
3786 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3787 }
3788
Steve Antonfa2260d2017-12-28 16:38:23 -08003789 // Intentionally unset the data channel type for RTP data channel with the
3790 // second condition. Otherwise the RTP data channels would be successfully
3791 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3792 // when building with chromium. We want to leave RTP data channels broken, so
3793 // people won't try to use them.
3794 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3795 session_options->data_channel_type = data_channel_type();
3796 }
3797
Steve Antondcc3c022017-12-22 16:02:54 -08003798 // Apply ICE restart flag and renomination flag.
3799 for (auto& options : session_options->media_description_options) {
3800 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3801 options.transport_options.enable_ice_renomination =
3802 configuration_.enable_ice_renomination;
3803 }
3804
3805 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003806 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08003807 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003808 session_options->pooled_ice_credentials =
3809 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3810 RTC_FROM_HERE,
3811 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3812 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003813 session_options->offer_extmap_allow_mixed =
3814 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003815}
3816
3817void PeerConnection::GetOptionsForPlanBOffer(
3818 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3819 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003820 // Figure out transceiver directional preferences.
3821 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3822 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3823
3824 // By default, generate sendrecv/recvonly m= sections.
3825 bool recv_audio = true;
3826 bool recv_video = true;
3827
3828 // By default, only offer a new m= section if we have media to send with it.
3829 bool offer_new_audio_description = send_audio;
3830 bool offer_new_video_description = send_video;
3831 bool offer_new_data_description = HasDataChannels();
3832
3833 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003834 if (offer_answer_options.offer_to_receive_audio !=
3835 RTCOfferAnswerOptions::kUndefined) {
3836 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003837 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003838 offer_new_audio_description ||
3839 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003840 }
Steve Antondcc3c022017-12-22 16:02:54 -08003841 if (offer_answer_options.offer_to_receive_video !=
3842 RTCOfferAnswerOptions::kUndefined) {
3843 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003844 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003845 offer_new_video_description ||
3846 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003847 }
3848
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003849 absl::optional<size_t> audio_index;
3850 absl::optional<size_t> video_index;
3851 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003852 // If a current description exists, generate m= sections in the same order,
3853 // using the first audio/video/data section that appears and rejecting
3854 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003855 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003856 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003857 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003858 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3859 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3860 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003861 }
3862
zhihuang1c378ed2017-08-17 14:10:50 -07003863 // Add audio/video/data m= sections to the end if needed.
3864 if (!audio_index && offer_new_audio_description) {
3865 session_options->media_description_options.push_back(
3866 cricket::MediaDescriptionOptions(
3867 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003868 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3869 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003870 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003871 }
zhihuang1c378ed2017-08-17 14:10:50 -07003872 if (!video_index && offer_new_video_description) {
3873 session_options->media_description_options.push_back(
3874 cricket::MediaDescriptionOptions(
3875 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003876 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3877 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003878 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003879 }
zhihuang1c378ed2017-08-17 14:10:50 -07003880 if (!data_index && offer_new_data_description) {
3881 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003882 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003883 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003884 }
3885
3886 cricket::MediaDescriptionOptions* audio_media_description_options =
3887 !audio_index ? nullptr
3888 : &session_options->media_description_options[*audio_index];
3889 cricket::MediaDescriptionOptions* video_media_description_options =
3890 !video_index ? nullptr
3891 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003892
Steve Anton4171afb2017-11-20 10:20:22 -08003893 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003894 video_media_description_options,
3895 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003896}
3897
3898// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3899// and return a reference to it.
3900// Generated MIDs should be no more than 3 bytes long to take up less space in
3901// the RTP packet.
3902static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3903 RTC_DCHECK(used_mids);
3904 // We're boring: just generate MIDs 0, 1, 2, ...
3905 size_t i = 0;
3906 std::set<std::string>::iterator it;
3907 bool inserted;
3908 do {
3909 std::string mid = rtc::ToString(i++);
3910 auto insert_result = used_mids->insert(mid);
3911 it = insert_result.first;
3912 inserted = insert_result.second;
3913 } while (!inserted);
3914 return *it;
3915}
3916
3917static cricket::MediaDescriptionOptions
3918GetMediaDescriptionOptionsForTransceiver(
3919 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3920 transceiver,
3921 const std::string& mid) {
3922 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003923 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003924 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003925 // This behavior is specified in JSEP. The gist is that:
3926 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3927 // sendrecv.
3928 // 2. If the MSID is included, then it must be included in any subsequent
3929 // offer/answer exactly the same until the RtpTransceiver is stopped.
3930 if (!transceiver->stopped() &&
3931 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3932 transceiver->internal()->has_ever_been_used_to_send())) {
3933 cricket::SenderOptions sender_options;
3934 sender_options.track_id = transceiver->sender()->id();
3935 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003936 int num_send_encoding_layers =
3937 transceiver->sender()->init_send_encodings().size();
3938 sender_options.num_sim_layers =
3939 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003940 media_description_options.sender_options.push_back(sender_options);
3941 }
Steve Antondcc3c022017-12-22 16:02:54 -08003942 return media_description_options;
3943}
3944
3945void PeerConnection::GetOptionsForUnifiedPlanOffer(
3946 const RTCOfferAnswerOptions& offer_answer_options,
3947 cricket::MediaSessionOptions* session_options) {
3948 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3949 // Offers) and 5.2.2 (Subsequent Offers).
3950 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3951 const ContentInfos& local_contents =
3952 (local_description() ? local_description()->description()->contents()
3953 : ContentInfos());
3954 const ContentInfos& remote_contents =
3955 (remote_description() ? remote_description()->description()->contents()
3956 : ContentInfos());
3957 // The mline indices that can be recycled. New transceivers should reuse these
3958 // slots first.
3959 std::queue<size_t> recycleable_mline_indices;
3960 // Track the MIDs used in previous offer/answer exchanges and the current
3961 // offer so that new, unique MIDs are generated.
3962 std::set<std::string> used_mids = seen_mids_;
3963 // First, go through each media section that exists in either the local or
3964 // remote description and generate a media section in this offer for the
3965 // associated transceiver. If a media section can be recycled, generate a
3966 // default, rejected media section here that can be later overwritten.
3967 for (size_t i = 0;
3968 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3969 // Either |local_content| or |remote_content| is non-null.
3970 const ContentInfo* local_content =
3971 (i < local_contents.size() ? &local_contents[i] : nullptr);
3972 const ContentInfo* remote_content =
3973 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3974 bool had_been_rejected = (local_content && local_content->rejected) ||
3975 (remote_content && remote_content->rejected);
3976 const std::string& mid =
3977 (local_content ? local_content->name : remote_content->name);
3978 cricket::MediaType media_type =
3979 (local_content ? local_content->media_description()->type()
3980 : remote_content->media_description()->type());
3981 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3982 media_type == cricket::MEDIA_TYPE_VIDEO) {
3983 auto transceiver = GetAssociatedTransceiver(mid);
3984 RTC_CHECK(transceiver);
3985 // A media section is considered eligible for recycling if it is marked as
3986 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003987 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003988 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003989 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3990 RtpTransceiverDirection::kInactive,
3991 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003992 recycleable_mline_indices.push(i);
3993 } else {
3994 session_options->media_description_options.push_back(
3995 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3996 // CreateOffer shouldn't really cause any state changes in
3997 // PeerConnection, but we need a way to match new transceivers to new
3998 // media sections in SetLocalDescription and JSEP specifies this is done
3999 // by recording the index of the media section generated for the
4000 // transceiver in the offer.
4001 transceiver->internal()->set_mline_index(i);
4002 }
4003 } else {
4004 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004005 RTC_CHECK(GetDataMid());
4006 if (had_been_rejected || mid != *GetDataMid()) {
4007 session_options->media_description_options.push_back(
4008 GetMediaDescriptionOptionsForRejectedData(mid));
4009 } else {
4010 session_options->media_description_options.push_back(
4011 GetMediaDescriptionOptionsForActiveData(mid));
4012 }
Steve Antondcc3c022017-12-22 16:02:54 -08004013 }
4014 }
4015 // Next, look for transceivers that are newly added (that is, are not stopped
4016 // and not associated). Reuse media sections marked as recyclable first,
4017 // otherwise append to the end of the offer. New media sections should be
4018 // added in the order they were added to the PeerConnection.
4019 for (auto transceiver : transceivers_) {
4020 if (transceiver->mid() || transceiver->stopped()) {
4021 continue;
4022 }
4023 size_t mline_index;
4024 if (!recycleable_mline_indices.empty()) {
4025 mline_index = recycleable_mline_indices.front();
4026 recycleable_mline_indices.pop();
4027 session_options->media_description_options[mline_index] =
4028 GetMediaDescriptionOptionsForTransceiver(transceiver,
4029 AllocateMid(&used_mids));
4030 } else {
4031 mline_index = session_options->media_description_options.size();
4032 session_options->media_description_options.push_back(
4033 GetMediaDescriptionOptionsForTransceiver(transceiver,
4034 AllocateMid(&used_mids)));
4035 }
4036 // See comment above for why CreateOffer changes the transceiver's state.
4037 transceiver->internal()->set_mline_index(mline_index);
4038 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004039 // Lastly, add a m-section if we have local data channels and an m section
4040 // does not already exist.
4041 if (!GetDataMid() && HasDataChannels()) {
4042 session_options->media_description_options.push_back(
4043 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4044 }
Steve Antondcc3c022017-12-22 16:02:54 -08004045}
4046
4047void PeerConnection::GetOptionsForAnswer(
4048 const RTCOfferAnswerOptions& offer_answer_options,
4049 cricket::MediaSessionOptions* session_options) {
4050 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4051
4052 if (IsUnifiedPlan()) {
4053 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4054 } else {
4055 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4056 }
4057
Steve Antonfa2260d2017-12-28 16:38:23 -08004058 // Intentionally unset the data channel type for RTP data channel. Otherwise
4059 // the RTP data channels would be successfully negotiated by default and the
4060 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4061 // We want to leave RTP data channels broken, so people won't try to use them.
4062 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4063 session_options->data_channel_type = data_channel_type();
4064 }
4065
Steve Antondcc3c022017-12-22 16:02:54 -08004066 // Apply ICE renomination flag.
4067 for (auto& options : session_options->media_description_options) {
4068 options.transport_options.enable_ice_renomination =
4069 configuration_.enable_ice_renomination;
4070 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004071
4072 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004073 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08004074 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004075 session_options->pooled_ice_credentials =
4076 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4077 RTC_FROM_HERE,
4078 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4079 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004080}
4081
Steve Antondcc3c022017-12-22 16:02:54 -08004082void PeerConnection::GetOptionsForPlanBAnswer(
4083 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004084 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004085 // Figure out transceiver directional preferences.
4086 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4087 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4088
4089 // By default, generate sendrecv/recvonly m= sections. The direction is also
4090 // restricted by the direction in the offer.
4091 bool recv_audio = true;
4092 bool recv_video = true;
4093
4094 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004095 if (offer_answer_options.offer_to_receive_audio !=
4096 RTCOfferAnswerOptions::kUndefined) {
4097 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004098 }
Steve Antondcc3c022017-12-22 16:02:54 -08004099 if (offer_answer_options.offer_to_receive_video !=
4100 RTCOfferAnswerOptions::kUndefined) {
4101 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004102 }
4103
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004104 absl::optional<size_t> audio_index;
4105 absl::optional<size_t> video_index;
4106 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004107
4108 // Generate m= sections that match those in the offer.
4109 // Note that mediasession.cc will handle intersection our preferred
4110 // direction with the offered direction.
4111 GenerateMediaDescriptionOptions(
4112 remote_description(),
4113 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4114 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4115 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004116
4117 cricket::MediaDescriptionOptions* audio_media_description_options =
4118 !audio_index ? nullptr
4119 : &session_options->media_description_options[*audio_index];
4120 cricket::MediaDescriptionOptions* video_media_description_options =
4121 !video_index ? nullptr
4122 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004123
Steve Anton4171afb2017-11-20 10:20:22 -08004124 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004125 video_media_description_options,
4126 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004127}
zhihuangaf388472016-11-02 16:49:48 -07004128
Steve Antondcc3c022017-12-22 16:02:54 -08004129void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4130 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4131 cricket::MediaSessionOptions* session_options) {
4132 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4133 // Answers) and 5.3.2 (Subsequent Answers).
4134 RTC_DCHECK(remote_description());
4135 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4136 for (const ContentInfo& content :
4137 remote_description()->description()->contents()) {
4138 cricket::MediaType media_type = content.media_description()->type();
4139 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4140 media_type == cricket::MEDIA_TYPE_VIDEO) {
4141 auto transceiver = GetAssociatedTransceiver(content.name);
4142 RTC_CHECK(transceiver);
4143 session_options->media_description_options.push_back(
4144 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4145 } else {
4146 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004147 // Reject all data sections if data channels are disabled.
4148 // Reject a data section if it has already been rejected.
4149 // Reject all data sections except for the first one.
4150 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4151 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004152 session_options->media_description_options.push_back(
4153 GetMediaDescriptionOptionsForRejectedData(content.name));
4154 } else {
4155 session_options->media_description_options.push_back(
4156 GetMediaDescriptionOptionsForActiveData(content.name));
4157 }
Steve Antondcc3c022017-12-22 16:02:54 -08004158 }
4159 }
htaa2a49d92016-03-04 02:51:39 -08004160}
4161
zhihuang1c378ed2017-08-17 14:10:50 -07004162void PeerConnection::GenerateMediaDescriptionOptions(
4163 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004164 RtpTransceiverDirection audio_direction,
4165 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004166 absl::optional<size_t>* audio_index,
4167 absl::optional<size_t>* video_index,
4168 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004169 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004170 for (const cricket::ContentInfo& content :
4171 session_desc->description()->contents()) {
4172 if (IsAudioContent(&content)) {
4173 // If we already have an audio m= section, reject this extra one.
4174 if (*audio_index) {
4175 session_options->media_description_options.push_back(
4176 cricket::MediaDescriptionOptions(
4177 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004178 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004179 } else {
4180 session_options->media_description_options.push_back(
4181 cricket::MediaDescriptionOptions(
4182 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004183 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004184 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004185 }
4186 } else if (IsVideoContent(&content)) {
4187 // If we already have an video m= section, reject this extra one.
4188 if (*video_index) {
4189 session_options->media_description_options.push_back(
4190 cricket::MediaDescriptionOptions(
4191 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004192 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004193 } else {
4194 session_options->media_description_options.push_back(
4195 cricket::MediaDescriptionOptions(
4196 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004197 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004198 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004199 }
4200 } else {
4201 RTC_DCHECK(IsDataContent(&content));
4202 // If we already have an data m= section, reject this extra one.
4203 if (*data_index) {
4204 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004205 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004206 } else {
4207 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004208 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004209 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004210 }
4211 }
htaa2a49d92016-03-04 02:51:39 -08004212 }
deadbeefab9b2d12015-10-14 11:33:11 -07004213}
4214
Steve Antonfa2260d2017-12-28 16:38:23 -08004215cricket::MediaDescriptionOptions
4216PeerConnection::GetMediaDescriptionOptionsForActiveData(
4217 const std::string& mid) const {
4218 // Direction for data sections is meaningless, but legacy endpoints might
4219 // expect sendrecv.
4220 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4221 RtpTransceiverDirection::kSendRecv,
4222 /*stopped=*/false);
4223 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4224 return options;
4225}
4226
4227cricket::MediaDescriptionOptions
4228PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4229 const std::string& mid) const {
4230 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4231 RtpTransceiverDirection::kInactive,
4232 /*stopped=*/true);
4233 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4234 return options;
4235}
4236
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004237absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004238 switch (data_channel_type_) {
4239 case cricket::DCT_RTP:
4240 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004241 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004242 }
4243 return rtp_data_channel_->content_name();
4244 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004245 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004246 case cricket::DCT_MEDIA_TRANSPORT:
4247 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004248 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004249 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004250 }
4251}
4252
Steve Anton4171afb2017-11-20 10:20:22 -08004253void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4254 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4255 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004256 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004257}
4258
Steve Anton4171afb2017-11-20 10:20:22 -08004259void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004260 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004261 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004262 cricket::MediaType media_type,
4263 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004264 RTC_DCHECK(!IsUnifiedPlan());
4265
Steve Anton4171afb2017-11-20 10:20:22 -08004266 std::vector<RtpSenderInfo>* current_senders =
4267 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004268
Steve Anton4171afb2017-11-20 10:20:22 -08004269 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004270 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004271 for (auto sender_it = current_senders->begin();
4272 sender_it != current_senders->end();
4273 /* incremented manually */) {
4274 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004275 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004276 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004277 std::string params_stream_id;
4278 if (params) {
4279 params_stream_id =
4280 (!params->first_stream_id().empty() ? params->first_stream_id()
4281 : kDefaultStreamId);
4282 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004283 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004284 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004285 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004286 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004287 sender_exists) {
4288 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004289 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004290 OnRemoteSenderRemoved(info, media_type);
4291 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004292 }
4293 }
4294
Steve Anton4171afb2017-11-20 10:20:22 -08004295 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004296 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004297 if (!params.has_ssrcs()) {
4298 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4299 // sender, this means it is coming from a Unified Plan endpoint,so we just
4300 // create a default.
4301 default_sender_needed = true;
4302 break;
4303 }
4304
Seth Hampson845e8782018-03-02 11:34:10 -08004305 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004306 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004307 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4308 // not supported in Plan B, we just take the first here and create the
4309 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004310 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004311 (!params.first_stream_id().empty() ? params.first_stream_id()
4312 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004313 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004314 uint32_t ssrc = params.first_ssrc();
4315
4316 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004317 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004318 if (!stream) {
4319 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004320 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004321 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004322 remote_streams_->AddStream(stream);
4323 new_streams->AddStream(stream);
4324 }
4325
Steve Anton4171afb2017-11-20 10:20:22 -08004326 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004327 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004328 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004329 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004330 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004331 }
4332 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004333
Steve Anton4171afb2017-11-20 10:20:22 -08004334 // Add default sender if necessary.
4335 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004336 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004337 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004338 if (!default_stream) {
4339 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004340 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004341 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004342 remote_streams_->AddStream(default_stream);
4343 new_streams->AddStream(default_stream);
4344 }
Steve Anton4171afb2017-11-20 10:20:22 -08004345 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4346 ? kDefaultAudioSenderId
4347 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004348 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004349 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004350 if (!default_sender_info) {
4351 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004352 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004353 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004354 }
4355 }
deadbeefab9b2d12015-10-14 11:33:11 -07004356}
4357
Steve Anton4171afb2017-11-20 10:20:22 -08004358void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4359 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004360 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4361 << " receiver for track_id=" << sender_info.sender_id
4362 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004363
Steve Anton3d954a62018-04-02 11:27:23 -07004364 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004365 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004366 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004367 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004368 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004369 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004370 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004371 }
4372}
4373
Steve Anton4171afb2017-11-20 10:20:22 -08004374void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4375 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004376 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4377 << " receiver for track_id=" << sender_info.sender_id
4378 << " and stream_id=" << sender_info.stream_id;
4379
Seth Hampson845e8782018-03-02 11:34:10 -08004380 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004381
Henrik Boström933d8b02017-10-10 10:05:16 -07004382 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004383 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004384 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4385 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004386 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004387 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004388 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004389 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004390 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004391 }
4392 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004393 // Stopping or destroying a VideoRtpReceiver will end the
4394 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004395 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004396 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004397 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004398 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004399 // There's no guarantee the track is still available, e.g. the track may
4400 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004401 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004402 }
4403 } else {
nisseede5da42017-01-12 05:15:36 -08004404 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004405 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004406 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004407 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004408 }
deadbeefab9b2d12015-10-14 11:33:11 -07004409}
4410
4411void PeerConnection::UpdateEndedRemoteMediaStreams() {
4412 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4413 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4414 MediaStreamInterface* stream = remote_streams_->at(i);
4415 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4416 streams_to_remove.push_back(stream);
4417 }
4418 }
4419
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004420 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004421 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004422 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004423 }
4424}
4425
Steve Anton4171afb2017-11-20 10:20:22 -08004426void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004427 const std::vector<cricket::StreamParams>& streams,
4428 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004429 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004430
Seth Hampson845e8782018-03-02 11:34:10 -08004431 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004432 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004433 for (auto sender_it = current_senders->begin();
4434 sender_it != current_senders->end();
4435 /* incremented manually */) {
4436 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004437 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004438 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4439 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004440 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004441 OnLocalSenderRemoved(info, media_type);
4442 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004443 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004444 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004445 }
4446 }
4447
Steve Anton4171afb2017-11-20 10:20:22 -08004448 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004449 for (const cricket::StreamParams& params : streams) {
4450 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004451 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004452 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004453 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004454 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004455 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004456 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004457 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004458 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004459 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004460 }
4461 }
4462}
4463
Steve Anton4171afb2017-11-20 10:20:22 -08004464void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4465 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004466 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004467 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004468 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004469 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4470 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004471 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004472 return;
4473 }
4474
deadbeeffac06552015-11-25 11:26:01 -08004475 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004476 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004477 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004478 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004479 }
deadbeeffac06552015-11-25 11:26:01 -08004480
Seth Hampson5b4f0752018-04-02 16:31:36 -07004481 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004482 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004483}
4484
Steve Anton4171afb2017-11-20 10:20:22 -08004485void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4486 cricket::MediaType media_type) {
4487 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004488 if (!sender) {
4489 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004490 // SessionDescriptions has been renegotiated.
4491 return;
4492 }
deadbeeffac06552015-11-25 11:26:01 -08004493
4494 // A sender has been removed from the SessionDescription but it's still
4495 // associated with the PeerConnection. This only occurs if the SDP doesn't
4496 // match with the calls to CreateSender, AddStream and RemoveStream.
4497 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004498 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004499 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004500 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004501 }
deadbeeffac06552015-11-25 11:26:01 -08004502
Steve Anton4171afb2017-11-20 10:20:22 -08004503 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004504}
4505
4506void PeerConnection::UpdateLocalRtpDataChannels(
4507 const cricket::StreamParamsVec& streams) {
4508 std::vector<std::string> existing_channels;
4509
4510 // Find new and active data channels.
4511 for (const cricket::StreamParams& params : streams) {
4512 // |it->sync_label| is actually the data channel label. The reason is that
4513 // we use the same naming of data channels as we do for
4514 // MediaStreams and Tracks.
4515 // For MediaStreams, the sync_label is the MediaStream label and the
4516 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004517 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004518 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004519 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004520 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004521 continue;
4522 }
4523 // Set the SSRC the data channel should use for sending.
4524 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4525 existing_channels.push_back(data_channel_it->first);
4526 }
4527
4528 UpdateClosingRtpDataChannels(existing_channels, true);
4529}
4530
4531void PeerConnection::UpdateRemoteRtpDataChannels(
4532 const cricket::StreamParamsVec& streams) {
4533 std::vector<std::string> existing_channels;
4534
4535 // Find new and active data channels.
4536 for (const cricket::StreamParams& params : streams) {
4537 // The data channel label is either the mslabel or the SSRC if the mslabel
4538 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004539 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004540 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004541 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004542 auto data_channel_it = rtp_data_channels_.find(label);
4543 if (data_channel_it == rtp_data_channels_.end()) {
4544 // This is a new data channel.
4545 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4546 } else {
4547 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4548 }
4549 existing_channels.push_back(label);
4550 }
4551
4552 UpdateClosingRtpDataChannels(existing_channels, false);
4553}
4554
4555void PeerConnection::UpdateClosingRtpDataChannels(
4556 const std::vector<std::string>& active_channels,
4557 bool is_local_update) {
4558 auto it = rtp_data_channels_.begin();
4559 while (it != rtp_data_channels_.end()) {
4560 DataChannel* data_channel = it->second;
4561 if (std::find(active_channels.begin(), active_channels.end(),
4562 data_channel->label()) != active_channels.end()) {
4563 ++it;
4564 continue;
4565 }
4566
4567 if (is_local_update) {
4568 data_channel->SetSendSsrc(0);
4569 } else {
4570 data_channel->RemotePeerRequestClose();
4571 }
4572
4573 if (data_channel->state() == DataChannel::kClosed) {
4574 rtp_data_channels_.erase(it);
4575 it = rtp_data_channels_.begin();
4576 } else {
4577 ++it;
4578 }
4579 }
4580}
4581
4582void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4583 uint32_t remote_ssrc) {
4584 rtc::scoped_refptr<DataChannel> channel(
4585 InternalCreateDataChannel(label, nullptr));
4586 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004587 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004588 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004589 return;
4590 }
4591 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004592 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4593 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004594 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004595}
4596
4597rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4598 const std::string& label,
4599 const InternalDataChannelInit* config) {
4600 if (IsClosed()) {
4601 return nullptr;
4602 }
Steve Anton75737c02017-11-06 10:37:17 -08004603 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004604 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004605 << "InternalCreateDataChannel: Data is not supported in this call.";
4606 return nullptr;
4607 }
4608 InternalDataChannelInit new_config =
4609 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004610 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004611 if (new_config.id < 0) {
4612 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004613 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004614 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004615 RTC_LOG(LS_ERROR)
4616 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004617 return nullptr;
4618 }
4619 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004620 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004621 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004622 return nullptr;
4623 }
4624 }
4625
Steve Anton75737c02017-11-06 10:37:17 -08004626 rtc::scoped_refptr<DataChannel> channel(
4627 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004628 if (!channel) {
4629 sid_allocator_.ReleaseSid(new_config.id);
4630 return nullptr;
4631 }
4632
4633 if (channel->data_channel_type() == cricket::DCT_RTP) {
4634 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004635 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4636 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004637 return nullptr;
4638 }
4639 rtp_data_channels_[channel->label()] = channel;
4640 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004641 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004642 sctp_data_channels_.push_back(channel);
4643 channel->SignalClosed.connect(this,
4644 &PeerConnection::OnSctpDataChannelClosed);
4645 }
4646
Steve Anton2d8609c2018-01-23 16:38:46 -08004647 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004648 return channel;
4649}
4650
4651bool PeerConnection::HasDataChannels() const {
4652 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4653}
4654
4655void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4656 for (const auto& channel : sctp_data_channels_) {
4657 if (channel->id() < 0) {
4658 int sid;
4659 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004660 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004661 continue;
4662 }
4663 channel->SetSctpSid(sid);
4664 }
4665 }
4666}
4667
4668void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004669 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004670 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4671 ++it) {
4672 if (it->get() == channel) {
4673 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004674 // After the closing procedure is done, it's safe to use this ID for
4675 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004676 sid_allocator_.ReleaseSid(channel->id());
4677 }
deadbeefbd292462015-12-14 18:15:29 -08004678 // Since this method is triggered by a signal from the DataChannel,
4679 // we can't free it directly here; we need to free it asynchronously.
4680 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004681 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004682 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4683 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004684 return;
4685 }
4686 }
4687}
4688
deadbeefab9b2d12015-10-14 11:33:11 -07004689void PeerConnection::OnDataChannelDestroyed() {
4690 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4691 // DataChannel may callback to us and try to modify the list.
4692 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4693 temp_rtp_dcs.swap(rtp_data_channels_);
4694 for (const auto& kv : temp_rtp_dcs) {
4695 kv.second->OnTransportChannelDestroyed();
4696 }
4697
4698 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4699 temp_sctp_dcs.swap(sctp_data_channels_);
4700 for (const auto& channel : temp_sctp_dcs) {
4701 channel->OnTransportChannelDestroyed();
4702 }
4703}
4704
4705void PeerConnection::OnDataChannelOpenMessage(
4706 const std::string& label,
4707 const InternalDataChannelInit& config) {
4708 rtc::scoped_refptr<DataChannel> channel(
4709 InternalCreateDataChannel(label, &config));
4710 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004711 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004712 return;
4713 }
4714
deadbeefa601f5c2016-06-06 14:27:39 -07004715 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4716 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004717 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004718 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004719}
4720
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004721bool PeerConnection::HandleOpenMessage_s(
4722 const cricket::ReceiveDataParams& params,
4723 const rtc::CopyOnWriteBuffer& buffer) {
4724 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4725 // Received OPEN message; parse and signal that a new data channel should
4726 // be created.
4727 std::string label;
4728 InternalDataChannelInit config;
4729 config.id = params.ssrc;
4730 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4731 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4732 << params.ssrc;
4733 return true;
4734 }
4735 config.open_handshake_role = InternalDataChannelInit::kAcker;
4736 OnDataChannelOpenMessage(label, config);
4737 return true;
4738 }
4739 return false;
4740}
4741
Steve Anton4171afb2017-11-20 10:20:22 -08004742rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4743PeerConnection::GetAudioTransceiver() const {
4744 // This method only works with Plan B SDP, where there is a single
4745 // audio/video transceiver.
4746 RTC_DCHECK(!IsUnifiedPlan());
4747 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004748 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004749 return transceiver;
4750 }
4751 }
4752 RTC_NOTREACHED();
4753 return nullptr;
4754}
4755
4756rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4757PeerConnection::GetVideoTransceiver() const {
4758 // This method only works with Plan B SDP, where there is a single
4759 // audio/video transceiver.
4760 RTC_DCHECK(!IsUnifiedPlan());
4761 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004762 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004763 return transceiver;
4764 }
4765 }
4766 RTC_NOTREACHED();
4767 return nullptr;
4768}
4769
4770// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4771// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004772bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004773 switch (type) {
4774 case cricket::MEDIA_TYPE_AUDIO:
4775 return !GetAudioTransceiver()->internal()->senders().empty();
4776 case cricket::MEDIA_TYPE_VIDEO:
4777 return !GetVideoTransceiver()->internal()->senders().empty();
4778 case cricket::MEDIA_TYPE_DATA:
4779 return false;
4780 }
4781 RTC_NOTREACHED();
4782 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004783}
4784
Steve Anton4171afb2017-11-20 10:20:22 -08004785rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4786PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4787 for (auto transceiver : transceivers_) {
4788 for (auto sender : transceiver->internal()->senders()) {
4789 if (sender->track() == track) {
4790 return sender;
4791 }
4792 }
4793 }
4794 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004795}
4796
Steve Anton4171afb2017-11-20 10:20:22 -08004797rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4798PeerConnection::FindSenderById(const std::string& sender_id) const {
4799 for (auto transceiver : transceivers_) {
4800 for (auto sender : transceiver->internal()->senders()) {
4801 if (sender->id() == sender_id) {
4802 return sender;
4803 }
4804 }
4805 }
4806 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004807}
4808
Steve Anton4171afb2017-11-20 10:20:22 -08004809rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4810PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4811 for (auto transceiver : transceivers_) {
4812 for (auto receiver : transceiver->internal()->receivers()) {
4813 if (receiver->id() == receiver_id) {
4814 return receiver;
4815 }
4816 }
4817 }
4818 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004819}
4820
Steve Anton4171afb2017-11-20 10:20:22 -08004821std::vector<PeerConnection::RtpSenderInfo>*
4822PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4823 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4824 media_type == cricket::MEDIA_TYPE_VIDEO);
4825 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4826 ? &remote_audio_sender_infos_
4827 : &remote_video_sender_infos_;
4828}
4829
4830std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004831 cricket::MediaType media_type) {
4832 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4833 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004834 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4835 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004836}
4837
Steve Anton4171afb2017-11-20 10:20:22 -08004838const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4839 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004840 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004841 const std::string sender_id) const {
4842 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004843 if (sender_info.stream_id == stream_id &&
4844 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004845 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004846 }
4847 }
4848 return nullptr;
4849}
4850
4851DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4852 for (const auto& channel : sctp_data_channels_) {
4853 if (channel->id() == sid) {
4854 return channel;
4855 }
4856 }
4857 return nullptr;
4858}
4859
deadbeef91dd5672016-05-18 16:55:30 -07004860bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004861 const cricket::ServerAddresses& stun_servers,
4862 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004863 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004864 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004865 // To handle both internal and externally created port allocator, we will
4866 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004867 port_allocator_flags_ = port_allocator_->flags();
4868 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4869 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4870 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004871 // If the disable-IPv6 flag was specified, we'll not override it
4872 // by experiment.
4873 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004874 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004875 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4876 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004877 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004878 }
4879
zhihuangb09b3f92017-03-07 14:40:51 -08004880 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004881 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004882 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004883 }
4884
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004885 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004886 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004887 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004888 }
4889
honghaiz60347052016-05-31 18:29:12 -07004890 if (configuration.candidate_network_policy ==
4891 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004892 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004893 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004894 }
4895
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004896 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004897 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004898 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4899 }
4900
Qingsi Wanga2d60672018-04-11 16:57:45 -07004901 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004902 // No step delay is used while allocating ports.
4903 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4904 port_allocator_->set_candidate_filter(
4905 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004906 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004907
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004908 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004909 for (auto& turn_server : turn_servers_copy) {
4910 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004911 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004912 // Call this last since it may create pooled allocator sessions using the
4913 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004914 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004915 stun_servers, std::move(turn_servers_copy),
4916 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4917 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004918 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004919 return true;
4920}
4921
deadbeef91dd5672016-05-18 16:55:30 -07004922bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004923 const cricket::ServerAddresses& stun_servers,
4924 const std::vector<cricket::RelayServerConfig>& turn_servers,
4925 IceTransportsType type,
4926 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004927 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004928 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004929 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004930 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004931 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004932 // According to JSEP, after setLocalDescription, changing the candidate pool
4933 // size is not allowed, and changing the set of ICE servers will not result
4934 // in new candidates being gathered.
4935 if (local_description()) {
4936 port_allocator_->FreezeCandidatePool();
4937 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004938 // Add the custom tls turn servers if they exist.
4939 auto turn_servers_copy = turn_servers;
4940 for (auto& turn_server : turn_servers_copy) {
4941 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4942 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004943 // Call this last since it may create pooled allocator sessions using the
4944 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004945 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004946 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4947 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004948}
4949
Steve Antonba818672017-11-06 10:21:57 -08004950cricket::ChannelManager* PeerConnection::channel_manager() const {
4951 return factory_->channel_manager();
4952}
4953
Elad Alon99c3fe52017-10-13 16:29:40 +02004954bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004955 std::unique_ptr<RtcEventLogOutput> output,
4956 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004957 if (!event_log_) {
4958 return false;
4959 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004960 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004961}
4962
4963void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004964 if (event_log_) {
4965 event_log_->StopLogging();
4966 }
ivoc14d5dbe2016-07-04 07:06:55 -07004967}
nisseeaabdf62017-05-05 02:23:02 -07004968
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004969cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08004970 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004971 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004972 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08004973 if (channel && channel->content_name() == content_name) {
4974 return channel;
4975 }
Steve Anton75737c02017-11-06 10:37:17 -08004976 }
4977 if (rtp_data_channel() &&
4978 rtp_data_channel()->content_name() == content_name) {
4979 return rtp_data_channel();
4980 }
4981 return nullptr;
4982}
4983
4984bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004985 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004986 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004987 RTC_LOG(LS_INFO)
4988 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004989 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004990 return false;
4991 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004992 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004993 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004994 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004995 return false;
4996 }
4997
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004998 absl::optional<rtc::SSLRole> dtls_role;
4999 if (sctp_mid_) {
5000 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5001 } else if (is_caller_) {
5002 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5003 }
Zhi Huange830e682018-03-30 10:48:35 -07005004 if (dtls_role) {
5005 *role = *dtls_role;
5006 return true;
5007 }
5008 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005009}
5010
5011bool PeerConnection::GetSslRole(const std::string& content_name,
5012 rtc::SSLRole* role) {
5013 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005014 RTC_LOG(LS_INFO)
5015 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005016 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005017 return false;
5018 }
5019
Zhi Huange830e682018-03-30 10:48:35 -07005020 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5021 if (dtls_role) {
5022 *role = *dtls_role;
5023 return true;
5024 }
5025 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005026}
5027
Steve Antonf8470812017-12-04 10:46:21 -08005028void PeerConnection::SetSessionError(SessionError error,
5029 const std::string& error_desc) {
5030 RTC_DCHECK_RUN_ON(signaling_thread());
5031 if (error != session_error_) {
5032 session_error_ = error;
5033 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005034 }
5035}
5036
Zhi Huange830e682018-03-30 10:48:35 -07005037RTCError PeerConnection::UpdateSessionState(
5038 SdpType type,
5039 cricket::ContentSource source,
5040 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005041 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005042
5043 // If there's already a pending error then no state transition should happen.
5044 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005045 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005046
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005047 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005048 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005049 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005050 }
5051
5052 // Update the signaling state according to the specified state machine (see
5053 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005054 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005055 ChangeSignalingState(source == cricket::CS_LOCAL
5056 ? PeerConnectionInterface::kHaveLocalOffer
5057 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005058 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005059 ChangeSignalingState(source == cricket::CS_LOCAL
5060 ? PeerConnectionInterface::kHaveLocalPrAnswer
5061 : PeerConnectionInterface::kHaveRemotePrAnswer);
5062 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005063 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005064 ChangeSignalingState(PeerConnectionInterface::kStable);
5065 }
5066
5067 // Update internal objects according to the session description's media
5068 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005069 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005070 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005071 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005072 }
5073
Steve Anton8a006912017-12-04 15:25:56 -08005074 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005075}
5076
Steve Anton8a006912017-12-04 15:25:56 -08005077RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005078 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005079 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005080 const SessionDescriptionInterface* sdesc =
5081 (source == cricket::CS_LOCAL ? local_description()
5082 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005083 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005084
5085 // Push down the new SDP media section for each audio/video transceiver.
5086 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005087 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005088 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005089 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005090 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005091 continue;
5092 }
5093 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005094 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005095 if (!content_desc) {
5096 continue;
5097 }
5098 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005099 bool success = (source == cricket::CS_LOCAL)
5100 ? channel->SetLocalContent(content_desc, type, &error)
5101 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005102 if (!success) {
5103 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5104 }
5105 }
5106
5107 // If using the RtpDataChannel, push down the new SDP section for it too.
5108 if (rtp_data_channel_) {
5109 const ContentInfo* data_content =
5110 cricket::GetFirstDataContent(sdesc->description());
5111 if (data_content && !data_content->rejected) {
5112 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005113 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005114 if (data_desc) {
5115 std::string error;
5116 bool success =
5117 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005118 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005119 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005120 if (!success) {
5121 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5122 std::move(error));
5123 }
Steve Anton75737c02017-11-06 10:37:17 -08005124 }
5125 }
5126 }
Steve Antoned10bd92017-12-05 10:52:59 -08005127
Steve Anton75737c02017-11-06 10:37:17 -08005128 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5129 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5130 if (sctp_transport_ && local_description() && remote_description() &&
5131 cricket::GetFirstDataContent(local_description()->description()) &&
5132 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005133 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005134 RTC_FROM_HERE,
5135 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005136 if (!success) {
5137 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5138 "Failed to push down SCTP parameters.");
5139 }
Steve Anton75737c02017-11-06 10:37:17 -08005140 }
Steve Antoned10bd92017-12-05 10:52:59 -08005141
Steve Anton8a006912017-12-04 15:25:56 -08005142 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005143}
5144
5145bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5146 RTC_DCHECK(network_thread()->IsCurrent());
5147 RTC_DCHECK(local_description());
5148 RTC_DCHECK(remote_description());
5149 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5150 // When we support "max-message-size", that would also be pushed down here.
5151 return sctp_transport_->Start(
5152 GetSctpPort(local_description()->description()),
5153 GetSctpPort(remote_description()->description()));
5154}
5155
Steve Anton8a006912017-12-04 15:25:56 -08005156RTCError PeerConnection::PushdownTransportDescription(
5157 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005158 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005159 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005160
Zhi Huange830e682018-03-30 10:48:35 -07005161 if (source == cricket::CS_LOCAL) {
5162 const SessionDescriptionInterface* sdesc = local_description();
5163 RTC_DCHECK(sdesc);
5164 return transport_controller_->SetLocalDescription(type,
5165 sdesc->description());
5166 } else {
5167 const SessionDescriptionInterface* sdesc = remote_description();
5168 RTC_DCHECK(sdesc);
5169 return transport_controller_->SetRemoteDescription(type,
5170 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005171 }
Steve Anton75737c02017-11-06 10:37:17 -08005172}
5173
5174bool PeerConnection::GetTransportDescription(
5175 const SessionDescription* description,
5176 const std::string& content_name,
5177 cricket::TransportDescription* tdesc) {
5178 if (!description || !tdesc) {
5179 return false;
5180 }
5181 const TransportInfo* transport_info =
5182 description->GetTransportInfoByName(content_name);
5183 if (!transport_info) {
5184 return false;
5185 }
5186 *tdesc = transport_info->description;
5187 return true;
5188}
5189
Steve Anton75737c02017-11-06 10:37:17 -08005190cricket::IceConfig PeerConnection::ParseIceConfig(
5191 const PeerConnectionInterface::RTCConfiguration& config) const {
5192 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005193 switch (config.continual_gathering_policy) {
5194 case PeerConnectionInterface::GATHER_ONCE:
5195 gathering_policy = cricket::GATHER_ONCE;
5196 break;
5197 case PeerConnectionInterface::GATHER_CONTINUALLY:
5198 gathering_policy = cricket::GATHER_CONTINUALLY;
5199 break;
5200 default:
5201 RTC_NOTREACHED();
5202 gathering_policy = cricket::GATHER_ONCE;
5203 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005204
Steve Anton75737c02017-11-06 10:37:17 -08005205 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005206 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5207 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005208 ice_config.prioritize_most_likely_candidate_pairs =
5209 config.prioritize_most_likely_ice_candidate_pairs;
5210 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005211 RTCConfigurationToIceConfigOptionalInt(
5212 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005213 ice_config.continual_gathering_policy = gathering_policy;
5214 ice_config.presume_writable_when_fully_relayed =
5215 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005216 ice_config.ice_check_interval_strong_connectivity =
5217 config.ice_check_interval_strong_connectivity;
5218 ice_config.ice_check_interval_weak_connectivity =
5219 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005220 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005221 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005222 ice_config.regather_all_networks_interval_range =
5223 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005224 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005225 return ice_config;
5226}
5227
Steve Anton75737c02017-11-06 10:37:17 -08005228bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5229 std::string* track_id) {
5230 if (!local_description()) {
5231 return false;
5232 }
5233 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5234 track_id);
5235}
5236
5237bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5238 std::string* track_id) {
5239 if (!remote_description()) {
5240 return false;
5241 }
5242 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5243 track_id);
5244}
5245
5246bool PeerConnection::SendData(const cricket::SendDataParams& params,
5247 const rtc::CopyOnWriteBuffer& payload,
5248 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005249 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5250 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5251 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005252 return false;
5253 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005254 if (media_transport_) {
5255 SendDataParams send_params;
5256 send_params.type = ToWebrtcDataMessageType(params.type);
5257 send_params.ordered = params.ordered;
5258 if (params.max_rtx_count >= 0) {
5259 send_params.max_rtx_count = params.max_rtx_count;
5260 } else if (params.max_rtx_ms >= 0) {
5261 send_params.max_rtx_ms = params.max_rtx_ms;
5262 }
5263 return media_transport_->SendData(params.sid, send_params, payload).ok();
5264 }
Steve Anton75737c02017-11-06 10:37:17 -08005265 return rtp_data_channel_
5266 ? rtp_data_channel_->SendData(params, payload, result)
5267 : network_thread()->Invoke<bool>(
5268 RTC_FROM_HERE,
5269 Bind(&cricket::SctpTransportInternal::SendData,
5270 sctp_transport_.get(), params, payload, result));
5271}
5272
5273bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005274 RTC_DCHECK_RUN_ON(signaling_thread());
5275 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005276 // Don't log an error here, because DataChannels are expected to call
5277 // ConnectDataChannel in this state. It's the only way to initially tell
5278 // whether or not the underlying transport is ready.
5279 return false;
5280 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005281 if (media_transport_) {
5282 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5283 &DataChannel::OnChannelReady);
5284 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5285 &DataChannel::OnDataReceived);
5286 SignalMediaTransportChannelClosing_s.connect(
5287 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5288 SignalMediaTransportChannelClosed_s.connect(
5289 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5290 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005291 rtp_data_channel_->SignalReadyToSendData.connect(
5292 webrtc_data_channel, &DataChannel::OnChannelReady);
5293 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5294 &DataChannel::OnDataReceived);
5295 } else {
5296 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5297 &DataChannel::OnChannelReady);
5298 SignalSctpDataReceived.connect(webrtc_data_channel,
5299 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005300 SignalSctpClosingProcedureStartedRemotely.connect(
5301 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5302 SignalSctpClosingProcedureComplete.connect(
5303 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005304 }
5305 return true;
5306}
5307
5308void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005309 RTC_DCHECK_RUN_ON(signaling_thread());
5310 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005311 RTC_LOG(LS_ERROR)
5312 << "DisconnectDataChannel called when rtp_data_channel_ and "
5313 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005314 return;
5315 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005316 if (media_transport_) {
5317 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5318 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5319 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5320 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5321 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005322 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5323 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5324 } else {
5325 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5326 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005327 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5328 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005329 }
5330}
5331
5332void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005333 if (media_transport_) {
5334 // No-op. Media transport does not need to add streams.
5335 return;
5336 }
Steve Anton75737c02017-11-06 10:37:17 -08005337 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005338 RTC_LOG(LS_ERROR)
5339 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005340 return;
5341 }
5342 network_thread()->Invoke<void>(
5343 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5344 sctp_transport_.get(), sid));
5345}
5346
5347void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005348 if (media_transport_) {
5349 media_transport_->CloseChannel(sid);
5350 return;
5351 }
Steve Anton75737c02017-11-06 10:37:17 -08005352 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005353 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005354 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005355 return;
5356 }
5357 network_thread()->Invoke<void>(
5358 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5359 sctp_transport_.get(), sid));
5360}
5361
5362bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005363 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005364 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005365 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005366 sctp_ready_to_send_data_;
5367}
5368
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005369void PeerConnection::OnDataReceived(int channel_id,
5370 DataMessageType type,
5371 const rtc::CopyOnWriteBuffer& buffer) {
5372 cricket::ReceiveDataParams params;
5373 params.sid = channel_id;
5374 params.type = ToCricketDataMessageType(type);
5375 media_transport_invoker_->AsyncInvoke<void>(
5376 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5377 RTC_DCHECK_RUN_ON(signaling_thread());
5378 if (!HandleOpenMessage_s(params, buffer)) {
5379 SignalMediaTransportReceivedData_s(params, buffer);
5380 }
5381 });
5382}
5383
5384void PeerConnection::OnChannelClosing(int channel_id) {
5385 media_transport_invoker_->AsyncInvoke<void>(
5386 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5387 RTC_DCHECK_RUN_ON(signaling_thread());
5388 SignalMediaTransportChannelClosing_s(channel_id);
5389 });
5390}
5391
5392void PeerConnection::OnChannelClosed(int channel_id) {
5393 media_transport_invoker_->AsyncInvoke<void>(
5394 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5395 RTC_DCHECK_RUN_ON(signaling_thread());
5396 SignalMediaTransportChannelClosed_s(channel_id);
5397 });
5398}
5399
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005400absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005401 if (sctp_mid_ && transport_controller_) {
5402 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5403 if (dtls_transport) {
5404 return dtls_transport->transport_name();
5405 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005406 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005407 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005408 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005409}
5410
Qingsi Wang72a43a12018-02-20 16:03:18 -08005411cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5412 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005413 network_thread()->Invoke<void>(
5414 RTC_FROM_HERE,
5415 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5416 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005417 return candidate_states_list;
5418}
5419
Steve Anton5dfde182018-02-06 10:34:40 -08005420std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5421 const {
5422 std::map<std::string, std::string> transport_names_by_mid;
5423 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005424 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005425 if (channel) {
5426 transport_names_by_mid[channel->content_name()] =
5427 channel->transport_name();
5428 }
Steve Anton75737c02017-11-06 10:37:17 -08005429 }
Steve Anton5dfde182018-02-06 10:34:40 -08005430 if (rtp_data_channel_) {
5431 transport_names_by_mid[rtp_data_channel_->content_name()] =
5432 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005433 }
5434 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005435 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005436 RTC_DCHECK(transport_name);
5437 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005438 }
Steve Anton5dfde182018-02-06 10:34:40 -08005439 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005440}
5441
Steve Anton5dfde182018-02-06 10:34:40 -08005442std::map<std::string, cricket::TransportStats>
5443PeerConnection::GetTransportStatsByNames(
5444 const std::set<std::string>& transport_names) {
5445 if (!network_thread()->IsCurrent()) {
5446 return network_thread()
5447 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5448 RTC_FROM_HERE,
5449 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005450 }
Steve Anton5dfde182018-02-06 10:34:40 -08005451 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5452 for (const std::string& transport_name : transport_names) {
5453 cricket::TransportStats transport_stats;
5454 bool success =
5455 transport_controller_->GetStats(transport_name, &transport_stats);
5456 if (success) {
5457 transport_stats_by_name[transport_name] = std::move(transport_stats);
5458 } else {
5459 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5460 << transport_name;
5461 }
5462 }
5463 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005464}
5465
5466bool PeerConnection::GetLocalCertificate(
5467 const std::string& transport_name,
5468 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005469 if (!certificate) {
5470 return false;
5471 }
5472 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5473 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005474}
5475
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005476std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005477 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005478 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005479}
5480
5481cricket::DataChannelType PeerConnection::data_channel_type() const {
5482 return data_channel_type_;
5483}
5484
5485bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5486 return pending_ice_restarts_.find(content_name) !=
5487 pending_ice_restarts_.end();
5488}
5489
Steve Anton75737c02017-11-06 10:37:17 -08005490bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5491 return transport_controller_->NeedsIceRestart(content_name);
5492}
5493
5494void PeerConnection::OnCertificateReady(
5495 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5496 transport_controller_->SetLocalCertificate(certificate);
5497}
5498
5499void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005500 SetSessionError(SessionError::kTransport,
5501 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005502}
5503
5504void PeerConnection::OnTransportControllerConnectionState(
5505 cricket::IceConnectionState state) {
5506 switch (state) {
5507 case cricket::kIceConnectionConnecting:
5508 // If the current state is Connected or Completed, then there were
5509 // writable channels but now there are not, so the next state must
5510 // be Disconnected.
5511 // kIceConnectionConnecting is currently used as the default,
5512 // un-connected state by the TransportController, so its only use is
5513 // detecting disconnections.
5514 if (ice_connection_state_ ==
5515 PeerConnectionInterface::kIceConnectionConnected ||
5516 ice_connection_state_ ==
5517 PeerConnectionInterface::kIceConnectionCompleted) {
5518 SetIceConnectionState(
5519 PeerConnectionInterface::kIceConnectionDisconnected);
5520 }
5521 break;
5522 case cricket::kIceConnectionFailed:
5523 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5524 break;
5525 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005526 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005527 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005528 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005529 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005530 break;
5531 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005532 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005533 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005534 if (ice_connection_state_ !=
5535 PeerConnectionInterface::kIceConnectionConnected) {
5536 // If jumping directly from "checking" to "connected",
5537 // signal "connected" first.
5538 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5539 }
5540 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005541 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005542 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005543 break;
5544 default:
5545 RTC_NOTREACHED();
5546 }
5547}
5548
5549void PeerConnection::OnTransportControllerCandidatesGathered(
5550 const std::string& transport_name,
5551 const cricket::Candidates& candidates) {
5552 RTC_DCHECK(signaling_thread()->IsCurrent());
5553 int sdp_mline_index;
5554 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005555 RTC_LOG(LS_ERROR)
5556 << "OnTransportControllerCandidatesGathered: content name "
5557 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005558 return;
5559 }
5560
5561 for (cricket::Candidates::const_iterator citer = candidates.begin();
5562 citer != candidates.end(); ++citer) {
5563 // Use transport_name as the candidate media id.
5564 std::unique_ptr<JsepIceCandidate> candidate(
5565 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5566 if (local_description()) {
5567 mutable_local_description()->AddCandidate(candidate.get());
5568 }
5569 OnIceCandidate(std::move(candidate));
5570 }
5571}
5572
5573void PeerConnection::OnTransportControllerCandidatesRemoved(
5574 const std::vector<cricket::Candidate>& candidates) {
5575 RTC_DCHECK(signaling_thread()->IsCurrent());
5576 // Sanity check.
5577 for (const cricket::Candidate& candidate : candidates) {
5578 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005579 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005580 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005581 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005582 return;
5583 }
5584 }
5585
5586 if (local_description()) {
5587 mutable_local_description()->RemoveCandidates(candidates);
5588 }
5589 OnIceCandidatesRemoved(candidates);
5590}
5591
5592void PeerConnection::OnTransportControllerDtlsHandshakeError(
5593 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005594 RTC_HISTOGRAM_ENUMERATION(
5595 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5596 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005597}
5598
Steve Antoned10bd92017-12-05 10:52:59 -08005599void PeerConnection::EnableSending() {
5600 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005601 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005602 if (channel && !channel->enabled()) {
5603 channel->Enable(true);
5604 }
Steve Anton75737c02017-11-06 10:37:17 -08005605 }
5606
Steve Anton4171afb2017-11-20 10:20:22 -08005607 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005608 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005609 }
Steve Anton75737c02017-11-06 10:37:17 -08005610}
5611
5612// Returns the media index for a local ice candidate given the content name.
5613bool PeerConnection::GetLocalCandidateMediaIndex(
5614 const std::string& content_name,
5615 int* sdp_mline_index) {
5616 if (!local_description() || !sdp_mline_index) {
5617 return false;
5618 }
5619
5620 bool content_found = false;
5621 const ContentInfos& contents = local_description()->description()->contents();
5622 for (size_t index = 0; index < contents.size(); ++index) {
5623 if (contents[index].name == content_name) {
5624 *sdp_mline_index = static_cast<int>(index);
5625 content_found = true;
5626 break;
5627 }
5628 }
5629 return content_found;
5630}
5631
5632bool PeerConnection::UseCandidatesInSessionDescription(
5633 const SessionDescriptionInterface* remote_desc) {
5634 if (!remote_desc) {
5635 return true;
5636 }
5637 bool ret = true;
5638
5639 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5640 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5641 for (size_t n = 0; n < candidates->count(); ++n) {
5642 const IceCandidateInterface* candidate = candidates->at(n);
5643 bool valid = false;
5644 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5645 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005646 RTC_LOG(LS_INFO)
5647 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005648 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005649 }
5650 continue;
5651 }
5652 ret = UseCandidate(candidate);
5653 if (!ret) {
5654 break;
5655 }
5656 }
5657 }
5658 return ret;
5659}
5660
5661bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5662 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5663 size_t remote_content_size =
5664 remote_description()->description()->contents().size();
5665 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005666 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005667 return false;
5668 }
5669
5670 cricket::ContentInfo content =
5671 remote_description()->description()->contents()[mediacontent_index];
5672 std::vector<cricket::Candidate> candidates;
5673 candidates.push_back(candidate->candidate());
5674 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005675 RTCError error =
5676 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005677 if (error.ok()) {
5678 // Candidates successfully submitted for checking.
5679 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5680 ice_connection_state_ ==
5681 PeerConnectionInterface::kIceConnectionDisconnected) {
5682 // If state is New, then the session has just gotten its first remote ICE
5683 // candidates, so go to Checking.
5684 // If state is Disconnected, the session is re-using old candidates or
5685 // receiving additional ones, so go to Checking.
5686 // If state is Connected, stay Connected.
5687 // TODO(bemasc): If state is Connected, and the new candidates are for a
5688 // newly added transport, then the state actually _should_ move to
5689 // checking. Add a way to distinguish that case.
5690 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5691 }
5692 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005693 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005694 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005695 }
5696 return true;
5697}
5698
5699void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005700 // Destroy video channel first since it may have a pointer to the
5701 // voice channel.
5702 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005703 if (!video_info || video_info->rejected) {
5704 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005705 }
5706
Steve Anton6fec8802017-12-04 10:37:29 -08005707 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5708 if (!audio_info || audio_info->rejected) {
5709 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005710 }
5711
5712 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5713 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005714 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005715 }
5716}
5717
Steve Antondcc3c022017-12-22 16:02:54 -08005718RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5719 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005720 const cricket::ContentGroup* bundle_group = nullptr;
5721 if (configuration_.bundle_policy ==
5722 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005723 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005724 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005725 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5726 "max-bundle configured but session description "
5727 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005728 }
5729 }
Steve Antondcc3c022017-12-22 16:02:54 -08005730 return std::move(bundle_group);
5731}
5732
5733RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005734 // Creating the media channels. Transports should already have been created
5735 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005736 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005737 if (voice && !voice->rejected &&
5738 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005739 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005740 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005741 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5742 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005743 }
5744 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5745 }
5746
Steve Antondcc3c022017-12-22 16:02:54 -08005747 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005748 if (video && !video->rejected &&
5749 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005750 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005751 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005752 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5753 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005754 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005755 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
5757
Steve Antondcc3c022017-12-22 16:02:54 -08005758 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005759 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005760 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005761 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005762 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5763 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005764 }
5765 }
5766
Steve Anton8a006912017-12-04 15:25:56 -08005767 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005768}
5769
Steve Anton4171afb2017-11-20 10:20:22 -08005770// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005771cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005772 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005773 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005774 MediaTransportInterface* media_transport = nullptr;
5775 if (configuration_.use_media_transport) {
5776 media_transport = GetMediaTransport(mid);
5777 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005778
Steve Anton75737c02017-11-06 10:37:17 -08005779 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005780 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005781 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5782 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005783 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005784 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005785 }
Steve Anton75737c02017-11-06 10:37:17 -08005786 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5787 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005788 voice_channel->SignalSentPacket.connect(this,
5789 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005790 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005791
Steve Antoneda6ccd2017-12-04 10:21:55 -08005792 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005793}
5794
Steve Anton4171afb2017-11-20 10:20:22 -08005795// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005796cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005797 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005798 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5799
5800 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005801 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005802 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005803 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5804 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005805 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005806 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005807 }
Steve Anton75737c02017-11-06 10:37:17 -08005808 video_channel->SignalDtlsSrtpSetupFailure.connect(
5809 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005810 video_channel->SignalSentPacket.connect(this,
5811 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005812 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005813
Steve Antoneda6ccd2017-12-04 10:21:55 -08005814 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005815}
5816
Zhi Huange830e682018-03-30 10:48:35 -07005817bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005818 switch (data_channel_type_) {
5819 case cricket::DCT_MEDIA_TRANSPORT:
5820 if (network_thread()->Invoke<bool>(
5821 RTC_FROM_HERE,
5822 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5823 this, mid))) {
5824 for (const auto& channel : sctp_data_channels_) {
5825 channel->OnTransportChannelCreated();
5826 }
5827 return true;
5828 }
Steve Anton75737c02017-11-06 10:37:17 -08005829 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005830 case cricket::DCT_SCTP:
5831 if (!sctp_factory_) {
5832 RTC_LOG(LS_ERROR)
5833 << "Trying to create SCTP transport, but didn't compile with "
5834 "SCTP support (HAVE_SCTP)";
5835 return false;
5836 }
5837 if (!network_thread()->Invoke<bool>(
5838 RTC_FROM_HERE,
5839 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5840 return false;
5841 }
5842 for (const auto& channel : sctp_data_channels_) {
5843 channel->OnTransportChannelCreated();
5844 }
5845 return true;
5846 case cricket::DCT_RTP:
5847 default:
5848 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5849 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5850 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5851 SrtpRequired(), GetCryptoOptions());
5852 if (!rtp_data_channel_) {
5853 return false;
5854 }
5855 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5856 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5857 rtp_data_channel_->SignalSentPacket.connect(
5858 this, &PeerConnection::OnSentPacket_w);
5859 rtp_data_channel_->SetRtpTransport(rtp_transport);
5860 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005861 }
5862
Steve Anton75737c02017-11-06 10:37:17 -08005863 return true;
5864}
5865
5866Call::Stats PeerConnection::GetCallStats() {
5867 if (!worker_thread()->IsCurrent()) {
5868 return worker_thread()->Invoke<Call::Stats>(
5869 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5870 }
5871 if (call_) {
5872 return call_->GetStats();
5873 } else {
5874 return Call::Stats();
5875 }
5876}
5877
Zhi Huange830e682018-03-30 10:48:35 -07005878bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005879 RTC_DCHECK(network_thread()->IsCurrent());
5880 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005881 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005882 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005883 RTC_DCHECK(dtls_transport);
5884 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005885 RTC_DCHECK(sctp_transport_);
5886 sctp_invoker_.reset(new rtc::AsyncInvoker());
5887 sctp_transport_->SignalReadyToSendData.connect(
5888 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5889 sctp_transport_->SignalDataReceived.connect(
5890 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005891 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5892 // another thread. Would be nice if there was a helper class similar to
5893 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5894 // code.
5895 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5896 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5897 sctp_transport_->SignalClosingProcedureComplete.connect(
5898 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005899 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005900 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005901 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005902}
5903
5904void PeerConnection::DestroySctpTransport_n() {
5905 RTC_DCHECK(network_thread()->IsCurrent());
5906 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005907 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005908 sctp_invoker_.reset(nullptr);
5909 sctp_ready_to_send_data_ = false;
5910}
5911
5912void PeerConnection::OnSctpTransportReadyToSendData_n() {
5913 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5914 RTC_DCHECK(network_thread()->IsCurrent());
5915 // Note: Cannot use rtc::Bind here because it will grab a reference to
5916 // PeerConnection and potentially cause PeerConnection to live longer than
5917 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5918 // be destroyed before PeerConnection is destroyed, and at that point all
5919 // pending tasks will be cleared.
5920 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5921 OnSctpTransportReadyToSendData_s(true);
5922 });
5923}
5924
5925void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5926 RTC_DCHECK(signaling_thread()->IsCurrent());
5927 sctp_ready_to_send_data_ = ready;
5928 SignalSctpReadyToSendData(ready);
5929}
5930
5931void PeerConnection::OnSctpTransportDataReceived_n(
5932 const cricket::ReceiveDataParams& params,
5933 const rtc::CopyOnWriteBuffer& payload) {
5934 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5935 RTC_DCHECK(network_thread()->IsCurrent());
5936 // Note: Cannot use rtc::Bind here because it will grab a reference to
5937 // PeerConnection and potentially cause PeerConnection to live longer than
5938 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5939 // be destroyed before PeerConnection is destroyed, and at that point all
5940 // pending tasks will be cleared.
5941 sctp_invoker_->AsyncInvoke<void>(
5942 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5943 OnSctpTransportDataReceived_s(params, payload);
5944 });
5945}
5946
5947void PeerConnection::OnSctpTransportDataReceived_s(
5948 const cricket::ReceiveDataParams& params,
5949 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005950 RTC_DCHECK_RUN_ON(signaling_thread());
5951 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005952 SignalSctpDataReceived(params, payload);
5953 }
5954}
5955
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005956void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005957 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5958 RTC_DCHECK(network_thread()->IsCurrent());
5959 sctp_invoker_->AsyncInvoke<void>(
5960 RTC_FROM_HERE, signaling_thread(),
5961 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005962 &SignalSctpClosingProcedureStartedRemotely, sid));
5963}
5964
5965void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5966 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5967 RTC_DCHECK(network_thread()->IsCurrent());
5968 sctp_invoker_->AsyncInvoke<void>(
5969 RTC_FROM_HERE, signaling_thread(),
5970 rtc::Bind(&sigslot::signal1<int>::operator(),
5971 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005972}
5973
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005974bool PeerConnection::SetupMediaTransportForDataChannels_n(
5975 const std::string& mid) {
5976 media_transport_ = transport_controller_->GetMediaTransport(mid);
5977 if (!media_transport_) {
5978 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
5979 return false;
5980 }
5981
5982 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
5983 media_transport_->SetDataSink(this);
5984 media_transport_data_mid_ = mid;
5985 transport_controller_->SignalMediaTransportStateChanged.connect(
5986 this, &PeerConnection::OnMediaTransportStateChanged_n);
5987 // Check the initial state right away, in case transport is already writable.
5988 OnMediaTransportStateChanged_n();
5989 return true;
5990}
5991
5992void PeerConnection::TeardownMediaTransportForDataChannels_n() {
5993 if (!media_transport_) {
5994 return;
5995 }
5996 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
5997 media_transport_data_mid_.reset();
5998 media_transport_->SetDataSink(nullptr);
5999 media_transport_invoker_ = nullptr;
6000 media_transport_ = nullptr;
6001}
6002
6003void PeerConnection::OnMediaTransportStateChanged_n() {
6004 if (!media_transport_data_mid_ ||
6005 transport_controller_->GetMediaTransportState(
6006 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6007 return;
6008 }
6009 media_transport_invoker_->AsyncInvoke<void>(
6010 RTC_FROM_HERE, signaling_thread(), [this] {
6011 RTC_DCHECK_RUN_ON(signaling_thread());
6012 media_transport_ready_to_send_data_ = true;
6013 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6014 });
6015}
6016
Steve Anton75737c02017-11-06 10:37:17 -08006017// Returns false if bundle is enabled and rtcp_mux is disabled.
6018bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6019 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6020 if (!bundle_enabled)
6021 return true;
6022
6023 const cricket::ContentGroup* bundle_group =
6024 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6025 RTC_DCHECK(bundle_group != NULL);
6026
6027 const cricket::ContentInfos& contents = desc->contents();
6028 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6029 citer != contents.end(); ++citer) {
6030 const cricket::ContentInfo* content = (&*citer);
6031 RTC_DCHECK(content != NULL);
6032 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006033 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006034 if (!HasRtcpMuxEnabled(content))
6035 return false;
6036 }
6037 }
6038 // RTCP-MUX is enabled in all the contents.
6039 return true;
6040}
6041
6042bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006043 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006044}
6045
Steve Anton8a006912017-12-04 15:25:56 -08006046RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006047 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006048 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006049 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006050 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006051 }
6052
6053 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006054 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006055 }
6056
Steve Anton3828c062017-12-06 10:34:51 -08006057 SdpType type = sdesc->GetType();
6058 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6059 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006060 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006061 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006062 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006063 }
6064
6065 // Verify crypto settings.
6066 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006067 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6068 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006069 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006070 if (!crypto_error.ok()) {
6071 return crypto_error;
6072 }
Steve Anton75737c02017-11-06 10:37:17 -08006073 }
6074
6075 // Verify ice-ufrag and ice-pwd.
6076 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006077 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6078 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006079 }
6080
6081 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006082 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6083 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006084 }
6085
6086 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6087 // m-lines that do not rtcp-mux enabled.
6088
6089 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006090 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006091 // With an answer we want to compare the new answer session description with
6092 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006093 const cricket::SessionDescription* offer_desc =
6094 (source == cricket::CS_LOCAL) ? remote_description()->description()
6095 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006096 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6097 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6098 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006099 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6100 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006101 }
6102 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006103 // The re-offers should respect the order of m= sections in current
6104 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006105 // With a re-offer, either the current local or current remote descriptions
6106 // could be the most up to date, so we would like to check against both of
6107 // them if they exist. It could be the case that one of them has a 0 port
6108 // for a media section, but the other does not. This is important to check
6109 // against in the case that we are recycling an m= section.
6110 const cricket::SessionDescription* current_desc = nullptr;
6111 const cricket::SessionDescription* secondary_current_desc = nullptr;
6112 if (local_description()) {
6113 current_desc = local_description()->description();
6114 if (remote_description()) {
6115 secondary_current_desc = remote_description()->description();
6116 }
6117 } else if (remote_description()) {
6118 current_desc = remote_description()->description();
6119 }
Steve Anton75737c02017-11-06 10:37:17 -08006120 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006121 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6122 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006123 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6124 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006125 }
6126 }
6127
Steve Antonba42e992018-04-09 14:10:01 -07006128 if (IsUnifiedPlan()) {
6129 // Ensure that each audio and video media section has at most one
6130 // "StreamParams". This will return an error if receiving a session
6131 // description from a "Plan B" endpoint which adds multiple tracks of the
6132 // same type. With Unified Plan, there can only be at most one track per
6133 // media section.
6134 for (const ContentInfo& content : sdesc->description()->contents()) {
6135 const MediaContentDescription& desc = *content.description;
6136 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6137 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6138 desc.streams().size() > 1u) {
6139 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6140 "Media section has more than one track specified "
6141 "with a=ssrc lines which is not supported with "
6142 "Unified Plan.");
6143 }
6144 }
6145 }
6146
Steve Anton8a006912017-12-04 15:25:56 -08006147 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006148}
6149
Steve Anton3828c062017-12-06 10:34:51 -08006150bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006151 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006152 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006153 return (state == PeerConnectionInterface::kStable) ||
6154 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006155 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006156 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006157 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6158 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6159 }
6160}
6161
Steve Anton3828c062017-12-06 10:34:51 -08006162bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006163 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006164 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006165 return (state == PeerConnectionInterface::kStable) ||
6166 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006167 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006168 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006169 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6170 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6171 }
6172}
6173
Steve Antonf8470812017-12-04 10:46:21 -08006174const char* PeerConnection::SessionErrorToString(SessionError error) const {
6175 switch (error) {
6176 case SessionError::kNone:
6177 return "ERROR_NONE";
6178 case SessionError::kContent:
6179 return "ERROR_CONTENT";
6180 case SessionError::kTransport:
6181 return "ERROR_TRANSPORT";
6182 }
6183 RTC_NOTREACHED();
6184 return "";
6185}
6186
Steve Anton75737c02017-11-06 10:37:17 -08006187std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006188 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006189 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6190 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006191 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006192}
6193
Steve Anton8e20f172018-03-06 10:55:04 -08006194void PeerConnection::ReportSdpFormatReceived(
6195 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006196 int num_audio_mlines = 0;
6197 int num_video_mlines = 0;
6198 int num_audio_tracks = 0;
6199 int num_video_tracks = 0;
6200 for (const ContentInfo& content : remote_offer.description()->contents()) {
6201 cricket::MediaType media_type = content.media_description()->type();
6202 int num_tracks = std::max(
6203 1, static_cast<int>(content.media_description()->streams().size()));
6204 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6205 num_audio_mlines += 1;
6206 num_audio_tracks += num_tracks;
6207 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6208 num_video_mlines += 1;
6209 num_video_tracks += num_tracks;
6210 }
6211 }
6212 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6213 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6214 format = kSdpFormatReceivedComplexUnifiedPlan;
6215 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6216 format = kSdpFormatReceivedComplexPlanB;
6217 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6218 format = kSdpFormatReceivedSimple;
6219 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006220 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6221 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006222}
6223
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006224void PeerConnection::NoteUsageEvent(UsageEvent event) {
6225 RTC_DCHECK_RUN_ON(signaling_thread());
6226 usage_event_accumulator_ |= static_cast<int>(event);
6227}
6228
6229void PeerConnection::ReportUsagePattern() const {
6230 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006231 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6232 usage_event_accumulator_,
6233 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006234 const int bad_bits =
6235 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6236 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6237 const int good_bits =
6238 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6239 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6240 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6241 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6242 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006243 // If called after close(), we can't report, because observer may have
6244 // been deallocated, and therefore pointer is null. Write to log instead.
6245 if (observer_) {
6246 Observer()->OnInterestingUsage(usage_event_accumulator_);
6247 } else {
6248 RTC_LOG(LS_INFO) << "Interesting usage signature "
6249 << usage_event_accumulator_
6250 << " observed after observer shutdown";
6251 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006252 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006253}
6254
Steve Anton0ffaaa22018-02-23 10:31:30 -08006255void PeerConnection::ReportNegotiatedSdpSemantics(
6256 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006257 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006258 switch (answer.description()->msid_signaling()) {
6259 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006260 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006261 break;
6262 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006263 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006264 break;
6265 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006266 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006267 break;
6268 case cricket::kMsidSignalingMediaSection |
6269 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006270 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006271 break;
6272 default:
6273 RTC_NOTREACHED();
6274 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006275 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6276 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006277}
6278
Steve Anton75737c02017-11-06 10:37:17 -08006279// We need to check the local/remote description for the Transport instead of
6280// the session, because a new Transport added during renegotiation may have
6281// them unset while the session has them set from the previous negotiation.
6282// Not doing so may trigger the auto generation of transport description and
6283// mess up DTLS identity information, ICE credential, etc.
6284bool PeerConnection::ReadyToUseRemoteCandidate(
6285 const IceCandidateInterface* candidate,
6286 const SessionDescriptionInterface* remote_desc,
6287 bool* valid) {
6288 *valid = true;
6289
6290 const SessionDescriptionInterface* current_remote_desc =
6291 remote_desc ? remote_desc : remote_description();
6292
6293 if (!current_remote_desc) {
6294 return false;
6295 }
6296
6297 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6298 size_t remote_content_size =
6299 current_remote_desc->description()->contents().size();
6300 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006301 RTC_LOG(LS_ERROR)
6302 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6303 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006304
6305 *valid = false;
6306 return false;
6307 }
6308
6309 cricket::ContentInfo content =
6310 current_remote_desc->description()->contents()[mediacontent_index];
6311
6312 const std::string transport_name = GetTransportName(content.name);
6313 if (transport_name.empty()) {
6314 return false;
6315 }
Zhi Huange830e682018-03-30 10:48:35 -07006316 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006317}
6318
6319bool PeerConnection::SrtpRequired() const {
6320 return dtls_enabled_ ||
6321 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6322}
6323
6324void PeerConnection::OnTransportControllerGatheringState(
6325 cricket::IceGatheringState state) {
6326 RTC_DCHECK(signaling_thread()->IsCurrent());
6327 if (state == cricket::kIceGatheringGathering) {
6328 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6329 } else if (state == cricket::kIceGatheringComplete) {
6330 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6331 }
6332}
6333
6334void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006335 std::map<std::string, std::set<cricket::MediaType>>
6336 media_types_by_transport_name;
6337 for (auto transceiver : transceivers_) {
6338 if (transceiver->internal()->channel()) {
6339 const std::string& transport_name =
6340 transceiver->internal()->channel()->transport_name();
6341 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006342 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006343 }
Steve Anton75737c02017-11-06 10:37:17 -08006344 }
6345 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006346 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6347 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006348 }
Zhi Huange830e682018-03-30 10:48:35 -07006349
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006350 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006351 if (transport_name) {
6352 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006353 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006354 }
Zhi Huange830e682018-03-30 10:48:35 -07006355
Steve Antonc7b964c2018-02-01 14:39:45 -08006356 for (const auto& entry : media_types_by_transport_name) {
6357 const std::string& transport_name = entry.first;
6358 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006359 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006360 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006361 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006362 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006363 }
6364 }
6365}
6366// Walk through the ConnectionInfos to gather best connection usage
6367// for IPv4 and IPv6.
6368void PeerConnection::ReportBestConnectionState(
6369 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006370 for (const cricket::TransportChannelStats& channel_stats :
6371 stats.channel_stats) {
6372 for (const cricket::ConnectionInfo& connection_info :
6373 channel_stats.connection_infos) {
6374 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006375 continue;
6376 }
6377
Steve Antonc7b964c2018-02-01 14:39:45 -08006378 const cricket::Candidate& local = connection_info.local_candidate;
6379 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006380
6381 // Increment the counter for IceCandidatePairType.
6382 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6383 (local.type() == RELAY_PORT_TYPE &&
6384 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006385 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6386 GetIceCandidatePairCounter(local, remote),
6387 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006388 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006389 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6390 GetIceCandidatePairCounter(local, remote),
6391 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006392 } else {
6393 RTC_CHECK(0);
6394 }
Steve Anton75737c02017-11-06 10:37:17 -08006395
6396 // Increment the counter for IP type.
6397 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006398 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6399 kBestConnections_IPv4,
6400 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006401 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006402 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6403 kBestConnections_IPv6,
6404 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006405 } else {
6406 RTC_CHECK(0);
6407 }
6408
6409 return;
6410 }
6411 }
6412}
6413
6414void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006415 const cricket::TransportStats& stats,
6416 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006417 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6418 return;
6419 }
6420
6421 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6422 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6423 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6424 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6425 return;
6426 }
6427
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006428 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6429 for (cricket::MediaType media_type : media_types) {
6430 switch (media_type) {
6431 case cricket::MEDIA_TYPE_AUDIO:
6432 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6433 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6434 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6435 break;
6436 case cricket::MEDIA_TYPE_VIDEO:
6437 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6438 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6439 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6440 break;
6441 case cricket::MEDIA_TYPE_DATA:
6442 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6443 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6444 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6445 break;
6446 default:
6447 RTC_NOTREACHED();
6448 continue;
6449 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006450 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006451 }
6452
6453 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6454 for (cricket::MediaType media_type : media_types) {
6455 switch (media_type) {
6456 case cricket::MEDIA_TYPE_AUDIO:
6457 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6458 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6459 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6460 break;
6461 case cricket::MEDIA_TYPE_VIDEO:
6462 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6463 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6464 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6465 break;
6466 case cricket::MEDIA_TYPE_DATA:
6467 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6468 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6469 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6470 break;
6471 default:
6472 RTC_NOTREACHED();
6473 continue;
6474 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006475 }
Steve Anton75737c02017-11-06 10:37:17 -08006476 }
6477}
6478
6479void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6480 RTC_DCHECK(worker_thread()->IsCurrent());
6481 RTC_DCHECK(call_);
6482 call_->OnSentPacket(sent_packet);
6483}
6484
6485const std::string PeerConnection::GetTransportName(
6486 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006487 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006488 if (channel) {
6489 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006490 }
Steve Anton6fec8802017-12-04 10:37:29 -08006491 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006492 RTC_DCHECK(sctp_mid_);
6493 if (content_name == *sctp_mid_) {
6494 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006495 }
6496 }
6497 // Return an empty string if failed to retrieve the transport name.
6498 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006499}
6500
Steve Anton6fec8802017-12-04 10:37:29 -08006501void PeerConnection::DestroyTransceiverChannel(
6502 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6503 transceiver) {
6504 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006505
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006506 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006507 if (channel) {
6508 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006509 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006510 }
6511}
6512
6513void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006514 if (rtp_data_channel_) {
6515 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006516 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006517 rtp_data_channel_ = nullptr;
6518 }
6519
6520 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6521 // grab a reference to this PeerConnection. If this is called from the
6522 // PeerConnection destructor, the RefCountedObject vtable will have already
6523 // been destroyed (since it is a subclass of PeerConnection) and using
6524 // rtc::Bind will cause "Pure virtual function called" error to appear.
6525
6526 if (sctp_transport_) {
6527 OnDataChannelDestroyed();
6528 network_thread()->Invoke<void>(RTC_FROM_HERE,
6529 [this] { DestroySctpTransport_n(); });
6530 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006531
6532 if (media_transport_) {
6533 OnDataChannelDestroyed();
6534 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6535 RTC_DCHECK_RUN_ON(network_thread());
6536 TeardownMediaTransportForDataChannels_n();
6537 });
6538 }
Steve Anton6fec8802017-12-04 10:37:29 -08006539}
6540
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006541void PeerConnection::DestroyChannelInterface(
6542 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006543 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006544 switch (channel->media_type()) {
6545 case cricket::MEDIA_TYPE_AUDIO:
6546 channel_manager()->DestroyVoiceChannel(
6547 static_cast<cricket::VoiceChannel*>(channel));
6548 break;
6549 case cricket::MEDIA_TYPE_VIDEO:
6550 channel_manager()->DestroyVideoChannel(
6551 static_cast<cricket::VideoChannel*>(channel));
6552 break;
6553 case cricket::MEDIA_TYPE_DATA:
6554 channel_manager()->DestroyRtpDataChannel(
6555 static_cast<cricket::RtpDataChannel*>(channel));
6556 break;
6557 default:
6558 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6559 break;
6560 }
Zhi Huange830e682018-03-30 10:48:35 -07006561}
Steve Anton6fec8802017-12-04 10:37:29 -08006562
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006563bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006564 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006565 RtpTransportInternal* rtp_transport,
6566 cricket::DtlsTransportInternal* dtls_transport) {
6567 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006568 auto base_channel = GetChannel(mid);
6569 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006570 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006571 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006572 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006573 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006574 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006575 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006576}
6577
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006578PeerConnectionObserver* PeerConnection::Observer() const {
6579 // In earlier production code, the pointer was not cleared on close,
6580 // which might have led to undefined behavior if the observer was not
6581 // deallocated, or strange crashes if it was.
6582 // We use CHECK in order to catch such behavior if it exists.
6583 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6584 RTC_CHECK(observer_);
6585 return observer_;
6586}
6587
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006588CryptoOptions PeerConnection::GetCryptoOptions() {
6589 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6590 // after it has been removed.
6591 return configuration_.crypto_options.has_value()
6592 ? *configuration_.crypto_options
6593 : factory_->options().crypto_options;
6594}
6595
Harald Alvestrand89061872018-01-02 14:08:34 +01006596void PeerConnection::ClearStatsCache() {
6597 if (stats_collector_) {
6598 stats_collector_->ClearCachedStatsReport();
6599 }
6600}
6601
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006602void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006603 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6604 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006605}
6606
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006607} // namespace webrtc