blob: d7247c4c9f45f8de3fe0c1b22f1566dd91ee2bb6 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 10:37:17 -0800342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800389}
390
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100417
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100424 }
425}
426
Harald Alvestrand76829d72018-07-18 23:24:36 +0200427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 10:37:17 -0800432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800443 continue;
444 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800479 }
480 }
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 continue;
494 }
Steve Anton8a006912017-12-04 15:25:56 -0800495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800515 return false;
516 }
517 }
518 return true;
519}
520
Steve Anton75737c02017-11-06 10:37:17 -0800521// Get the SCTP port out of a SessionDescription.
522// Return -1 if not found.
523int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800524 const cricket::DataContentDescription* data_desc =
525 GetFirstDataContentDescription(session_description);
526 RTC_DCHECK(data_desc);
527 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800528 return -1;
529 }
Steve Anton75737c02017-11-06 10:37:17 -0800530 std::string value;
531 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
532 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800533 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800534 if (!codec.Matches(match_pattern)) {
535 continue;
536 }
537 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
538 return rtc::FromString<int>(value);
539 }
540 }
541 return -1;
542}
543
Steve Anton75737c02017-11-06 10:37:17 -0800544// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
545bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
546 const SessionDescriptionInterface* new_desc,
547 const std::string& content_name) {
548 if (!old_desc) {
549 return false;
550 }
551 const SessionDescription* new_sd = new_desc->description();
552 const SessionDescription* old_sd = old_desc->description();
553 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
554 if (!cinfo || cinfo->rejected) {
555 return false;
556 }
557 // If the content isn't rejected, check if ufrag and password has changed.
558 const cricket::TransportDescription* new_transport_desc =
559 new_sd->GetTransportDescriptionByName(content_name);
560 const cricket::TransportDescription* old_transport_desc =
561 old_sd->GetTransportDescriptionByName(content_name);
562 if (!new_transport_desc || !old_transport_desc) {
563 // No transport description exists. This is not an ICE restart.
564 return false;
565 }
566 if (cricket::IceCredentialsChanged(
567 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
568 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100569 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
570 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800571 return true;
572 }
573 return false;
574}
575
Steve Anton80dd7b52018-02-16 17:08:42 -0800576// Generates a string error message for SetLocalDescription/SetRemoteDescription
577// from an RTCError.
578std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
579 SdpType type,
580 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200581 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800582 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
583 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200584 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800585}
586
Seth Hampson5b4f0752018-04-02 16:31:36 -0700587std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
588 std::string output = "streams=[";
589 const char* separator = "";
590 for (const auto& stream_id : stream_ids) {
591 output.append(separator).append(stream_id);
592 separator = ", ";
593 }
594 output.append("]");
595 return output;
596}
597
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200598absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700599 int rtc_configuration_parameter) {
600 if (rtc_configuration_parameter ==
601 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200602 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700603 }
604 return rtc_configuration_parameter;
605}
606
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800607cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
608 switch (type) {
609 case DataMessageType::kText:
610 return cricket::DMT_TEXT;
611 case DataMessageType::kBinary:
612 return cricket::DMT_BINARY;
613 case DataMessageType::kControl:
614 return cricket::DMT_CONTROL;
615 default:
616 return cricket::DMT_NONE;
617 }
618 return cricket::DMT_NONE;
619}
620
621DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
622 switch (type) {
623 case cricket::DMT_TEXT:
624 return DataMessageType::kText;
625 case cricket::DMT_BINARY:
626 return DataMessageType::kBinary;
627 case cricket::DMT_CONTROL:
628 return DataMessageType::kControl;
629 case cricket::DMT_NONE:
630 default:
631 RTC_NOTREACHED();
632 }
633 return DataMessageType::kControl;
634}
635
Steve Anton75737c02017-11-06 10:37:17 -0800636} // namespace
637
Henrik Boström31638672017-11-23 17:48:32 +0100638// Upon completion, posts a task to execute the callback of the
639// SetSessionDescriptionObserver asynchronously on the same thread. At this
640// point, the state of the peer connection might no longer reflect the effects
641// of the SetRemoteDescription operation, as the peer connection could have been
642// modified during the post.
643// TODO(hbos): Remove this class once we remove the version of
644// PeerConnectionInterface::SetRemoteDescription() that takes a
645// SetSessionDescriptionObserver as an argument.
646class PeerConnection::SetRemoteDescriptionObserverAdapter
647 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
648 public:
649 SetRemoteDescriptionObserverAdapter(
650 rtc::scoped_refptr<PeerConnection> pc,
651 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
652 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
653
654 // SetRemoteDescriptionObserverInterface implementation.
655 void OnSetRemoteDescriptionComplete(RTCError error) override {
656 if (error.ok())
657 pc_->PostSetSessionDescriptionSuccess(wrapper_);
658 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100659 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100660 }
661
662 private:
663 rtc::scoped_refptr<PeerConnection> pc_;
664 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
665};
666
deadbeef293e9262017-01-11 12:28:30 -0800667bool PeerConnectionInterface::RTCConfiguration::operator==(
668 const PeerConnectionInterface::RTCConfiguration& o) const {
669 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700670 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800671 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000672 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700673 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800674 BundlePolicy bundle_policy;
675 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700676 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
677 int ice_candidate_pool_size;
678 bool disable_ipv6;
679 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700680 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100681 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700682 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200683 absl::optional<int> screencast_min_bitrate;
684 absl::optional<bool> combined_audio_video_bwe;
685 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800686 TcpCandidatePolicy tcp_candidate_policy;
687 CandidateNetworkPolicy candidate_network_policy;
688 int audio_jitter_buffer_max_packets;
689 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100690 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800691 int ice_connection_receiving_timeout;
692 int ice_backup_candidate_pair_ping_interval;
693 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800694 bool prioritize_most_likely_ice_candidate_pairs;
695 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800696 bool prune_turn_ports;
697 bool presume_writable_when_fully_relayed;
698 bool enable_ice_renomination;
699 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200700 absl::optional<int> ice_check_interval_strong_connectivity;
701 absl::optional<int> ice_check_interval_weak_connectivity;
702 absl::optional<int> ice_check_min_interval;
703 absl::optional<int> ice_unwritable_timeout;
704 absl::optional<int> ice_unwritable_min_checks;
705 absl::optional<int> stun_candidate_keepalive_interval;
706 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200707 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800708 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200709 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700710 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700711 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700712 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700713 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100714 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800715 };
716 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
717 "Did you add something to RTCConfiguration and forget to "
718 "update operator==?");
719 return type == o.type && servers == o.servers &&
720 bundle_policy == o.bundle_policy &&
721 rtcp_mux_policy == o.rtcp_mux_policy &&
722 tcp_candidate_policy == o.tcp_candidate_policy &&
723 candidate_network_policy == o.candidate_network_policy &&
724 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
725 audio_jitter_buffer_fast_accelerate ==
726 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100727 audio_jitter_buffer_min_delay_ms ==
728 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800729 ice_connection_receiving_timeout ==
730 o.ice_connection_receiving_timeout &&
731 ice_backup_candidate_pair_ping_interval ==
732 o.ice_backup_candidate_pair_ping_interval &&
733 continual_gathering_policy == o.continual_gathering_policy &&
734 certificates == o.certificates &&
735 prioritize_most_likely_ice_candidate_pairs ==
736 o.prioritize_most_likely_ice_candidate_pairs &&
737 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800738 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700739 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100740 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800741 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800742 screencast_min_bitrate == o.screencast_min_bitrate &&
743 combined_audio_video_bwe == o.combined_audio_video_bwe &&
744 enable_dtls_srtp == o.enable_dtls_srtp &&
745 ice_candidate_pool_size == o.ice_candidate_pool_size &&
746 prune_turn_ports == o.prune_turn_ports &&
747 presume_writable_when_fully_relayed ==
748 o.presume_writable_when_fully_relayed &&
749 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800750 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800751 ice_check_interval_strong_connectivity ==
752 o.ice_check_interval_strong_connectivity &&
753 ice_check_interval_weak_connectivity ==
754 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700755 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700756 ice_unwritable_timeout == o.ice_unwritable_timeout &&
757 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800758 stun_candidate_keepalive_interval ==
759 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200760 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800761 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800762 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700763 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700764 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700765 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700766 use_media_transport_for_data_channels ==
767 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100768 crypto_options == o.crypto_options &&
769 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800770}
771
772bool PeerConnectionInterface::RTCConfiguration::operator!=(
773 const PeerConnectionInterface::RTCConfiguration& o) const {
774 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800775}
776
zhihuang8f65cdf2016-05-06 18:40:30 -0700777// Generate a RTCP CNAME when a PeerConnection is created.
778std::string GenerateRtcpCname() {
779 std::string cname;
780 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100781 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800782 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700783 }
784 return cname;
785}
786
zhihuang1c378ed2017-08-17 14:10:50 -0700787bool ValidateOfferAnswerOptions(
788 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
789 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
790 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700791}
792
zhihuang1c378ed2017-08-17 14:10:50 -0700793// From |rtc_options|, fill parts of |session_options| shared by all generated
794// m= sections (in other words, nothing that involves a map/array).
795void ExtractSharedMediaSessionOptions(
796 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
797 cricket::MediaSessionOptions* session_options) {
798 session_options->vad_enabled = rtc_options.voice_activity_detection;
799 session_options->bundle_enabled = rtc_options.use_rtp_mux;
800}
zhihuanga77e6bb2017-08-14 18:17:48 -0700801
zhihuang38ede132017-06-15 12:52:32 -0700802PeerConnection::PeerConnection(PeerConnectionFactory* factory,
803 std::unique_ptr<RtcEventLog> event_log,
804 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700806 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700807 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700808 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700809 remote_streams_(StreamCollection::Create()),
810 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811
812PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100813 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800814 RTC_DCHECK_RUN_ON(signaling_thread());
815
Steve Anton8af21862017-12-15 11:20:13 -0800816 // Need to stop transceivers before destroying the stats collector because
817 // AudioRtpSender has a reference to the StatsCollector it will update when
818 // stopping.
819 for (auto transceiver : transceivers_) {
820 transceiver->Stop();
821 }
Steve Anton4171afb2017-11-20 10:20:22 -0800822
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700823 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800824 if (stats_collector_) {
825 stats_collector_->WaitForPendingRequest();
826 stats_collector_ = nullptr;
827 }
Steve Anton75737c02017-11-06 10:37:17 -0800828
Steve Anton8af21862017-12-15 11:20:13 -0800829 // Don't destroy BaseChannels until after stats has been cleaned up so that
830 // the last stats request can still read from the channels.
831 DestroyAllChannels();
832
Mirko Bonadei675513b2017-11-09 11:09:25 +0100833 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800834
835 webrtc_session_desc_factory_.reset();
836 sctp_invoker_.reset();
837 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800838 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800839 transport_controller_.reset();
840
deadbeef91dd5672016-05-18 16:55:30 -0700841 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700842 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700843 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700844 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700845 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700846 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800847 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700848 event_log_.reset();
849 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000850}
851
Steve Anton8af21862017-12-15 11:20:13 -0800852void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800853 // Destroy video channels first since they may have a pointer to a voice
854 // channel.
855 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800856 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800857 DestroyTransceiverChannel(transceiver);
858 }
859 }
860 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800861 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800862 DestroyTransceiverChannel(transceiver);
863 }
864 }
865 DestroyDataChannel();
866}
867
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000869 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700870 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100871 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700872
873 RTCError config_error = ValidateConfiguration(configuration);
874 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100875 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700876 return false;
877 }
878
Benjamin Wrightcab58882018-05-02 15:12:47 -0700879 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100880 RTC_LOG(LS_ERROR)
881 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100882 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800883 return false;
884 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200885
Benjamin Wrightcab58882018-05-02 15:12:47 -0700886 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800887 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100888 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100889 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800890 return false;
891 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700892
Benjamin Wrightcab58882018-05-02 15:12:47 -0700893 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700894 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700895 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700896 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800897
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200898 cricket::ServerAddresses stun_servers;
899 std::vector<cricket::RelayServerConfig> turn_servers;
900
901 RTCErrorType parse_error =
902 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
903 if (parse_error != RTCErrorType::NONE) {
904 return false;
905 }
906
deadbeef91dd5672016-05-18 16:55:30 -0700907 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700908 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700909 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200910 RTC_FROM_HERE,
911 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
912 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000913 return false;
914 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200915 // If initialization was successful, note if STUN or TURN servers
916 // were supplied.
917 if (!stun_servers.empty()) {
918 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
919 }
920 if (!turn_servers.empty()) {
921 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
922 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700924 // Send information about IPv4/IPv6 status.
925 PeerConnectionAddressFamilyCounter address_family;
926 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
927 address_family = kPeerConnection_IPv6;
928 } else {
929 address_family = kPeerConnection_IPv4;
930 }
931 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
932 kPeerConnectionAddressFamilyCounter_Max);
933
Zhi Huange830e682018-03-30 10:48:35 -0700934 const PeerConnectionFactoryInterface::Options& options = factory_->options();
935
Steve Anton75737c02017-11-06 10:37:17 -0800936 // RFC 3264: The numeric value of the session id and version in the
937 // o line MUST be representable with a "64 bit signed integer".
938 // Due to this constraint session id |session_id_| is max limited to
939 // LLONG_MAX.
940 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700941 JsepTransportController::Config config;
942 config.redetermine_role_on_ice_restart =
943 configuration.redetermine_role_on_ice_restart;
944 config.ssl_max_version = factory_->options().ssl_max_version;
945 config.disable_encryption = options.disable_encryption;
946 config.bundle_policy = configuration.bundle_policy;
947 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700948 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
949 // stub.
950 config.crypto_options = configuration.crypto_options.has_value()
951 ? *configuration.crypto_options
952 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700953 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700954 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700955#if defined(ENABLE_EXTERNAL_AUTH)
956 config.enable_external_auth = true;
957#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700958 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700959
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700960 if (configuration.use_media_transport ||
961 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700962 if (!factory_->media_transport_factory()) {
963 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700964 << "PeerConnecton is initialized with use_media_transport = true or "
965 << "use_media_transport_for_data_channels = true "
966 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700967 return false;
968 }
969
970 config.media_transport_factory = factory_->media_transport_factory();
971 }
972
Zhi Huange830e682018-03-30 10:48:35 -0700973 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700974 signaling_thread(), network_thread(), port_allocator_.get(),
975 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700976 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +0000977 this, &PeerConnection::OnTransportControllerConnectionState);
978 transport_controller_->SignalStandardizedIceConnectionState.connect(
979 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +0200980 transport_controller_->SignalConnectionState.connect(
981 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700982 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800983 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700984 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800985 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700986 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800987 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
988 transport_controller_->SignalDtlsHandshakeError.connect(
989 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
990
991 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700992
deadbeefab9b2d12015-10-14 11:33:11 -0700993 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700994 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995
Steve Antonba818672017-11-06 10:21:57 -0800996 configuration_ = configuration;
997
Steve Anton75737c02017-11-06 10:37:17 -0800998 // Obtain a certificate from RTCConfiguration if any were provided (optional).
999 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1000 if (!configuration.certificates.empty()) {
1001 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1002 // just picking the first one. The decision should be made based on the DTLS
1003 // handshake. The DTLS negotiations need to know about all certificates.
1004 certificate = configuration.certificates[0];
1005 }
1006
Steve Antond25da372017-11-06 14:50:29 -08001007 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001008
1009 if (options.disable_encryption) {
1010 dtls_enabled_ = false;
1011 } else {
1012 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001013 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001014 // |configuration| can override the default |dtls_enabled_| value.
1015 if (configuration.enable_dtls_srtp) {
1016 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1017 }
1018 }
1019
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001020 if (configuration.use_media_transport_for_data_channels) {
1021 if (configuration.enable_rtp_data_channel) {
1022 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1023 "use_media_transport_for_data_channels are "
1024 "incompatible and cannot both be set to true";
1025 return false;
1026 }
1027 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1028 } else if (configuration.enable_rtp_data_channel) {
1029 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1030 // set. It takes precendence over the disable_sctp_data_channels
1031 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001032 data_channel_type_ = cricket::DCT_RTP;
1033 } else {
1034 // DTLS has to be enabled to use SCTP.
1035 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1036 data_channel_type_ = cricket::DCT_SCTP;
1037 }
1038 }
1039
1040 video_options_.screencast_min_bitrate_kbps =
1041 configuration.screencast_min_bitrate;
1042 audio_options_.combined_audio_video_bwe =
1043 configuration.combined_audio_video_bwe;
1044
1045 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001046 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001047
1048 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001049 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001050
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001051 audio_options_.audio_jitter_buffer_min_delay_ms =
1052 configuration.audio_jitter_buffer_min_delay_ms;
1053
Steve Anton75737c02017-11-06 10:37:17 -08001054 // Whether the certificate generator/certificate is null or not determines
1055 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1056 // the right instructions by clearing the variables if needed.
1057 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001058 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001059 certificate = nullptr;
1060 } else if (certificate) {
1061 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001062 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001063 }
1064
1065 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1066 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001067 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001068 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1069 this, &PeerConnection::OnCertificateReady);
1070
1071 if (options.disable_encryption) {
1072 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1073 }
1074
1075 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001076 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001077 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001078
Steve Anton4171afb2017-11-20 10:20:22 -08001079 // Add default audio/video transceivers for Plan B SDP.
1080 if (!IsUnifiedPlan()) {
1081 transceivers_.push_back(
1082 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1083 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1084 transceivers_.push_back(
1085 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1086 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1087 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001088 int delay_ms =
1089 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001090 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1091 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001092 return true;
1093}
1094
Steve Anton038834f2017-07-14 15:59:59 -07001095RTCError PeerConnection::ValidateConfiguration(
1096 const RTCConfiguration& config) const {
1097 if (config.ice_regather_interval_range &&
1098 config.continual_gathering_policy == GATHER_ONCE) {
1099 return RTCError(RTCErrorType::INVALID_PARAMETER,
1100 "ice_regather_interval_range specified but continual "
1101 "gathering policy is GATHER_ONCE");
1102 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001103 auto result =
1104 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1105 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001106}
1107
Yves Gerey665174f2018-06-19 15:03:05 +02001108rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001109 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1110 "Plan SdpSemantics. Please use GetSenders "
1111 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001112 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001113}
1114
Yves Gerey665174f2018-06-19 15:03:05 +02001115rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001116 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1117 "Plan SdpSemantics. Please use GetReceivers "
1118 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001119 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001120}
1121
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001122bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001123 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1124 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001125 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001126 if (IsClosed()) {
1127 return false;
1128 }
deadbeefab9b2d12015-10-14 11:33:11 -07001129 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 return false;
1131 }
deadbeefab9b2d12015-10-14 11:33:11 -07001132
1133 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001134 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1135 observer->SignalAudioTrackAdded.connect(this,
1136 &PeerConnection::OnAudioTrackAdded);
1137 observer->SignalAudioTrackRemoved.connect(
1138 this, &PeerConnection::OnAudioTrackRemoved);
1139 observer->SignalVideoTrackAdded.connect(this,
1140 &PeerConnection::OnVideoTrackAdded);
1141 observer->SignalVideoTrackRemoved.connect(
1142 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001143 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001144
deadbeefab9b2d12015-10-14 11:33:11 -07001145 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001146 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001147 }
1148 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001149 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001150 }
1151
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001152 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001153 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001154 return true;
1155}
1156
1157void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001158 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1159 "Plan SdpSemantics. Please use RemoveTrack "
1160 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001161 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001162 if (!IsClosed()) {
1163 for (const auto& track : local_stream->GetAudioTracks()) {
1164 RemoveAudioTrack(track.get(), local_stream);
1165 }
1166 for (const auto& track : local_stream->GetVideoTracks()) {
1167 RemoveVideoTrack(track.get(), local_stream);
1168 }
deadbeefab9b2d12015-10-14 11:33:11 -07001169 }
deadbeefab9b2d12015-10-14 11:33:11 -07001170 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001171 stream_observers_.erase(
1172 std::remove_if(
1173 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001174 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001175 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001176 }),
1177 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001178
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001179 if (IsClosed()) {
1180 return;
1181 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001182 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183}
1184
Steve Anton2d6c76a2018-01-05 17:10:52 -08001185RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001186 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001187 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001188 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001189 if (!track) {
1190 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1191 }
1192 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1193 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1194 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1195 "Track has invalid kind: " + track->kind());
1196 }
Steve Antonf9381f02017-12-14 10:23:57 -08001197 if (IsClosed()) {
1198 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1199 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001200 }
Steve Anton4171afb2017-11-20 10:20:22 -08001201 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001202 LOG_AND_RETURN_ERROR(
1203 RTCErrorType::INVALID_PARAMETER,
1204 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001205 }
Steve Antonf9381f02017-12-14 10:23:57 -08001206 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001207 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1208 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001209 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001210 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001211 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001212 }
1213 return sender_or_error;
1214}
deadbeefe1f9d832016-01-14 15:35:42 -08001215
Steve Antonf9381f02017-12-14 10:23:57 -08001216RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1217PeerConnection::AddTrackPlanB(
1218 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001219 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001220 if (stream_ids.size() > 1u) {
1221 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1222 "AddTrack with more than one stream is not "
1223 "supported with Plan B semantics.");
1224 }
1225 std::vector<std::string> adjusted_stream_ids = stream_ids;
1226 if (adjusted_stream_ids.empty()) {
1227 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1228 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001229 cricket::MediaType media_type =
1230 (track->kind() == MediaStreamTrackInterface::kAudioKind
1231 ? cricket::MEDIA_TYPE_AUDIO
1232 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001233 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001234 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001235 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001236 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001237 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001238 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001239 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001240 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001241 if (sender_info) {
1242 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001243 }
Steve Antonf9381f02017-12-14 10:23:57 -08001244 } else {
1245 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001246 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001247 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001248 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001249 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001250 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001251 if (sender_info) {
1252 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001253 }
deadbeefe1f9d832016-01-14 15:35:42 -08001254 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001255 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001256}
deadbeefe1f9d832016-01-14 15:35:42 -08001257
Steve Antonf9381f02017-12-14 10:23:57 -08001258RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1259PeerConnection::AddTrackUnifiedPlan(
1260 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001261 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001262 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1263 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001264 RTC_LOG(LS_INFO) << "Reusing an existing "
1265 << cricket::MediaTypeToString(transceiver->media_type())
1266 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001267 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001268 transceiver->internal()->set_direction(
1269 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001270 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001271 transceiver->internal()->set_direction(
1272 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001273 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001274 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001275 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001276 } else {
1277 cricket::MediaType media_type =
1278 (track->kind() == MediaStreamTrackInterface::kAudioKind
1279 ? cricket::MEDIA_TYPE_AUDIO
1280 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001281 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1282 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001283 std::string sender_id = track->id();
1284 // Avoid creating a sender with an existing ID by generating a random ID.
1285 // This can happen if this is the second time AddTrack has created a sender
1286 // for this track.
1287 if (FindSenderById(sender_id)) {
1288 sender_id = rtc::CreateRandomUuid();
1289 }
Florent Castelli892acf02018-10-01 22:47:20 +02001290 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001291 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1292 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001293 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001294 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001295 }
Steve Antonf9381f02017-12-14 10:23:57 -08001296 return transceiver->sender();
1297}
1298
1299rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1300PeerConnection::FindFirstTransceiverForAddedTrack(
1301 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1302 RTC_DCHECK(track);
1303 for (auto transceiver : transceivers_) {
1304 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001305 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001306 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001307 !transceiver->internal()->has_ever_been_used_to_send() &&
1308 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001309 return transceiver;
1310 }
1311 }
1312 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001313}
1314
1315bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1316 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001317 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001318}
1319
Steve Anton24db5732018-07-23 10:27:33 -07001320RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001321 rtc::scoped_refptr<RtpSenderInterface> sender) {
1322 if (!sender) {
1323 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1324 }
deadbeefe1f9d832016-01-14 15:35:42 -08001325 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001326 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1327 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001328 }
Steve Antonf9381f02017-12-14 10:23:57 -08001329 if (IsUnifiedPlan()) {
1330 auto transceiver = FindTransceiverBySender(sender);
1331 if (!transceiver || !sender->track()) {
1332 return RTCError::OK();
1333 }
1334 sender->SetTrack(nullptr);
1335 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001336 transceiver->internal()->set_direction(
1337 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001338 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001339 transceiver->internal()->set_direction(
1340 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001341 }
Steve Anton4171afb2017-11-20 10:20:22 -08001342 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001343 bool removed;
1344 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1345 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1346 } else {
1347 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1348 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1349 }
1350 if (!removed) {
1351 LOG_AND_RETURN_ERROR(
1352 RTCErrorType::INVALID_PARAMETER,
1353 "Couldn't find sender " + sender->id() + " to remove.");
1354 }
Steve Anton4171afb2017-11-20 10:20:22 -08001355 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001356 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001357 return RTCError::OK();
1358}
1359
1360rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1361PeerConnection::FindTransceiverBySender(
1362 rtc::scoped_refptr<RtpSenderInterface> sender) {
1363 for (auto transceiver : transceivers_) {
1364 if (transceiver->sender() == sender) {
1365 return transceiver;
1366 }
1367 }
1368 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001369}
1370
Steve Anton9158ef62017-11-27 13:01:52 -08001371RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1372PeerConnection::AddTransceiver(
1373 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1374 return AddTransceiver(track, RtpTransceiverInit());
1375}
1376
1377RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1378PeerConnection::AddTransceiver(
1379 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1380 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001381 RTC_CHECK(IsUnifiedPlan())
1382 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001383 if (!track) {
1384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1385 }
1386 cricket::MediaType media_type;
1387 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1388 media_type = cricket::MEDIA_TYPE_AUDIO;
1389 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1390 media_type = cricket::MEDIA_TYPE_VIDEO;
1391 } else {
1392 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1393 "Track kind is not audio or video");
1394 }
1395 return AddTransceiver(media_type, track, init);
1396}
1397
1398RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1399PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1400 return AddTransceiver(media_type, RtpTransceiverInit());
1401}
1402
1403RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1404PeerConnection::AddTransceiver(cricket::MediaType media_type,
1405 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001406 RTC_CHECK(IsUnifiedPlan())
1407 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001408 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1409 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1410 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1411 "media type is not audio or video");
1412 }
1413 return AddTransceiver(media_type, nullptr, init);
1414}
1415
1416RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1417PeerConnection::AddTransceiver(
1418 cricket::MediaType media_type,
1419 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001420 const RtpTransceiverInit& init,
1421 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001422 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1423 media_type == cricket::MEDIA_TYPE_VIDEO));
1424 if (track) {
1425 RTC_DCHECK_EQ(media_type,
1426 (track->kind() == MediaStreamTrackInterface::kAudioKind
1427 ? cricket::MEDIA_TYPE_AUDIO
1428 : cricket::MEDIA_TYPE_VIDEO));
1429 }
1430
1431 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001432 if (init.send_encodings.size() > 1) {
1433 LOG_AND_RETURN_ERROR(
1434 RTCErrorType::UNSUPPORTED_PARAMETER,
1435 "Attempted to create an encoder with more than 1 encoding parameter.");
1436 }
1437
1438 for (const auto& encoding : init.send_encodings) {
1439 if (encoding.ssrc.has_value()) {
1440 LOG_AND_RETURN_ERROR(
1441 RTCErrorType::UNSUPPORTED_PARAMETER,
1442 "Attempted to set an unimplemented parameter of RtpParameters.");
1443 }
1444 }
1445
1446 RtpParameters parameters;
1447 parameters.encodings = init.send_encodings;
1448 if (UnimplementedRtpParameterHasValue(parameters)) {
1449 LOG_AND_RETURN_ERROR(
1450 RTCErrorType::UNSUPPORTED_PARAMETER,
1451 "Attempted to set an unimplemented parameter of RtpParameters.");
1452 }
Steve Anton9158ef62017-11-27 13:01:52 -08001453
Steve Anton3d954a62018-04-02 11:27:23 -07001454 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1455 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001456 // Set the sender ID equal to the track ID if the track is specified unless
1457 // that sender ID is already in use.
1458 std::string sender_id =
1459 (track && !FindSenderById(track->id()) ? track->id()
1460 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001461 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1462 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001463 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1464 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1465 transceiver->internal()->set_direction(init.direction);
1466
Steve Anton22da89f2018-01-25 13:58:07 -08001467 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001468 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001469 }
Steve Antonf9381f02017-12-14 10:23:57 -08001470
1471 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1472}
1473
Steve Anton02ee47c2018-01-10 16:26:06 -08001474rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1475PeerConnection::CreateSender(
1476 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001477 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001478 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001479 const std::vector<std::string>& stream_ids,
1480 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001481 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001482 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1483 RTC_DCHECK(!track ||
1484 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1485 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1486 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001487 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001488 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001489 } else {
1490 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1491 RTC_DCHECK(!track ||
1492 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1493 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001494 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001495 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001496 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001497 bool set_track_succeeded = sender->SetTrack(track);
1498 RTC_DCHECK(set_track_succeeded);
1499 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001500 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001501 return sender;
1502}
1503
1504rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1505PeerConnection::CreateReceiver(cricket::MediaType media_type,
1506 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001507 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1508 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001509 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001510 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001511 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1512 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001513 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001514 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001515 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001516 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001517 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1518 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001519 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001520 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001521 return receiver;
1522}
1523
1524rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1525PeerConnection::CreateAndAddTransceiver(
1526 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1527 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1528 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001529 // Ensure that the new sender does not have an ID that is already in use by
1530 // another sender.
1531 // Allow receiver IDs to conflict since those come from remote SDP (which
1532 // could be invalid, but should not cause a crash).
1533 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001534 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1535 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001536 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001537 transceiver->internal()->SignalNegotiationNeeded.connect(
1538 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001539 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001540}
1541
Steve Anton52d86772018-02-20 15:48:12 -08001542void PeerConnection::OnNegotiationNeeded() {
1543 RTC_DCHECK_RUN_ON(signaling_thread());
1544 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001545 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001546}
1547
deadbeeffac06552015-11-25 11:26:01 -08001548rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001549 const std::string& kind,
1550 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001551 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1552 "Plan SdpSemantics. Please use AddTransceiver "
1553 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001554 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001555 if (IsClosed()) {
1556 return nullptr;
1557 }
Steve Anton4171afb2017-11-20 10:20:22 -08001558
Seth Hampson5b4f0752018-04-02 16:31:36 -07001559 // Internally we need to have one stream with Plan B semantics, so we
1560 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001561 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001562 if (stream_id.empty()) {
1563 stream_ids.push_back(rtc::CreateRandomUuid());
1564 RTC_LOG(LS_INFO)
1565 << "No stream_id specified for sender. Generated stream ID: "
1566 << stream_ids[0];
1567 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001568 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001569 }
1570
Steve Anton4171afb2017-11-20 10:20:22 -08001571 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001572 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001573 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001574 auto* audio_sender = new AudioRtpSender(
1575 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001576 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001577 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001578 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001579 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001580 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001581 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001582 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001583 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001584 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001585 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001586 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001587 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001588 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001589 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001590 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001591 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001592
deadbeefe1f9d832016-01-14 15:35:42 -08001593 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001594}
1595
deadbeef70ab1a12015-09-28 16:53:55 -07001596std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1597 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001598 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001599 for (auto sender : GetSendersInternal()) {
1600 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001601 }
1602 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001603}
1604
Steve Anton4171afb2017-11-20 10:20:22 -08001605std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1606PeerConnection::GetSendersInternal() const {
1607 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1608 all_senders;
1609 for (auto transceiver : transceivers_) {
1610 auto senders = transceiver->internal()->senders();
1611 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1612 }
1613 return all_senders;
1614}
1615
deadbeef70ab1a12015-09-28 16:53:55 -07001616std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1617PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001618 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001619 for (const auto& receiver : GetReceiversInternal()) {
1620 ret.push_back(receiver);
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<
1626 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1627PeerConnection::GetReceiversInternal() const {
1628 std::vector<
1629 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1630 all_receivers;
1631 for (auto transceiver : transceivers_) {
1632 auto receivers = transceiver->internal()->receivers();
1633 all_receivers.insert(all_receivers.end(), receivers.begin(),
1634 receivers.end());
1635 }
1636 return all_receivers;
1637}
1638
Steve Anton9158ef62017-11-27 13:01:52 -08001639std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1640PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001641 RTC_CHECK(IsUnifiedPlan())
1642 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001643 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1644 for (auto transceiver : transceivers_) {
1645 all_transceivers.push_back(transceiver);
1646 }
1647 return all_transceivers;
1648}
1649
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001650bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001651 MediaStreamTrackInterface* track,
1652 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001653 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001654 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001655 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001656 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001657 return false;
1658 }
1659
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001660 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001661 // The StatsCollector is used to tell if a track is valid because it may
1662 // remember tracks that the PeerConnection previously removed.
1663 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001664 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1665 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001666 return false;
1667 }
Steve Antonad182762018-09-05 20:22:40 +00001668 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1669 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001670 return true;
1671}
1672
hbos74e1a4f2016-09-15 23:33:01 -07001673void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001674 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001675 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001676 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001677 stats_collector_->GetStatsReport(callback);
1678}
1679
Henrik Boström1df1bf82018-03-20 13:24:20 +01001680void PeerConnection::GetStats(
1681 rtc::scoped_refptr<RtpSenderInterface> selector,
1682 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1683 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1684 RTC_DCHECK(callback);
1685 RTC_DCHECK(stats_collector_);
1686 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1687 if (selector) {
1688 for (const auto& proxy_transceiver : transceivers_) {
1689 for (const auto& proxy_sender :
1690 proxy_transceiver->internal()->senders()) {
1691 if (proxy_sender == selector) {
1692 internal_sender = proxy_sender->internal();
1693 break;
1694 }
1695 }
1696 if (internal_sender)
1697 break;
1698 }
1699 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001700 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001701 // belong to the PeerConnection (in Plan B, senders can be removed from the
1702 // PeerConnection). This means that "all the stats objects representing the
1703 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1704 // produces an empty stats report.
1705 stats_collector_->GetStatsReport(internal_sender, callback);
1706}
1707
1708void PeerConnection::GetStats(
1709 rtc::scoped_refptr<RtpReceiverInterface> selector,
1710 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1711 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1712 RTC_DCHECK(callback);
1713 RTC_DCHECK(stats_collector_);
1714 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1715 if (selector) {
1716 for (const auto& proxy_transceiver : transceivers_) {
1717 for (const auto& proxy_receiver :
1718 proxy_transceiver->internal()->receivers()) {
1719 if (proxy_receiver == selector) {
1720 internal_receiver = proxy_receiver->internal();
1721 break;
1722 }
1723 }
1724 if (internal_receiver)
1725 break;
1726 }
1727 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001728 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001729 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1730 // the PeerConnection). This means that "all the stats objects representing
1731 // the selector" is an empty set. Invoking GetStatsReport() with a null
1732 // selector produces an empty stats report.
1733 stats_collector_->GetStatsReport(internal_receiver, callback);
1734}
1735
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001736PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1737 return signaling_state_;
1738}
1739
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001740PeerConnectionInterface::IceConnectionState
1741PeerConnection::ice_connection_state() {
1742 return ice_connection_state_;
1743}
1744
Alex Loiko9289eda2018-11-23 16:18:59 +00001745PeerConnectionInterface::IceConnectionState
1746PeerConnection::standardized_ice_connection_state() {
1747 return standardized_ice_connection_state_;
1748}
1749
Jonas Olsson635474e2018-10-18 15:58:17 +02001750PeerConnectionInterface::PeerConnectionState
1751PeerConnection::peer_connection_state() {
1752 return connection_state_;
1753}
1754
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001755PeerConnectionInterface::IceGatheringState
1756PeerConnection::ice_gathering_state() {
1757 return ice_gathering_state_;
1758}
1759
Yves Gerey665174f2018-06-19 15:03:05 +02001760rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001761 const std::string& label,
1762 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001763 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001764
deadbeefab9b2d12015-10-14 11:33:11 -07001765 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001766
kwibergd1fe2812016-04-27 06:47:29 -07001767 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001768 if (config) {
1769 internal_config.reset(new InternalDataChannelInit(*config));
1770 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001771 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001772 InternalCreateDataChannel(label, internal_config.get()));
1773 if (!channel.get()) {
1774 return nullptr;
1775 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001776
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001777 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1778 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001779 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001780 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001781 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001782 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001783 return DataChannelProxy::Create(signaling_thread(), channel.get());
1784}
1785
1786void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001787 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001788 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001789
nisse7ce109a2017-01-31 00:57:56 -08001790 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001791 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001792 return;
1793 }
deadbeefab9b2d12015-10-14 11:33:11 -07001794
Steve Anton8d3444d2017-10-20 15:30:51 -07001795 if (IsClosed()) {
1796 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001797 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001798 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001799 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001800 return;
1801 }
1802
zhihuang1c378ed2017-08-17 14:10:50 -07001803 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001804 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001805 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001806 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001807 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001808 return;
1809 }
1810
Steve Anton22da89f2018-01-25 13:58:07 -08001811 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1812 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1813 if (IsUnifiedPlan()) {
1814 RTCError error = HandleLegacyOfferOptions(options);
1815 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001816 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001817 return;
1818 }
1819 }
1820
zhihuang1c378ed2017-08-17 14:10:50 -07001821 cricket::MediaSessionOptions session_options;
1822 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001823 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001824}
1825
Steve Anton22da89f2018-01-25 13:58:07 -08001826RTCError PeerConnection::HandleLegacyOfferOptions(
1827 const RTCOfferAnswerOptions& options) {
1828 RTC_DCHECK(IsUnifiedPlan());
1829
1830 if (options.offer_to_receive_audio == 0) {
1831 RemoveRecvDirectionFromReceivingTransceiversOfType(
1832 cricket::MEDIA_TYPE_AUDIO);
1833 } else if (options.offer_to_receive_audio == 1) {
1834 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1835 } else if (options.offer_to_receive_audio > 1) {
1836 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1837 "offer_to_receive_audio > 1 is not supported.");
1838 }
1839
1840 if (options.offer_to_receive_video == 0) {
1841 RemoveRecvDirectionFromReceivingTransceiversOfType(
1842 cricket::MEDIA_TYPE_VIDEO);
1843 } else if (options.offer_to_receive_video == 1) {
1844 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1845 } else if (options.offer_to_receive_video > 1) {
1846 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1847 "offer_to_receive_video > 1 is not supported.");
1848 }
1849
1850 return RTCError::OK();
1851}
1852
1853void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1854 cricket::MediaType media_type) {
1855 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001856 RtpTransceiverDirection new_direction =
1857 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1858 if (new_direction != transceiver->direction()) {
1859 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1860 << " transceiver (MID="
1861 << transceiver->mid().value_or("<not set>") << ") from "
1862 << RtpTransceiverDirectionToString(
1863 transceiver->direction())
1864 << " to "
1865 << RtpTransceiverDirectionToString(new_direction)
1866 << " since CreateOffer specified offer_to_receive=0";
1867 transceiver->internal()->set_direction(new_direction);
1868 }
Steve Anton22da89f2018-01-25 13:58:07 -08001869 }
1870}
1871
1872void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1873 cricket::MediaType media_type) {
1874 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001875 RTC_LOG(LS_INFO)
1876 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1877 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001878 RtpTransceiverInit init;
1879 init.direction = RtpTransceiverDirection::kRecvOnly;
1880 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1881 }
1882}
1883
1884std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1885PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1886 std::vector<
1887 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1888 receiving_transceivers;
1889 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001890 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001891 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1892 receiving_transceivers.push_back(transceiver);
1893 }
1894 }
1895 return receiving_transceivers;
1896}
1897
htaa2a49d92016-03-04 02:51:39 -08001898void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1899 const RTCOfferAnswerOptions& options) {
1900 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001901 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001902 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001903 return;
1904 }
1905
Steve Antondffead82018-02-06 10:31:29 -08001906 if (!(signaling_state_ == kHaveRemoteOffer ||
1907 signaling_state_ == kHaveLocalPrAnswer)) {
1908 std::string error =
1909 "PeerConnection cannot create an answer in a state other than "
1910 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001911 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001912 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001913 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001914 return;
1915 }
1916
Steve Antondffead82018-02-06 10:31:29 -08001917 // The remote description should be set if we're in the right state.
1918 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001919
Steve Anton22da89f2018-01-25 13:58:07 -08001920 if (IsUnifiedPlan()) {
1921 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1922 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1923 "supported with Unified Plan semantics. Use the "
1924 "RtpTransceiver API instead.";
1925 }
1926 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1927 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1928 "supported with Unified Plan semantics. Use the "
1929 "RtpTransceiver API instead.";
1930 }
1931 }
1932
htaa2a49d92016-03-04 02:51:39 -08001933 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001934 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001935
Steve Antond25da372017-11-06 14:50:29 -08001936 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001937}
1938
1939void PeerConnection::SetLocalDescription(
1940 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001941 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001942 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001943
Steve Anton80dd7b52018-02-16 17:08:42 -08001944 // The SetLocalDescription contract is that we take ownership of the session
1945 // description regardless of the outcome, so wrap it in a unique_ptr right
1946 // away. Ideally, SetLocalDescription's signature will be changed to take the
1947 // description as a unique_ptr argument to formalize this agreement.
1948 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1949
nisse7ce109a2017-01-31 00:57:56 -08001950 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001951 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952 return;
1953 }
Steve Anton8a006912017-12-04 15:25:56 -08001954
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001956 PostSetSessionDescriptionFailure(
1957 observer,
1958 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001959 return;
1960 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001961
Steve Anton80dd7b52018-02-16 17:08:42 -08001962 // If a session error has occurred the PeerConnection is in a possibly
1963 // inconsistent state so fail right away.
1964 if (session_error() != SessionError::kNone) {
1965 std::string error_message = GetSessionErrorMsg();
1966 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001967 PostSetSessionDescriptionFailure(
1968 observer,
1969 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001970 return;
1971 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001972
Steve Anton80dd7b52018-02-16 17:08:42 -08001973 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1974 if (!error.ok()) {
1975 std::string error_message = GetSetDescriptionErrorMessage(
1976 cricket::CS_LOCAL, desc->GetType(), error);
1977 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001978 PostSetSessionDescriptionFailure(
1979 observer,
1980 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001981 return;
1982 }
1983
1984 // Grab the description type before moving ownership to ApplyLocalDescription,
1985 // which may destroy it before returning.
1986 const SdpType type = desc->GetType();
1987
1988 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001989 // |desc| may be destroyed at this point.
1990
1991 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001992 // If ApplyLocalDescription fails, the PeerConnection could be in an
1993 // inconsistent state, so act conservatively here and set the session error
1994 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1995 SetSessionError(SessionError::kContent, error.message());
1996 std::string error_message =
1997 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1998 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001999 PostSetSessionDescriptionFailure(
2000 observer,
2001 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002002 return;
2003 }
Steve Anton8a006912017-12-04 15:25:56 -08002004 RTC_DCHECK(local_description());
2005
2006 PostSetSessionDescriptionSuccess(observer);
2007
Steve Antonad182762018-09-05 20:22:40 +00002008 // MaybeStartGathering needs to be called after posting
2009 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2010 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002011 transport_controller_->MaybeStartGathering();
2012
Steve Antona3a92c22017-12-07 10:27:41 -08002013 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002014 // TODO(deadbeef): We already had to hop to the network thread for
2015 // MaybeStartGathering...
2016 network_thread()->Invoke<void>(
2017 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2018 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002019 // Make UMA notes about what was agreed to.
2020 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002021 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002022 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002023}
2024
2025RTCError PeerConnection::ApplyLocalDescription(
2026 std::unique_ptr<SessionDescriptionInterface> desc) {
2027 RTC_DCHECK_RUN_ON(signaling_thread());
2028 RTC_DCHECK(desc);
2029
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 // Update stats here so that we have the most recent stats for tracks and
2031 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002032 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002033
Steve Antondcc3c022017-12-22 16:02:54 -08002034 // Take a reference to the old local description since it's used below to
2035 // compare against the new local description. When setting the new local
2036 // description, grab ownership of the replaced session description in case it
2037 // is the same as |old_local_description|, to keep it alive for the duration
2038 // of the method.
2039 const SessionDescriptionInterface* old_local_description =
2040 local_description();
2041 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002042 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002043 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002044 replaced_local_description = pending_local_description_
2045 ? std::move(pending_local_description_)
2046 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002047 current_local_description_ = std::move(desc);
2048 pending_local_description_ = nullptr;
2049 current_remote_description_ = std::move(pending_remote_description_);
2050 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002051 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002052 pending_local_description_ = std::move(desc);
2053 }
2054 // The session description to apply now must be accessed by
2055 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002056 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002057
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002058 if (!is_caller_) {
2059 if (remote_description()) {
2060 // Remote description was applied first, so this PC is the callee.
2061 is_caller_ = false;
2062 } else {
2063 // Local description is applied first, so this PC is the caller.
2064 is_caller_ = true;
2065 }
2066 }
2067
Zhi Huange830e682018-03-30 10:48:35 -07002068 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2069 if (!error.ok()) {
2070 return error;
2071 }
2072
Steve Antondcc3c022017-12-22 16:02:54 -08002073 if (IsUnifiedPlan()) {
2074 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002075 cricket::CS_LOCAL, *local_description(), old_local_description,
2076 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002077 if (!error.ok()) {
2078 return error;
2079 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002080 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2081 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002082 for (auto transceiver : transceivers_) {
2083 const ContentInfo* content =
2084 FindMediaSectionForTransceiver(transceiver, local_description());
2085 if (!content) {
2086 continue;
2087 }
2088 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002089 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2090 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002091 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002092 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2093 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2094 // "recvonly", process the removal of a remote track for the media
2095 // description, given transceiver, removeList, and muteTracks.
2096 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2097 (transceiver->internal()->fired_direction() &&
2098 RtpTransceiverDirectionHasRecv(
2099 *transceiver->internal()->fired_direction()))) {
2100 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2101 &removed_streams);
2102 }
2103 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2104 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002105 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002106 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002107 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002108 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002109 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002110 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002111 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002112 }
2113 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002114 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002115 }
2116 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002117 // Media channels will be created only when offer is set. These may use new
2118 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002119 if (type == SdpType::kOffer) {
2120 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2121 // description is applied. Restore back to old description.
2122 RTCError error = CreateChannels(*local_description()->description());
2123 if (!error.ok()) {
2124 return error;
2125 }
2126 }
Steve Antondcc3c022017-12-22 16:02:54 -08002127 // Remove unused channels if MediaContentDescription is rejected.
2128 RemoveUnusedChannels(local_description()->description());
2129 }
Steve Anton8a006912017-12-04 15:25:56 -08002130
Zhi Huange830e682018-03-30 10:48:35 -07002131 error = UpdateSessionState(type, cricket::CS_LOCAL,
2132 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002133 if (!error.ok()) {
2134 return error;
2135 }
Steve Antondcc3c022017-12-22 16:02:54 -08002136
Steve Anton8a006912017-12-04 15:25:56 -08002137 if (remote_description()) {
2138 // Now that we have a local description, we can push down remote candidates.
2139 UseCandidatesInSessionDescription(remote_description());
2140 }
2141
2142 pending_ice_restarts_.clear();
2143 if (session_error() != SessionError::kNone) {
2144 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2145 }
2146
deadbeefab9b2d12015-10-14 11:33:11 -07002147 // If setting the description decided our SSL role, allocate any necessary
2148 // SCTP sids.
2149 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002150 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002151 AllocateSctpSids(role);
2152 }
2153
Steve Antond3679212018-01-17 17:41:02 -08002154 if (IsUnifiedPlan()) {
2155 for (auto transceiver : transceivers_) {
2156 const ContentInfo* content =
2157 FindMediaSectionForTransceiver(transceiver, local_description());
2158 if (!content) {
2159 continue;
2160 }
Steve Anton74255ff2018-01-24 18:32:57 -08002161 const auto& streams = content->media_description()->streams();
2162 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002163 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002164 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002165 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002166 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002167 } else {
2168 // 0 is a special value meaning "this sender has no associated send
2169 // stream". Need to call this so the sender won't attempt to configure
2170 // a no longer existing stream and run into DCHECKs in the lower
2171 // layers.
2172 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002173 }
2174 }
2175 } else {
2176 // Plan B semantics.
2177
Steve Antondcc3c022017-12-22 16:02:54 -08002178 // Update state and SSRC of local MediaStreams and DataChannels based on the
2179 // local session description.
2180 const cricket::ContentInfo* audio_content =
2181 GetFirstAudioContent(local_description()->description());
2182 if (audio_content) {
2183 if (audio_content->rejected) {
2184 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2185 } else {
2186 const cricket::AudioContentDescription* audio_desc =
2187 audio_content->media_description()->as_audio();
2188 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2189 }
deadbeeffaac4972015-11-12 15:33:07 -08002190 }
deadbeefab9b2d12015-10-14 11:33:11 -07002191
Steve Antondcc3c022017-12-22 16:02:54 -08002192 const cricket::ContentInfo* video_content =
2193 GetFirstVideoContent(local_description()->description());
2194 if (video_content) {
2195 if (video_content->rejected) {
2196 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2197 } else {
2198 const cricket::VideoContentDescription* video_desc =
2199 video_content->media_description()->as_video();
2200 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2201 }
deadbeeffaac4972015-11-12 15:33:07 -08002202 }
deadbeefab9b2d12015-10-14 11:33:11 -07002203 }
2204
2205 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002206 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002207 if (data_content) {
2208 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002209 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002210 if (rtc::starts_with(data_desc->protocol().data(),
2211 cricket::kMediaProtocolRtpPrefix)) {
2212 UpdateLocalRtpDataChannels(data_desc->streams());
2213 }
2214 }
2215
Steve Anton8a006912017-12-04 15:25:56 -08002216 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002217}
2218
2219void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002220 SetSessionDescriptionObserver* observer,
2221 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002222 SetRemoteDescription(
2223 std::unique_ptr<SessionDescriptionInterface>(desc),
2224 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2225 new SetRemoteDescriptionObserverAdapter(this, observer)));
2226}
2227
2228void PeerConnection::SetRemoteDescription(
2229 std::unique_ptr<SessionDescriptionInterface> desc,
2230 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002231 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002232
nisse7ce109a2017-01-31 00:57:56 -08002233 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002234 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235 return;
2236 }
Steve Anton8a006912017-12-04 15:25:56 -08002237
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002239 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002240 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002241 return;
2242 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002243
Steve Anton80dd7b52018-02-16 17:08:42 -08002244 // If a session error has occurred the PeerConnection is in a possibly
2245 // inconsistent state so fail right away.
2246 if (session_error() != SessionError::kNone) {
2247 std::string error_message = GetSessionErrorMsg();
2248 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2249 observer->OnSetRemoteDescriptionComplete(
2250 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2251 return;
2252 }
Steve Anton71439a62018-02-15 11:53:06 -08002253
Steve Antonba42e992018-04-09 14:10:01 -07002254 if (desc->GetType() == SdpType::kOffer) {
2255 // Report to UMA the format of the received offer.
2256 ReportSdpFormatReceived(*desc);
2257 }
2258
Steve Anton80dd7b52018-02-16 17:08:42 -08002259 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002260 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002261 std::string error_message = GetSetDescriptionErrorMessage(
2262 cricket::CS_REMOTE, desc->GetType(), error);
2263 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002264 observer->OnSetRemoteDescriptionComplete(
2265 RTCError(error.type(), std::move(error_message)));
2266 return;
2267 }
Steve Anton71439a62018-02-15 11:53:06 -08002268
Steve Anton80dd7b52018-02-16 17:08:42 -08002269 // Grab the description type before moving ownership to
2270 // ApplyRemoteDescription, which may destroy it before returning.
2271 const SdpType type = desc->GetType();
2272
2273 error = ApplyRemoteDescription(std::move(desc));
2274 // |desc| may be destroyed at this point.
2275
2276 if (!error.ok()) {
2277 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2278 // inconsistent state, so act conservatively here and set the session error
2279 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2280 SetSessionError(SessionError::kContent, error.message());
2281 std::string error_message =
2282 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2283 RTC_LOG(LS_ERROR) << error_message;
2284 observer->OnSetRemoteDescriptionComplete(
2285 RTCError(error.type(), std::move(error_message)));
2286 return;
2287 }
2288 RTC_DCHECK(remote_description());
2289
2290 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002291 // TODO(deadbeef): We already had to hop to the network thread for
2292 // MaybeStartGathering...
2293 network_thread()->Invoke<void>(
2294 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2295 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002296 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002297 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002298 }
2299
2300 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002301 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002302}
2303
2304RTCError PeerConnection::ApplyRemoteDescription(
2305 std::unique_ptr<SessionDescriptionInterface> desc) {
2306 RTC_DCHECK_RUN_ON(signaling_thread());
2307 RTC_DCHECK(desc);
2308
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002309 // Update stats here so that we have the most recent stats for tracks and
2310 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002311 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002312
Steve Antondcc3c022017-12-22 16:02:54 -08002313 // Take a reference to the old remote description since it's used below to
2314 // compare against the new remote description. When setting the new remote
2315 // description, grab ownership of the replaced session description in case it
2316 // is the same as |old_remote_description|, to keep it alive for the duration
2317 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002318 const SessionDescriptionInterface* old_remote_description =
2319 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002320 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002321 SdpType type = desc->GetType();
2322 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002323 replaced_remote_description = pending_remote_description_
2324 ? std::move(pending_remote_description_)
2325 : std::move(current_remote_description_);
2326 current_remote_description_ = std::move(desc);
2327 pending_remote_description_ = nullptr;
2328 current_local_description_ = std::move(pending_local_description_);
2329 } else {
2330 replaced_remote_description = std::move(pending_remote_description_);
2331 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002332 }
Steve Anton8a006912017-12-04 15:25:56 -08002333 // The session description to apply now must be accessed by
2334 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002335 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002336
Zhi Huange830e682018-03-30 10:48:35 -07002337 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2338 if (!error.ok()) {
2339 return error;
2340 }
Steve Anton8a006912017-12-04 15:25:56 -08002341 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002342 if (IsUnifiedPlan()) {
2343 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002344 cricket::CS_REMOTE, *remote_description(), local_description(),
2345 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002346 if (!error.ok()) {
2347 return error;
2348 }
Steve Antondcc3c022017-12-22 16:02:54 -08002349 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002350 // Media channels will be created only when offer is set. These may use new
2351 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002352 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002353 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002354 // description is applied. Restore back to old description.
2355 RTCError error = CreateChannels(*remote_description()->description());
2356 if (!error.ok()) {
2357 return error;
2358 }
2359 }
Steve Antondcc3c022017-12-22 16:02:54 -08002360 // Remove unused channels if MediaContentDescription is rejected.
2361 RemoveUnusedChannels(remote_description()->description());
2362 }
Steve Anton8a006912017-12-04 15:25:56 -08002363
Zhi Huange830e682018-03-30 10:48:35 -07002364 // NOTE: Candidates allocation will be initiated only when
2365 // SetLocalDescription is called.
2366 error = UpdateSessionState(type, cricket::CS_REMOTE,
2367 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002368 if (!error.ok()) {
2369 return error;
2370 }
2371
2372 if (local_description() &&
2373 !UseCandidatesInSessionDescription(remote_description())) {
2374 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2375 }
2376
2377 if (old_remote_description) {
2378 for (const cricket::ContentInfo& content :
2379 old_remote_description->description()->contents()) {
2380 // Check if this new SessionDescription contains new ICE ufrag and
2381 // password that indicates the remote peer requests an ICE restart.
2382 // TODO(deadbeef): When we start storing both the current and pending
2383 // remote description, this should reset pending_ice_restarts and compare
2384 // against the current description.
2385 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2386 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002387 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002388 pending_ice_restarts_.insert(content.name);
2389 }
2390 } else {
2391 // We retain all received candidates only if ICE is not restarted.
2392 // When ICE is restarted, all previous candidates belong to an old
2393 // generation and should not be kept.
2394 // TODO(deadbeef): This goes against the W3C spec which says the remote
2395 // description should only contain candidates from the last set remote
2396 // description plus any candidates added since then. We should remove
2397 // this once we're sure it won't break anything.
2398 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2399 old_remote_description, content.name, mutable_remote_description());
2400 }
2401 }
2402 }
2403
2404 if (session_error() != SessionError::kNone) {
2405 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2406 }
2407
2408 // Set the the ICE connection state to connecting since the connection may
2409 // become writable with peer reflexive candidates before any remote candidate
2410 // is signaled.
2411 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2412 // is to have a new signal the indicates a change in checking state from the
2413 // transport and expose a new checking() member from transport that can be
2414 // read to determine the current checking state. The existing SignalConnecting
2415 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002416 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002417 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002418 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2419 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2420 }
2421
deadbeefab9b2d12015-10-14 11:33:11 -07002422 // If setting the description decided our SSL role, allocate any necessary
2423 // SCTP sids.
2424 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002425 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002426 AllocateSctpSids(role);
2427 }
2428
Steve Antondcc3c022017-12-22 16:02:54 -08002429 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002430 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002431 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002432 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002433 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002434 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002435 for (auto transceiver : transceivers_) {
2436 const ContentInfo* content =
2437 FindMediaSectionForTransceiver(transceiver, remote_description());
2438 if (!content) {
2439 continue;
2440 }
2441 const MediaContentDescription* media_desc = content->media_description();
2442 RtpTransceiverDirection local_direction =
2443 RtpTransceiverDirectionReversed(media_desc->direction());
2444 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2445 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2446 // transceiver's current direction is neither sendrecv nor recvonly,
2447 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002448 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002449 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002450 // The remote description has signaled the stream IDs.
2451 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002452 }
Steve Antondcc3c022017-12-22 16:02:54 -08002453 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002454 (!transceiver->fired_direction() ||
2455 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002456 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002457 << content->name << " (added to "
2458 << GetStreamIdsString(stream_ids) << ").";
2459
2460 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2461 for (const std::string& stream_id : stream_ids) {
2462 rtc::scoped_refptr<MediaStreamInterface> stream =
2463 remote_streams_->find(stream_id);
2464 if (!stream) {
2465 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2466 MediaStream::Create(stream_id));
2467 remote_streams_->AddStream(stream);
2468 added_streams.push_back(stream);
2469 }
2470 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002471 }
Henrik Boström5b147782018-12-04 11:25:05 +01002472 // Special case: "a=msid" missing, use random stream ID.
2473 if (media_streams.empty() &&
2474 !(remote_description()->description()->msid_signaling() &
2475 cricket::kMsidSignalingMediaSection)) {
2476 if (!missing_msid_default_stream_) {
2477 missing_msid_default_stream_ = MediaStreamProxy::Create(
2478 rtc::Thread::Current(),
2479 MediaStream::Create(rtc::CreateRandomUuid()));
2480 added_streams.push_back(missing_msid_default_stream_);
2481 }
2482 media_streams.push_back(missing_msid_default_stream_);
2483 }
Steve Anton3172c032018-05-03 15:30:18 -07002484 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002485 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2486 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002487 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002488 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002489 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002490 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2491 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2492 // removal of a remote track for the media description, given transceiver,
2493 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002494 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002495 (transceiver->fired_direction() &&
2496 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2497 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2498 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002499 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002500 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2501 transceiver->internal()->set_fired_direction(local_direction);
2502 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2503 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002504 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002505 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2506 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002507 transceiver->internal()->set_current_direction(local_direction);
2508 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002509 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2510 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002511 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002512 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2513 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002514 transceiver->Stop();
2515 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002516 if (!content->rejected &&
2517 RtpTransceiverDirectionHasRecv(local_direction)) {
2518 // Set ssrc to 0 in the case of an unsignalled ssrc.
2519 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002520 if (!media_desc->streams().empty() &&
2521 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002522 ssrc = media_desc->streams()[0].first_ssrc();
2523 }
2524 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002525 }
Steve Antondcc3c022017-12-22 16:02:54 -08002526 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002527 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002528 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002529 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002530 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002531 observer->OnTrack(transceiver);
2532 observer->OnAddTrack(transceiver->receiver(),
2533 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002534 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002535 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002536 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002537 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002538 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002539 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002540 }
2541 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002542 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002543 }
Steve Antondcc3c022017-12-22 16:02:54 -08002544 }
2545
Henrik Boströmfdb92012017-11-09 19:55:44 +01002546 const cricket::ContentInfo* audio_content =
2547 GetFirstAudioContent(remote_description()->description());
2548 const cricket::ContentInfo* video_content =
2549 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002550 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002551 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002552 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002553 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002554 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002555 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002556
2557 // Check if the descriptions include streams, just in case the peer supports
2558 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002559 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002560 (audio_desc && !audio_desc->streams().empty()) ||
2561 (video_desc && !video_desc->streams().empty())) {
2562 remote_peer_supports_msid_ = true;
2563 }
deadbeefab9b2d12015-10-14 11:33:11 -07002564
2565 // We wait to signal new streams until we finish processing the description,
2566 // since only at that point will new streams have all their tracks.
2567 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2568
Steve Antondcc3c022017-12-22 16:02:54 -08002569 if (!IsUnifiedPlan()) {
2570 // TODO(steveanton): When removing RTP senders/receivers in response to a
2571 // rejected media section, there is some cleanup logic that expects the
2572 // voice/ video channel to still be set. But in this method the voice/video
2573 // channel would have been destroyed by the SetRemoteDescription caller
2574 // above so the cleanup that relies on them fails to run. The RemoveSenders
2575 // calls should be moved to right before the DestroyChannel calls to fix
2576 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002577
Steve Antondcc3c022017-12-22 16:02:54 -08002578 // Find all audio rtp streams and create corresponding remote AudioTracks
2579 // and MediaStreams.
2580 if (audio_content) {
2581 if (audio_content->rejected) {
2582 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2583 } else {
2584 bool default_audio_track_needed =
2585 !remote_peer_supports_msid_ &&
2586 RtpTransceiverDirectionHasSend(audio_desc->direction());
2587 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2588 default_audio_track_needed, audio_desc->type(),
2589 new_streams);
2590 }
deadbeeffaac4972015-11-12 15:33:07 -08002591 }
deadbeefab9b2d12015-10-14 11:33:11 -07002592
Steve Antondcc3c022017-12-22 16:02:54 -08002593 // Find all video rtp streams and create corresponding remote VideoTracks
2594 // and MediaStreams.
2595 if (video_content) {
2596 if (video_content->rejected) {
2597 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2598 } else {
2599 bool default_video_track_needed =
2600 !remote_peer_supports_msid_ &&
2601 RtpTransceiverDirectionHasSend(video_desc->direction());
2602 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2603 default_video_track_needed, video_desc->type(),
2604 new_streams);
2605 }
deadbeeffaac4972015-11-12 15:33:07 -08002606 }
deadbeefab9b2d12015-10-14 11:33:11 -07002607
Steve Antondcc3c022017-12-22 16:02:54 -08002608 // Update the DataChannels with the information from the remote peer.
2609 if (data_desc) {
2610 if (rtc::starts_with(data_desc->protocol().data(),
2611 cricket::kMediaProtocolRtpPrefix)) {
2612 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2613 }
deadbeefab9b2d12015-10-14 11:33:11 -07002614 }
deadbeefab9b2d12015-10-14 11:33:11 -07002615
Steve Antondcc3c022017-12-22 16:02:54 -08002616 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002617 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002618 for (size_t i = 0; i < new_streams->count(); ++i) {
2619 MediaStreamInterface* new_stream = new_streams->at(i);
2620 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002621 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002622 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2623 }
deadbeefab9b2d12015-10-14 11:33:11 -07002624
Steve Antondcc3c022017-12-22 16:02:54 -08002625 UpdateEndedRemoteMediaStreams();
2626 }
deadbeefab9b2d12015-10-14 11:33:11 -07002627
Steve Anton8a006912017-12-04 15:25:56 -08002628 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002629}
2630
Steve Anton0f5400a2018-07-17 14:25:36 -07002631void PeerConnection::ProcessRemovalOfRemoteTrack(
2632 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2633 transceiver,
2634 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2635 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2636 RTC_DCHECK(transceiver->mid());
2637 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2638 << *transceiver->mid();
2639 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2640 transceiver->internal()->receiver_internal()->streams();
2641 // This will remove the remote track from the streams.
2642 transceiver->internal()->receiver_internal()->set_stream_ids({});
2643 remove_list->push_back(transceiver);
2644 // Remove any streams that no longer have tracks.
2645 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2646 // of streams, see if the stream was removed by checking if this was the
2647 // last receiver with that stream ID.
2648 for (auto stream : media_streams) {
2649 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2650 remote_streams_->RemoveStream(stream);
2651 removed_streams->push_back(stream);
2652 }
2653 }
2654}
2655
Steve Antondcc3c022017-12-22 16:02:54 -08002656RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2657 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002658 const SessionDescriptionInterface& new_session,
2659 const SessionDescriptionInterface* old_local_description,
2660 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002661 RTC_DCHECK(IsUnifiedPlan());
2662
Steve Anton7464fca2018-01-19 11:10:37 -08002663 const cricket::ContentGroup* bundle_group = nullptr;
2664 if (new_session.GetType() == SdpType::kOffer) {
2665 auto bundle_group_or_error =
2666 GetEarlyBundleGroup(*new_session.description());
2667 if (!bundle_group_or_error.ok()) {
2668 return bundle_group_or_error.MoveError();
2669 }
2670 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002671 }
Steve Antondcc3c022017-12-22 16:02:54 -08002672
Steve Antondcc3c022017-12-22 16:02:54 -08002673 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002674 for (size_t i = 0; i < new_contents.size(); ++i) {
2675 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002676 cricket::MediaType media_type = new_content.media_description()->type();
2677 seen_mids_.insert(new_content.name);
2678 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2679 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002680 const cricket::ContentInfo* old_local_content = nullptr;
2681 if (old_local_description &&
2682 i < old_local_description->description()->contents().size()) {
2683 old_local_content =
2684 &old_local_description->description()->contents()[i];
2685 }
2686 const cricket::ContentInfo* old_remote_content = nullptr;
2687 if (old_remote_description &&
2688 i < old_remote_description->description()->contents().size()) {
2689 old_remote_content =
2690 &old_remote_description->description()->contents()[i];
2691 }
Steve Antondcc3c022017-12-22 16:02:54 -08002692 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002693 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2694 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002695 if (!transceiver_or_error.ok()) {
2696 return transceiver_or_error.MoveError();
2697 }
2698 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002699 RTCError error =
2700 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2701 if (!error.ok()) {
2702 return error;
2703 }
2704 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002705 if (GetDataMid() && new_content.name != *GetDataMid()) {
2706 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002707 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2708 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002709 continue;
2710 }
2711 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2712 if (!error.ok()) {
2713 return error;
2714 }
Steve Antondcc3c022017-12-22 16:02:54 -08002715 } else {
2716 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2717 "Unknown section type.");
2718 }
2719 }
2720
2721 return RTCError::OK();
2722}
2723
2724RTCError PeerConnection::UpdateTransceiverChannel(
2725 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2726 transceiver,
2727 const cricket::ContentInfo& content,
2728 const cricket::ContentGroup* bundle_group) {
2729 RTC_DCHECK(IsUnifiedPlan());
2730 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002731 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002732 if (content.rejected) {
2733 if (channel) {
2734 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002735 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002736 }
2737 } else {
2738 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002739 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002740 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002741 } else {
Steve Anton69470252018-02-09 11:43:08 -08002742 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002743 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002744 }
2745 if (!channel) {
2746 LOG_AND_RETURN_ERROR(
2747 RTCErrorType::INTERNAL_ERROR,
2748 "Failed to create channel for mid=" + content.name);
2749 }
2750 transceiver->internal()->SetChannel(channel);
2751 }
2752 }
2753 return RTCError::OK();
2754}
2755
Steve Antonfa2260d2017-12-28 16:38:23 -08002756RTCError PeerConnection::UpdateDataChannel(
2757 cricket::ContentSource source,
2758 const cricket::ContentInfo& content,
2759 const cricket::ContentGroup* bundle_group) {
2760 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002761 // If data channels are disabled, ignore this media section. CreateAnswer
2762 // will take care of rejecting it.
2763 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002764 }
2765 if (content.rejected) {
2766 DestroyDataChannel();
2767 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002768 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002769 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002770 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2771 "Failed to create data channel.");
2772 }
2773 }
2774 if (source == cricket::CS_REMOTE) {
2775 const MediaContentDescription* data_desc = content.media_description();
2776 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2777 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2778 }
2779 }
2780 }
2781 return RTCError::OK();
2782}
2783
Steve Antondcc3c022017-12-22 16:02:54 -08002784RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2785PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002786 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002787 size_t mline_index,
2788 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002789 const ContentInfo* old_local_content,
2790 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002791 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002792 // If this is an offer then the m= section might be recycled. If the m=
2793 // section is being recycled (defined as: rejected in the current local or
2794 // remote description and not rejected in new description), dissociate the
2795 // currently associated RtpTransceiver by setting its mid property to null,
2796 // and discard the mapping between the transceiver and its m= section index.
2797 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2798 old_remote_content)) {
2799 // We want to dissociate the transceiver that has the rejected mid.
2800 const std::string& old_mid =
2801 (old_local_content && old_local_content->rejected)
2802 ? old_local_content->name
2803 : old_remote_content->name;
2804 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002805 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002806 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2807 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002808 old_transceiver->internal()->set_mid(absl::nullopt);
2809 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002810 }
2811 }
2812 const MediaContentDescription* media_desc = content.media_description();
2813 auto transceiver = GetAssociatedTransceiver(content.name);
2814 if (source == cricket::CS_LOCAL) {
2815 // Find the RtpTransceiver that corresponds to this m= section, using the
2816 // mapping between transceivers and m= section indices established when
2817 // creating the offer.
2818 if (!transceiver) {
2819 transceiver = GetTransceiverByMLineIndex(mline_index);
2820 }
2821 if (!transceiver) {
2822 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2823 "Unknown transceiver");
2824 }
2825 } else {
2826 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2827 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2828 // of the same type...
2829 if (!transceiver &&
2830 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2831 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2832 }
2833 // If no RtpTransceiver was found in the previous step, create one with a
2834 // recvonly direction.
2835 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002836 RTC_LOG(LS_INFO) << "Adding "
2837 << cricket::MediaTypeToString(media_desc->type())
2838 << " transceiver for MID=" << content.name
2839 << " at i=" << mline_index
2840 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002841 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002842 auto sender =
2843 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002844 std::string receiver_id;
2845 if (!media_desc->streams().empty()) {
2846 receiver_id = media_desc->streams()[0].id;
2847 } else {
2848 receiver_id = rtc::CreateRandomUuid();
2849 }
2850 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002851 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002852 transceiver->internal()->set_direction(
2853 RtpTransceiverDirection::kRecvOnly);
2854 }
2855 }
2856 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002857 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002858 LOG_AND_RETURN_ERROR(
2859 RTCErrorType::INVALID_PARAMETER,
2860 "Transceiver type does not match media description type.");
2861 }
2862 // Associate the found or created RtpTransceiver with the m= section by
2863 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2864 // section, and establish a mapping between the transceiver and the index of
2865 // the m= section.
2866 transceiver->internal()->set_mid(content.name);
2867 transceiver->internal()->set_mline_index(mline_index);
2868 return std::move(transceiver);
2869}
2870
2871rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2872PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2873 RTC_DCHECK(IsUnifiedPlan());
2874 for (auto transceiver : transceivers_) {
2875 if (transceiver->mid() == mid) {
2876 return transceiver;
2877 }
2878 }
2879 return nullptr;
2880}
2881
2882rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2883PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2884 RTC_DCHECK(IsUnifiedPlan());
2885 for (auto transceiver : transceivers_) {
2886 if (transceiver->internal()->mline_index() == mline_index) {
2887 return transceiver;
2888 }
2889 }
2890 return nullptr;
2891}
2892
2893rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2894PeerConnection::FindAvailableTransceiverToReceive(
2895 cricket::MediaType media_type) const {
2896 RTC_DCHECK(IsUnifiedPlan());
2897 // From JSEP section 5.10 (Applying a Remote Description):
2898 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2899 // the same type that were added to the PeerConnection by addTrack and are not
2900 // associated with any m= section and are not stopped, find the first such
2901 // RtpTransceiver.
2902 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002903 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002904 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2905 !transceiver->stopped()) {
2906 return transceiver;
2907 }
2908 }
2909 return nullptr;
2910}
2911
Steve Antoned10bd92017-12-05 10:52:59 -08002912const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2913 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2914 transceiver,
2915 const SessionDescriptionInterface* sdesc) const {
2916 RTC_DCHECK(transceiver);
2917 RTC_DCHECK(sdesc);
2918 if (IsUnifiedPlan()) {
2919 if (!transceiver->internal()->mid()) {
2920 // This transceiver is not associated with a media section yet.
2921 return nullptr;
2922 }
2923 return sdesc->description()->GetContentByName(
2924 *transceiver->internal()->mid());
2925 } else {
2926 // Plan B only allows at most one audio and one video section, so use the
2927 // first media section of that type.
2928 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002929 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002930 }
2931}
2932
deadbeef46c73892016-11-16 19:42:04 -08002933PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2934 return configuration_;
2935}
2936
deadbeef293e9262017-01-11 12:28:30 -08002937bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2938 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002939 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002940 if (IsClosed()) {
2941 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2942 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2943 }
2944
Qingsi Wanga2d60672018-04-11 16:57:45 -07002945 // According to JSEP, after setLocalDescription, changing the candidate pool
2946 // size is not allowed, and changing the set of ICE servers will not result
2947 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002948 if (local_description() && configuration.ice_candidate_pool_size !=
2949 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002950 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2951 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002952 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002953 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002954
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002955 if (local_description() &&
2956 configuration.use_media_transport != configuration_.use_media_transport) {
2957 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2958 "SetLocalDescription.";
2959 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2960 }
2961
2962 if (remote_description() &&
2963 configuration.use_media_transport != configuration_.use_media_transport) {
2964 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2965 "SetRemoteDescription.";
2966 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2967 }
2968
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002969 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002970 configuration.use_media_transport_for_data_channels !=
2971 configuration_.use_media_transport_for_data_channels) {
2972 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2973 "after calling SetLocalDescription.";
2974 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2975 }
2976
2977 if (remote_description() &&
2978 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 SetRemoteDescription.";
2982 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2983 }
2984
2985 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002986 configuration.crypto_options != configuration_.crypto_options) {
2987 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2988 "SetLocalDescription.";
2989 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2990 }
2991
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08002992 if (configuration.use_media_transport_for_data_channels ||
2993 configuration.use_media_transport) {
2994 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
2995 << "Media transport requires MaxBundle policy.";
2996 }
2997
deadbeef293e9262017-01-11 12:28:30 -08002998 // The simplest (and most future-compatible) way to tell if the config was
2999 // modified in an invalid way is to copy each property we do support
3000 // modifying, then use operator==. There are far more properties we don't
3001 // support modifying than those we do, and more could be added.
3002 RTCConfiguration modified_config = configuration_;
3003 modified_config.servers = configuration.servers;
3004 modified_config.type = configuration.type;
3005 modified_config.ice_candidate_pool_size =
3006 configuration.ice_candidate_pool_size;
3007 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003008 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003009 modified_config.ice_check_interval_strong_connectivity =
3010 configuration.ice_check_interval_strong_connectivity;
3011 modified_config.ice_check_interval_weak_connectivity =
3012 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003013 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3014 modified_config.ice_unwritable_min_checks =
3015 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003016 modified_config.stun_candidate_keepalive_interval =
3017 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003018 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003019 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003020 modified_config.active_reset_srtp_params =
3021 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003022 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003023 modified_config.use_media_transport_for_data_channels =
3024 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003025 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003026 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003027 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3028 }
3029
Steve Anton038834f2017-07-14 15:59:59 -07003030 // Validate the modified configuration.
3031 RTCError validate_error = ValidateConfiguration(modified_config);
3032 if (!validate_error.ok()) {
3033 return SafeSetError(std::move(validate_error), error);
3034 }
3035
deadbeef293e9262017-01-11 12:28:30 -08003036 // Note that this isn't possible through chromium, since it's an unsigned
3037 // short in WebIDL.
3038 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003039 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003040 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3041 }
3042
3043 // Parse ICE servers before hopping to network thread.
3044 cricket::ServerAddresses stun_servers;
3045 std::vector<cricket::RelayServerConfig> turn_servers;
3046 RTCErrorType parse_error =
3047 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3048 if (parse_error != RTCErrorType::NONE) {
3049 return SafeSetError(parse_error, error);
3050 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003051 // Note if STUN or TURN servers were supplied.
3052 if (!stun_servers.empty()) {
3053 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3054 }
3055 if (!turn_servers.empty()) {
3056 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3057 }
deadbeef293e9262017-01-11 12:28:30 -08003058
3059 // In theory this shouldn't fail.
3060 if (!network_thread()->Invoke<bool>(
3061 RTC_FROM_HERE,
3062 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3063 stun_servers, turn_servers, modified_config.type,
3064 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003065 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003066 modified_config.turn_customizer,
3067 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003068 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003069 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3070 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003071
deadbeefd1a38b52016-12-10 13:15:33 -08003072 // As described in JSEP, calling setConfiguration with new ICE servers or
3073 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3074 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003075 if (modified_config.servers != configuration_.servers ||
3076 modified_config.type != configuration_.type ||
3077 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003078 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003079 }
skvladd1f5fda2017-02-03 16:54:05 -08003080
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003081 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003082 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003083 modified_config.use_media_transport ||
3084 modified_config.use_media_transport_for_data_channels
3085 ? factory_->media_transport_factory()
3086 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003087
Zhi Huangb57e1692018-06-12 11:41:11 -07003088 if (configuration_.active_reset_srtp_params !=
3089 modified_config.active_reset_srtp_params) {
3090 transport_controller_->SetActiveResetSrtpParams(
3091 modified_config.active_reset_srtp_params);
3092 }
3093
deadbeef293e9262017-01-11 12:28:30 -08003094 configuration_ = modified_config;
3095 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003096}
3097
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003098bool PeerConnection::AddIceCandidate(
3099 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003100 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003101 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003102 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003103 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003104 return false;
3105 }
Steve Antond25da372017-11-06 14:50:29 -08003106
3107 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003108 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003109 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003110 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003111 return false;
3112 }
3113
3114 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003115 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003116 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003117 return false;
3118 }
3119
3120 bool valid = false;
3121 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3122 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003123 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003124 return false;
3125 }
3126
3127 // Add this candidate to the remote session description.
3128 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003129 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003130 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003131 return false;
3132 }
3133
3134 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003135 bool result = UseCandidate(ice_candidate);
3136 if (result) {
3137 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3138 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3139 } else {
3140 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3141 }
3142 return result;
Steve Antond25da372017-11-06 14:50:29 -08003143 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003144 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003145 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003146 return true;
3147 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003148}
3149
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003150bool PeerConnection::RemoveIceCandidates(
3151 const std::vector<cricket::Candidate>& candidates) {
3152 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003153 if (IsClosed()) {
3154 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3155 return false;
3156 }
3157
Steve Antond25da372017-11-06 14:50:29 -08003158 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003159 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3160 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003161 return false;
3162 }
3163
3164 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003165 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003166 return false;
3167 }
3168
3169 size_t number_removed =
3170 mutable_remote_description()->RemoveCandidates(candidates);
3171 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003172 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003173 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003174 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003175 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003176 }
3177
3178 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003179 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3180 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003181 RTC_LOG(LS_ERROR)
3182 << "RemoveIceCandidates: Error when removing remote candidates: "
3183 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003184 }
3185 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003186}
3187
Niels Möller0c4f7be2018-05-07 14:01:37 +02003188RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003189 if (!worker_thread()->IsCurrent()) {
3190 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003191 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003192 }
3193
Niels Möller0c4f7be2018-05-07 14:01:37 +02003194 const bool has_min = bitrate.min_bitrate_bps.has_value();
3195 const bool has_start = bitrate.start_bitrate_bps.has_value();
3196 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003197 if (has_min && *bitrate.min_bitrate_bps < 0) {
3198 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3199 "min_bitrate_bps <= 0");
3200 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003201 if (has_start) {
3202 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003203 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003204 "start_bitrate_bps < min_bitrate_bps");
3205 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3207 "curent_bitrate_bps < 0");
3208 }
3209 }
3210 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003211 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003213 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003214 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3216 "max_bitrate_bps < min_bitrate_bps");
3217 } else if (*bitrate.max_bitrate_bps < 0) {
3218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3219 "max_bitrate_bps < 0");
3220 }
3221 }
3222
zstein4b979802017-06-02 14:37:37 -07003223 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003224 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003225
3226 return RTCError::OK();
3227}
3228
Alex Narest78609d52017-10-20 10:37:47 +02003229void PeerConnection::SetBitrateAllocationStrategy(
3230 std::unique_ptr<rtc::BitrateAllocationStrategy>
3231 bitrate_allocation_strategy) {
3232 rtc::Thread* worker_thread = factory_->worker_thread();
3233 if (!worker_thread->IsCurrent()) {
3234 rtc::BitrateAllocationStrategy* strategy_raw =
3235 bitrate_allocation_strategy.release();
3236 auto functor = [this, strategy_raw]() {
3237 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003238 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003239 };
3240 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3241 return;
3242 }
3243 RTC_DCHECK(call_.get());
3244 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3245}
3246
henrika5f6bf242017-11-01 11:06:56 +01003247void PeerConnection::SetAudioPlayout(bool playout) {
3248 if (!worker_thread()->IsCurrent()) {
3249 worker_thread()->Invoke<void>(
3250 RTC_FROM_HERE,
3251 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3252 return;
3253 }
3254 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003255 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003256 audio_state->SetPlayout(playout);
3257}
3258
3259void PeerConnection::SetAudioRecording(bool recording) {
3260 if (!worker_thread()->IsCurrent()) {
3261 worker_thread()->Invoke<void>(
3262 RTC_FROM_HERE,
3263 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3264 return;
3265 }
3266 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003267 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003268 audio_state->SetRecording(recording);
3269}
3270
Steve Anton8c0f7a72017-10-03 10:03:10 -07003271std::unique_ptr<rtc::SSLCertificate>
3272PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003273 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3274 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003275 return nullptr;
3276 }
Steve Antonf25303e2018-10-16 15:23:31 -07003277 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003278}
3279
Zhi Huang70b820f2018-01-27 14:16:15 -08003280std::unique_ptr<rtc::SSLCertChain>
3281PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003282 auto audio_transceiver = GetFirstAudioTransceiver();
3283 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003284 return nullptr;
3285 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003286 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003287 audio_transceiver->internal()->channel()->transport_name());
3288}
3289
3290rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3291PeerConnection::GetFirstAudioTransceiver() const {
3292 for (auto transceiver : transceivers_) {
3293 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3294 return transceiver;
3295 }
3296 }
3297 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003298}
3299
ivoc14d5dbe2016-07-04 07:06:55 -07003300bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3301 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003302 // TODO(eladalon): It would be better to not allow negative values into PC.
3303 const size_t max_size = (max_size_bytes < 0)
3304 ? RtcEventLog::kUnlimitedOutput
3305 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003306 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3307 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3308 output_period_ms = 5000;
3309 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003310 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003311 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003312 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003313}
3314
Bjorn Tereliusde939432017-11-20 17:38:14 +01003315bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3316 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003317 // TODO(eladalon): In C++14, this can be done with a lambda.
3318 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003319 bool operator()() {
3320 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3321 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003322 PeerConnection* const pc;
3323 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003324 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003325 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003326 return worker_thread()->Invoke<bool>(
3327 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003328}
3329
3330void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003331 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003332 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3333}
3334
Harald Alvestrandad88c882018-11-28 16:47:46 +01003335rtc::scoped_refptr<DtlsTransportInterface>
3336PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3337 return transport_controller_->LookupDtlsTransportByMid(mid);
3338}
3339
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003341 return pending_local_description_ ? pending_local_description_.get()
3342 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003343}
3344
3345const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003346 return pending_remote_description_ ? pending_remote_description_.get()
3347 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003348}
3349
deadbeeffe4a8a42016-12-20 17:56:17 -08003350const SessionDescriptionInterface* PeerConnection::current_local_description()
3351 const {
Steve Anton75737c02017-11-06 10:37:17 -08003352 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003353}
3354
3355const SessionDescriptionInterface* PeerConnection::current_remote_description()
3356 const {
Steve Anton75737c02017-11-06 10:37:17 -08003357 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003358}
3359
3360const SessionDescriptionInterface* PeerConnection::pending_local_description()
3361 const {
Steve Anton75737c02017-11-06 10:37:17 -08003362 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003363}
3364
3365const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3366 const {
Steve Anton75737c02017-11-06 10:37:17 -08003367 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003368}
3369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003370void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003371 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003372 // Update stats here so that we have the most recent stats for tracks and
3373 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003374 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375
Steve Anton75737c02017-11-06 10:37:17 -08003376 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003377 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003378
Steve Anton8af21862017-12-15 11:20:13 -08003379 for (auto transceiver : transceivers_) {
3380 transceiver->Stop();
3381 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003382
3383 // Ensure that all asynchronous stats requests are completed before destroying
3384 // the transport controller below.
3385 if (stats_collector_) {
3386 stats_collector_->WaitForPendingRequest();
3387 }
3388
3389 // Don't destroy BaseChannels until after stats has been cleaned up so that
3390 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003391 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003392
Qingsi Wang93a84392018-01-30 17:13:09 -08003393 // The event log is used in the transport controller, which must be outlived
3394 // by the former. CreateOffer by the peer connection is implemented
3395 // asynchronously and if the peer connection is closed without resetting the
3396 // WebRTC session description factory, the session description factory would
3397 // call the transport controller.
3398 webrtc_session_desc_factory_.reset();
3399 transport_controller_.reset();
3400
deadbeef42a42632017-03-10 15:18:00 -08003401 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003402 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3403 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003404
Steve Anton978b8762017-09-29 12:15:02 -07003405 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003406 call_.reset();
3407 // The event log must outlive call (and any other object that uses it).
3408 event_log_.reset();
3409 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003410 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003411 // The .h file says that observer can be discarded after close() returns.
3412 // Make sure this is true.
3413 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003414}
3415
Steve Antonad182762018-09-05 20:22:40 +00003416void PeerConnection::OnMessage(rtc::Message* msg) {
3417 switch (msg->message_id) {
3418 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3419 SetSessionDescriptionMsg* param =
3420 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3421 param->observer->OnSuccess();
3422 delete param;
3423 break;
3424 }
3425 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3426 SetSessionDescriptionMsg* param =
3427 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3428 param->observer->OnFailure(std::move(param->error));
3429 delete param;
3430 break;
3431 }
3432 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3433 CreateSessionDescriptionMsg* param =
3434 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3435 param->observer->OnFailure(std::move(param->error));
3436 delete param;
3437 break;
3438 }
3439 case MSG_GETSTATS: {
3440 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3441 StatsReports reports;
3442 stats_->GetStats(param->track, &reports);
3443 param->observer->OnComplete(reports);
3444 delete param;
3445 break;
3446 }
3447 case MSG_FREE_DATACHANNELS: {
3448 sctp_data_channels_to_free_.clear();
3449 break;
3450 }
3451 case MSG_REPORT_USAGE_PATTERN: {
3452 ReportUsagePattern();
3453 break;
3454 }
3455 default:
3456 RTC_NOTREACHED() << "Not implemented";
3457 break;
3458 }
3459}
3460
Steve Antonafb0bb72018-02-20 11:35:37 -08003461cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3462 RTC_DCHECK(!IsUnifiedPlan());
3463 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3464 GetAudioTransceiver()->internal()->channel());
3465 if (voice_channel) {
3466 return voice_channel->media_channel();
3467 } else {
3468 return nullptr;
3469 }
3470}
3471
3472cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3473 RTC_DCHECK(!IsUnifiedPlan());
3474 auto* video_channel = static_cast<cricket::VideoChannel*>(
3475 GetVideoTransceiver()->internal()->channel());
3476 if (video_channel) {
3477 return video_channel->media_channel();
3478 } else {
3479 return nullptr;
3480 }
3481}
3482
Steve Anton4171afb2017-11-20 10:20:22 -08003483void PeerConnection::CreateAudioReceiver(
3484 MediaStreamInterface* stream,
3485 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003486 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3487 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003488 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3489 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003490 auto* audio_receiver = new AudioRtpReceiver(
3491 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003492 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003493 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3494 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3495 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003496 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003497 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003498 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003499}
3500
Steve Anton4171afb2017-11-20 10:20:22 -08003501void PeerConnection::CreateVideoReceiver(
3502 MediaStreamInterface* stream,
3503 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003504 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3505 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003506 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3507 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003508 auto* video_receiver = new VideoRtpReceiver(
3509 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003510 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003511 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3512 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3513 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003514 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003515 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003516 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003517}
3518
deadbeef70ab1a12015-09-28 16:53:55 -07003519// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3520// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003521rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003522 const RtpSenderInfo& remote_sender_info) {
3523 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3524 if (!receiver) {
3525 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3526 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003527 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003528 }
Steve Anton4171afb2017-11-20 10:20:22 -08003529 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3530 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3531 } else {
3532 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3533 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003534 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003535}
3536
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003537void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3538 MediaStreamInterface* stream) {
3539 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003540 RTC_DCHECK(track);
3541 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003542 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003543 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003544 // We already have a sender for this track, so just change the stream_id
3545 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003546 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003547 return;
3548 }
3549
3550 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003551 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003552 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003553 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003554 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003555 // If the sender has already been configured in SDP, we call SetSsrc,
3556 // which will connect the sender to the underlying transport. This can
3557 // occur if a local session description that contains the ID of the sender
3558 // is set before AddStream is called. It can also occur if the local
3559 // session description is not changed and RemoveStream is called, and
3560 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003561 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003562 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003563 if (sender_info) {
3564 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003565 }
3566}
3567
3568// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3569// indefinitely, when we have unified plan SDP.
3570void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3571 MediaStreamInterface* stream) {
3572 RTC_DCHECK(!IsClosed());
3573 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003574 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003575 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3576 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003577 return;
3578 }
Steve Anton4171afb2017-11-20 10:20:22 -08003579 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003580}
3581
3582void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3583 MediaStreamInterface* stream) {
3584 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003585 RTC_DCHECK(track);
3586 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003587 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003588 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003589 // We already have a sender for this track, so just change the stream_id
3590 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003591 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003592 return;
3593 }
3594
3595 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003596 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003597 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003598 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003599 GetVideoTransceiver()->internal()->AddSender(new_sender);
3600 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003601 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003602 if (sender_info) {
3603 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003604 }
3605}
3606
3607void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3608 MediaStreamInterface* stream) {
3609 RTC_DCHECK(!IsClosed());
3610 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003611 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003612 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3613 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003614 return;
3615 }
Steve Anton4171afb2017-11-20 10:20:22 -08003616 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003617}
3618
Steve Antonba818672017-11-06 10:21:57 -08003619void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003620 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003621 if (ice_connection_state_ == new_state) {
3622 return;
3623 }
3624
deadbeefcbecd352015-09-23 11:50:27 -07003625 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003626 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003627 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003628 return;
3629 }
Steve Antonba818672017-11-06 10:21:57 -08003630
Mirko Bonadei675513b2017-11-09 11:09:25 +01003631 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3632 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003633 RTC_DCHECK(ice_connection_state_ !=
3634 PeerConnectionInterface::kIceConnectionClosed);
3635
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003636 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003637 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003638}
3639
Alex Loiko9289eda2018-11-23 16:18:59 +00003640void PeerConnection::SetStandardizedIceConnectionState(
3641 PeerConnectionInterface::IceConnectionState new_state) {
3642 RTC_DCHECK(signaling_thread()->IsCurrent());
3643 if (standardized_ice_connection_state_ == new_state)
3644 return;
3645 if (IsClosed())
3646 return;
3647 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003648 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003649}
3650
Jonas Olsson635474e2018-10-18 15:58:17 +02003651void PeerConnection::SetConnectionState(
3652 PeerConnectionInterface::PeerConnectionState new_state) {
3653 RTC_DCHECK(signaling_thread()->IsCurrent());
3654 if (connection_state_ == new_state)
3655 return;
3656 if (IsClosed())
3657 return;
3658 connection_state_ = new_state;
3659 Observer()->OnConnectionChange(new_state);
3660}
3661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003662void PeerConnection::OnIceGatheringChange(
3663 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003664 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003665 if (IsClosed()) {
3666 return;
3667 }
3668 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003669 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003670}
3671
jbauch81bf7b02017-03-25 08:31:12 -07003672void PeerConnection::OnIceCandidate(
3673 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003674 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003675 if (IsClosed()) {
3676 return;
3677 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003678 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003679 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3680 candidate->candidate().address().IsPrivateIP()) {
3681 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3682 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003683 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003684}
3685
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003686void PeerConnection::OnIceCandidatesRemoved(
3687 const std::vector<cricket::Candidate>& candidates) {
3688 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003689 if (IsClosed()) {
3690 return;
3691 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003692 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003693}
3694
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003695void PeerConnection::ChangeSignalingState(
3696 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003697 RTC_DCHECK(signaling_thread()->IsCurrent());
3698 if (signaling_state_ == signaling_state) {
3699 return;
3700 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003701 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3702 << GetSignalingStateString(signaling_state_)
3703 << " New state: "
3704 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003705 signaling_state_ = signaling_state;
3706 if (signaling_state == kClosed) {
3707 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003708 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003709 standardized_ice_connection_state_ =
3710 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003711 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3712 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003713 if (ice_gathering_state_ != kIceGatheringComplete) {
3714 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003715 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003716 }
3717 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003718 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003719}
3720
deadbeefeb459812015-12-15 19:24:43 -08003721void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3722 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003723 if (IsClosed()) {
3724 return;
3725 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003726 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003727 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003728}
3729
deadbeefeb459812015-12-15 19:24:43 -08003730void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3731 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003732 if (IsClosed()) {
3733 return;
3734 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003735 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003736 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003737}
3738
3739void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3740 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003741 if (IsClosed()) {
3742 return;
3743 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003744 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003745 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003746}
3747
3748void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3749 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003750 if (IsClosed()) {
3751 return;
3752 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003753 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003754 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003755}
3756
Henrik Boström31638672017-11-23 17:48:32 +01003757void PeerConnection::PostSetSessionDescriptionSuccess(
3758 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003759 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3760 signaling_thread()->Post(RTC_FROM_HERE, this,
3761 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003762}
3763
deadbeefab9b2d12015-10-14 11:33:11 -07003764void PeerConnection::PostSetSessionDescriptionFailure(
3765 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003766 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003767 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003768 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3769 msg->error = std::move(error);
3770 signaling_thread()->Post(RTC_FROM_HERE, this,
3771 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003772}
3773
3774void PeerConnection::PostCreateSessionDescriptionFailure(
3775 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003776 RTCError error) {
3777 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003778 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3779 msg->error = std::move(error);
3780 signaling_thread()->Post(RTC_FROM_HERE, this,
3781 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003782}
3783
zhihuang1c378ed2017-08-17 14:10:50 -07003784void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003785 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003786 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003787 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003788
Steve Antondcc3c022017-12-22 16:02:54 -08003789 if (IsUnifiedPlan()) {
3790 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3791 } else {
3792 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3793 }
3794
Steve Antonfa2260d2017-12-28 16:38:23 -08003795 // Intentionally unset the data channel type for RTP data channel with the
3796 // second condition. Otherwise the RTP data channels would be successfully
3797 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3798 // when building with chromium. We want to leave RTP data channels broken, so
3799 // people won't try to use them.
3800 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3801 session_options->data_channel_type = data_channel_type();
3802 }
3803
Steve Antondcc3c022017-12-22 16:02:54 -08003804 // Apply ICE restart flag and renomination flag.
3805 for (auto& options : session_options->media_description_options) {
3806 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3807 options.transport_options.enable_ice_renomination =
3808 configuration_.enable_ice_renomination;
3809 }
3810
3811 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003812 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003813 session_options->pooled_ice_credentials =
3814 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3815 RTC_FROM_HERE,
3816 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3817 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003818 session_options->offer_extmap_allow_mixed =
3819 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003820}
3821
3822void PeerConnection::GetOptionsForPlanBOffer(
3823 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3824 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003825 // Figure out transceiver directional preferences.
3826 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3827 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3828
3829 // By default, generate sendrecv/recvonly m= sections.
3830 bool recv_audio = true;
3831 bool recv_video = true;
3832
3833 // By default, only offer a new m= section if we have media to send with it.
3834 bool offer_new_audio_description = send_audio;
3835 bool offer_new_video_description = send_video;
3836 bool offer_new_data_description = HasDataChannels();
3837
3838 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003839 if (offer_answer_options.offer_to_receive_audio !=
3840 RTCOfferAnswerOptions::kUndefined) {
3841 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003842 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003843 offer_new_audio_description ||
3844 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003845 }
Steve Antondcc3c022017-12-22 16:02:54 -08003846 if (offer_answer_options.offer_to_receive_video !=
3847 RTCOfferAnswerOptions::kUndefined) {
3848 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003849 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003850 offer_new_video_description ||
3851 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003852 }
3853
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003854 absl::optional<size_t> audio_index;
3855 absl::optional<size_t> video_index;
3856 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003857 // If a current description exists, generate m= sections in the same order,
3858 // using the first audio/video/data section that appears and rejecting
3859 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003860 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003861 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003862 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003863 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3864 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3865 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003866 }
3867
zhihuang1c378ed2017-08-17 14:10:50 -07003868 // Add audio/video/data m= sections to the end if needed.
3869 if (!audio_index && offer_new_audio_description) {
3870 session_options->media_description_options.push_back(
3871 cricket::MediaDescriptionOptions(
3872 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003873 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3874 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003875 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003876 }
zhihuang1c378ed2017-08-17 14:10:50 -07003877 if (!video_index && offer_new_video_description) {
3878 session_options->media_description_options.push_back(
3879 cricket::MediaDescriptionOptions(
3880 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003881 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3882 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003883 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003884 }
zhihuang1c378ed2017-08-17 14:10:50 -07003885 if (!data_index && offer_new_data_description) {
3886 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003887 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003888 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003889 }
3890
3891 cricket::MediaDescriptionOptions* audio_media_description_options =
3892 !audio_index ? nullptr
3893 : &session_options->media_description_options[*audio_index];
3894 cricket::MediaDescriptionOptions* video_media_description_options =
3895 !video_index ? nullptr
3896 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003897
Steve Anton4171afb2017-11-20 10:20:22 -08003898 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003899 video_media_description_options,
3900 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003901}
3902
3903// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3904// and return a reference to it.
3905// Generated MIDs should be no more than 3 bytes long to take up less space in
3906// the RTP packet.
3907static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3908 RTC_DCHECK(used_mids);
3909 // We're boring: just generate MIDs 0, 1, 2, ...
3910 size_t i = 0;
3911 std::set<std::string>::iterator it;
3912 bool inserted;
3913 do {
3914 std::string mid = rtc::ToString(i++);
3915 auto insert_result = used_mids->insert(mid);
3916 it = insert_result.first;
3917 inserted = insert_result.second;
3918 } while (!inserted);
3919 return *it;
3920}
3921
3922static cricket::MediaDescriptionOptions
3923GetMediaDescriptionOptionsForTransceiver(
3924 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3925 transceiver,
3926 const std::string& mid) {
3927 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003928 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003929 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003930 // This behavior is specified in JSEP. The gist is that:
3931 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3932 // sendrecv.
3933 // 2. If the MSID is included, then it must be included in any subsequent
3934 // offer/answer exactly the same until the RtpTransceiver is stopped.
3935 if (!transceiver->stopped() &&
3936 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3937 transceiver->internal()->has_ever_been_used_to_send())) {
3938 cricket::SenderOptions sender_options;
3939 sender_options.track_id = transceiver->sender()->id();
3940 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003941 int num_send_encoding_layers =
3942 transceiver->sender()->init_send_encodings().size();
3943 sender_options.num_sim_layers =
3944 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003945 media_description_options.sender_options.push_back(sender_options);
3946 }
Steve Antondcc3c022017-12-22 16:02:54 -08003947 return media_description_options;
3948}
3949
Steve Anton5c72e712018-12-10 14:25:30 -08003950// Returns the ContentInfo at mline index |i|, or null if none exists.
3951static const ContentInfo* GetContentByIndex(
3952 const SessionDescriptionInterface* sdesc,
3953 size_t i) {
3954 if (!sdesc) {
3955 return nullptr;
3956 }
3957 const ContentInfos& contents = sdesc->description()->contents();
3958 return (i < contents.size() ? &contents[i] : nullptr);
3959}
3960
Steve Antondcc3c022017-12-22 16:02:54 -08003961void PeerConnection::GetOptionsForUnifiedPlanOffer(
3962 const RTCOfferAnswerOptions& offer_answer_options,
3963 cricket::MediaSessionOptions* session_options) {
3964 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3965 // Offers) and 5.2.2 (Subsequent Offers).
3966 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3967 const ContentInfos& local_contents =
3968 (local_description() ? local_description()->description()->contents()
3969 : ContentInfos());
3970 const ContentInfos& remote_contents =
3971 (remote_description() ? remote_description()->description()->contents()
3972 : ContentInfos());
3973 // The mline indices that can be recycled. New transceivers should reuse these
3974 // slots first.
3975 std::queue<size_t> recycleable_mline_indices;
3976 // Track the MIDs used in previous offer/answer exchanges and the current
3977 // offer so that new, unique MIDs are generated.
3978 std::set<std::string> used_mids = seen_mids_;
3979 // First, go through each media section that exists in either the local or
3980 // remote description and generate a media section in this offer for the
3981 // associated transceiver. If a media section can be recycled, generate a
3982 // default, rejected media section here that can be later overwritten.
3983 for (size_t i = 0;
3984 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3985 // Either |local_content| or |remote_content| is non-null.
3986 const ContentInfo* local_content =
3987 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08003988 const ContentInfo* current_local_content =
3989 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08003990 const ContentInfo* remote_content =
3991 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08003992 const ContentInfo* current_remote_content =
3993 GetContentByIndex(current_remote_description(), i);
3994 bool had_been_rejected =
3995 (current_local_content && current_local_content->rejected) ||
3996 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08003997 const std::string& mid =
3998 (local_content ? local_content->name : remote_content->name);
3999 cricket::MediaType media_type =
4000 (local_content ? local_content->media_description()->type()
4001 : remote_content->media_description()->type());
4002 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4003 media_type == cricket::MEDIA_TYPE_VIDEO) {
4004 auto transceiver = GetAssociatedTransceiver(mid);
4005 RTC_CHECK(transceiver);
4006 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004007 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004008 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004009 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004010 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4011 RtpTransceiverDirection::kInactive,
4012 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004013 recycleable_mline_indices.push(i);
4014 } else {
4015 session_options->media_description_options.push_back(
4016 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4017 // CreateOffer shouldn't really cause any state changes in
4018 // PeerConnection, but we need a way to match new transceivers to new
4019 // media sections in SetLocalDescription and JSEP specifies this is done
4020 // by recording the index of the media section generated for the
4021 // transceiver in the offer.
4022 transceiver->internal()->set_mline_index(i);
4023 }
4024 } else {
4025 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004026 RTC_CHECK(GetDataMid());
4027 if (had_been_rejected || mid != *GetDataMid()) {
4028 session_options->media_description_options.push_back(
4029 GetMediaDescriptionOptionsForRejectedData(mid));
4030 } else {
4031 session_options->media_description_options.push_back(
4032 GetMediaDescriptionOptionsForActiveData(mid));
4033 }
Steve Antondcc3c022017-12-22 16:02:54 -08004034 }
4035 }
4036 // Next, look for transceivers that are newly added (that is, are not stopped
4037 // and not associated). Reuse media sections marked as recyclable first,
4038 // otherwise append to the end of the offer. New media sections should be
4039 // added in the order they were added to the PeerConnection.
4040 for (auto transceiver : transceivers_) {
4041 if (transceiver->mid() || transceiver->stopped()) {
4042 continue;
4043 }
4044 size_t mline_index;
4045 if (!recycleable_mline_indices.empty()) {
4046 mline_index = recycleable_mline_indices.front();
4047 recycleable_mline_indices.pop();
4048 session_options->media_description_options[mline_index] =
4049 GetMediaDescriptionOptionsForTransceiver(transceiver,
4050 AllocateMid(&used_mids));
4051 } else {
4052 mline_index = session_options->media_description_options.size();
4053 session_options->media_description_options.push_back(
4054 GetMediaDescriptionOptionsForTransceiver(transceiver,
4055 AllocateMid(&used_mids)));
4056 }
4057 // See comment above for why CreateOffer changes the transceiver's state.
4058 transceiver->internal()->set_mline_index(mline_index);
4059 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004060 // Lastly, add a m-section if we have local data channels and an m section
4061 // does not already exist.
4062 if (!GetDataMid() && HasDataChannels()) {
4063 session_options->media_description_options.push_back(
4064 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4065 }
Steve Antondcc3c022017-12-22 16:02:54 -08004066}
4067
4068void PeerConnection::GetOptionsForAnswer(
4069 const RTCOfferAnswerOptions& offer_answer_options,
4070 cricket::MediaSessionOptions* session_options) {
4071 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4072
4073 if (IsUnifiedPlan()) {
4074 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4075 } else {
4076 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4077 }
4078
Steve Antonfa2260d2017-12-28 16:38:23 -08004079 // Intentionally unset the data channel type for RTP data channel. Otherwise
4080 // the RTP data channels would be successfully negotiated by default and the
4081 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4082 // We want to leave RTP data channels broken, so people won't try to use them.
4083 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4084 session_options->data_channel_type = data_channel_type();
4085 }
4086
Steve Antondcc3c022017-12-22 16:02:54 -08004087 // Apply ICE renomination flag.
4088 for (auto& options : session_options->media_description_options) {
4089 options.transport_options.enable_ice_renomination =
4090 configuration_.enable_ice_renomination;
4091 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004092
4093 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004094 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004095 session_options->pooled_ice_credentials =
4096 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4097 RTC_FROM_HERE,
4098 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4099 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004100}
4101
Steve Antondcc3c022017-12-22 16:02:54 -08004102void PeerConnection::GetOptionsForPlanBAnswer(
4103 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004104 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004105 // Figure out transceiver directional preferences.
4106 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4107 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4108
4109 // By default, generate sendrecv/recvonly m= sections. The direction is also
4110 // restricted by the direction in the offer.
4111 bool recv_audio = true;
4112 bool recv_video = true;
4113
4114 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004115 if (offer_answer_options.offer_to_receive_audio !=
4116 RTCOfferAnswerOptions::kUndefined) {
4117 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004118 }
Steve Antondcc3c022017-12-22 16:02:54 -08004119 if (offer_answer_options.offer_to_receive_video !=
4120 RTCOfferAnswerOptions::kUndefined) {
4121 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004122 }
4123
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004124 absl::optional<size_t> audio_index;
4125 absl::optional<size_t> video_index;
4126 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004127
4128 // Generate m= sections that match those in the offer.
4129 // Note that mediasession.cc will handle intersection our preferred
4130 // direction with the offered direction.
4131 GenerateMediaDescriptionOptions(
4132 remote_description(),
4133 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4134 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4135 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004136
4137 cricket::MediaDescriptionOptions* audio_media_description_options =
4138 !audio_index ? nullptr
4139 : &session_options->media_description_options[*audio_index];
4140 cricket::MediaDescriptionOptions* video_media_description_options =
4141 !video_index ? nullptr
4142 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004143
Steve Anton4171afb2017-11-20 10:20:22 -08004144 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004145 video_media_description_options,
4146 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004147}
zhihuangaf388472016-11-02 16:49:48 -07004148
Steve Antondcc3c022017-12-22 16:02:54 -08004149void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4150 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4151 cricket::MediaSessionOptions* session_options) {
4152 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4153 // Answers) and 5.3.2 (Subsequent Answers).
4154 RTC_DCHECK(remote_description());
4155 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4156 for (const ContentInfo& content :
4157 remote_description()->description()->contents()) {
4158 cricket::MediaType media_type = content.media_description()->type();
4159 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4160 media_type == cricket::MEDIA_TYPE_VIDEO) {
4161 auto transceiver = GetAssociatedTransceiver(content.name);
4162 RTC_CHECK(transceiver);
4163 session_options->media_description_options.push_back(
4164 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4165 } else {
4166 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004167 // Reject all data sections if data channels are disabled.
4168 // Reject a data section if it has already been rejected.
4169 // Reject all data sections except for the first one.
4170 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4171 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004172 session_options->media_description_options.push_back(
4173 GetMediaDescriptionOptionsForRejectedData(content.name));
4174 } else {
4175 session_options->media_description_options.push_back(
4176 GetMediaDescriptionOptionsForActiveData(content.name));
4177 }
Steve Antondcc3c022017-12-22 16:02:54 -08004178 }
4179 }
htaa2a49d92016-03-04 02:51:39 -08004180}
4181
zhihuang1c378ed2017-08-17 14:10:50 -07004182void PeerConnection::GenerateMediaDescriptionOptions(
4183 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004184 RtpTransceiverDirection audio_direction,
4185 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004186 absl::optional<size_t>* audio_index,
4187 absl::optional<size_t>* video_index,
4188 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004189 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004190 for (const cricket::ContentInfo& content :
4191 session_desc->description()->contents()) {
4192 if (IsAudioContent(&content)) {
4193 // If we already have an audio m= section, reject this extra one.
4194 if (*audio_index) {
4195 session_options->media_description_options.push_back(
4196 cricket::MediaDescriptionOptions(
4197 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004198 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004199 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004200 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004201 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004202 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4203 content.name, audio_direction,
4204 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004205 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004206 }
4207 } else if (IsVideoContent(&content)) {
4208 // If we already have an video m= section, reject this extra one.
4209 if (*video_index) {
4210 session_options->media_description_options.push_back(
4211 cricket::MediaDescriptionOptions(
4212 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004213 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004214 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004215 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004216 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004217 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4218 content.name, video_direction,
4219 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004220 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004221 }
4222 } else {
4223 RTC_DCHECK(IsDataContent(&content));
4224 // If we already have an data m= section, reject this extra one.
4225 if (*data_index) {
4226 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004227 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004228 } else {
4229 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004230 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004231 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004232 }
4233 }
htaa2a49d92016-03-04 02:51:39 -08004234 }
deadbeefab9b2d12015-10-14 11:33:11 -07004235}
4236
Steve Antonfa2260d2017-12-28 16:38:23 -08004237cricket::MediaDescriptionOptions
4238PeerConnection::GetMediaDescriptionOptionsForActiveData(
4239 const std::string& mid) const {
4240 // Direction for data sections is meaningless, but legacy endpoints might
4241 // expect sendrecv.
4242 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4243 RtpTransceiverDirection::kSendRecv,
4244 /*stopped=*/false);
4245 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4246 return options;
4247}
4248
4249cricket::MediaDescriptionOptions
4250PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4251 const std::string& mid) const {
4252 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4253 RtpTransceiverDirection::kInactive,
4254 /*stopped=*/true);
4255 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4256 return options;
4257}
4258
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004259absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004260 switch (data_channel_type_) {
4261 case cricket::DCT_RTP:
4262 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004263 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004264 }
4265 return rtp_data_channel_->content_name();
4266 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004267 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004268 case cricket::DCT_MEDIA_TRANSPORT:
4269 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004270 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004271 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004272 }
4273}
4274
Steve Anton4171afb2017-11-20 10:20:22 -08004275void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4276 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4277 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004278 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004279}
4280
Steve Anton4171afb2017-11-20 10:20:22 -08004281void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004282 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004283 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004284 cricket::MediaType media_type,
4285 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004286 RTC_DCHECK(!IsUnifiedPlan());
4287
Steve Anton4171afb2017-11-20 10:20:22 -08004288 std::vector<RtpSenderInfo>* current_senders =
4289 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004290
Steve Anton4171afb2017-11-20 10:20:22 -08004291 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004292 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004293 for (auto sender_it = current_senders->begin();
4294 sender_it != current_senders->end();
4295 /* incremented manually */) {
4296 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004297 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004298 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004299 std::string params_stream_id;
4300 if (params) {
4301 params_stream_id =
4302 (!params->first_stream_id().empty() ? params->first_stream_id()
4303 : kDefaultStreamId);
4304 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004305 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004306 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004307 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004308 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004309 sender_exists) {
4310 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004311 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004312 OnRemoteSenderRemoved(info, media_type);
4313 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004314 }
4315 }
4316
Steve Anton4171afb2017-11-20 10:20:22 -08004317 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004318 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004319 if (!params.has_ssrcs()) {
4320 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4321 // sender, this means it is coming from a Unified Plan endpoint,so we just
4322 // create a default.
4323 default_sender_needed = true;
4324 break;
4325 }
4326
Seth Hampson845e8782018-03-02 11:34:10 -08004327 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004328 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004329 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4330 // not supported in Plan B, we just take the first here and create the
4331 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004332 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004333 (!params.first_stream_id().empty() ? params.first_stream_id()
4334 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004335 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004336 uint32_t ssrc = params.first_ssrc();
4337
4338 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004339 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004340 if (!stream) {
4341 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004342 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004343 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004344 remote_streams_->AddStream(stream);
4345 new_streams->AddStream(stream);
4346 }
4347
Steve Anton4171afb2017-11-20 10:20:22 -08004348 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004349 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004350 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004351 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004352 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004353 }
4354 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004355
Steve Anton4171afb2017-11-20 10:20:22 -08004356 // Add default sender if necessary.
4357 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004358 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004359 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004360 if (!default_stream) {
4361 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004362 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004363 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004364 remote_streams_->AddStream(default_stream);
4365 new_streams->AddStream(default_stream);
4366 }
Steve Anton4171afb2017-11-20 10:20:22 -08004367 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4368 ? kDefaultAudioSenderId
4369 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004370 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004371 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004372 if (!default_sender_info) {
4373 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004374 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004375 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004376 }
4377 }
deadbeefab9b2d12015-10-14 11:33:11 -07004378}
4379
Steve Anton4171afb2017-11-20 10:20:22 -08004380void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4381 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004382 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4383 << " receiver for track_id=" << sender_info.sender_id
4384 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004385
Steve Anton3d954a62018-04-02 11:27:23 -07004386 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004387 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004388 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004389 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004390 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004391 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004392 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004393 }
4394}
4395
Steve Anton4171afb2017-11-20 10:20:22 -08004396void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4397 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004398 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4399 << " receiver for track_id=" << sender_info.sender_id
4400 << " and stream_id=" << sender_info.stream_id;
4401
Seth Hampson845e8782018-03-02 11:34:10 -08004402 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004403
Henrik Boström933d8b02017-10-10 10:05:16 -07004404 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004405 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004406 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4407 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004408 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004409 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004410 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004411 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004412 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004413 }
4414 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004415 // Stopping or destroying a VideoRtpReceiver will end the
4416 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004417 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004418 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004419 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004420 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004421 // There's no guarantee the track is still available, e.g. the track may
4422 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004423 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004424 }
4425 } else {
nisseede5da42017-01-12 05:15:36 -08004426 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004427 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004428 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004429 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004430 }
deadbeefab9b2d12015-10-14 11:33:11 -07004431}
4432
4433void PeerConnection::UpdateEndedRemoteMediaStreams() {
4434 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4435 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4436 MediaStreamInterface* stream = remote_streams_->at(i);
4437 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4438 streams_to_remove.push_back(stream);
4439 }
4440 }
4441
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004442 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004443 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004444 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004445 }
4446}
4447
Steve Anton4171afb2017-11-20 10:20:22 -08004448void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004449 const std::vector<cricket::StreamParams>& streams,
4450 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004451 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004452
Seth Hampson845e8782018-03-02 11:34:10 -08004453 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004454 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004455 for (auto sender_it = current_senders->begin();
4456 sender_it != current_senders->end();
4457 /* incremented manually */) {
4458 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004459 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004460 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4461 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004462 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004463 OnLocalSenderRemoved(info, media_type);
4464 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004465 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004466 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004467 }
4468 }
4469
Steve Anton4171afb2017-11-20 10:20:22 -08004470 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004471 for (const cricket::StreamParams& params : streams) {
4472 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004473 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004474 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004475 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004476 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004477 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004478 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004479 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004480 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004481 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004482 }
4483 }
4484}
4485
Steve Anton4171afb2017-11-20 10:20:22 -08004486void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4487 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004488 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004489 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004490 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004491 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4492 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004493 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004494 return;
4495 }
4496
deadbeeffac06552015-11-25 11:26:01 -08004497 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
Seth Hampson5b4f0752018-04-02 16:31:36 -07004503 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004504 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004505}
4506
Steve Anton4171afb2017-11-20 10:20:22 -08004507void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4508 cricket::MediaType media_type) {
4509 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004510 if (!sender) {
4511 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004512 // SessionDescriptions has been renegotiated.
4513 return;
4514 }
deadbeeffac06552015-11-25 11:26:01 -08004515
4516 // A sender has been removed from the SessionDescription but it's still
4517 // associated with the PeerConnection. This only occurs if the SDP doesn't
4518 // match with the calls to CreateSender, AddStream and RemoveStream.
4519 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004520 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004521 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004522 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004523 }
deadbeeffac06552015-11-25 11:26:01 -08004524
Steve Anton4171afb2017-11-20 10:20:22 -08004525 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004526}
4527
4528void PeerConnection::UpdateLocalRtpDataChannels(
4529 const cricket::StreamParamsVec& streams) {
4530 std::vector<std::string> existing_channels;
4531
4532 // Find new and active data channels.
4533 for (const cricket::StreamParams& params : streams) {
4534 // |it->sync_label| is actually the data channel label. The reason is that
4535 // we use the same naming of data channels as we do for
4536 // MediaStreams and Tracks.
4537 // For MediaStreams, the sync_label is the MediaStream label and the
4538 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004539 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004540 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004541 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004542 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004543 continue;
4544 }
4545 // Set the SSRC the data channel should use for sending.
4546 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4547 existing_channels.push_back(data_channel_it->first);
4548 }
4549
4550 UpdateClosingRtpDataChannels(existing_channels, true);
4551}
4552
4553void PeerConnection::UpdateRemoteRtpDataChannels(
4554 const cricket::StreamParamsVec& streams) {
4555 std::vector<std::string> existing_channels;
4556
4557 // Find new and active data channels.
4558 for (const cricket::StreamParams& params : streams) {
4559 // The data channel label is either the mslabel or the SSRC if the mslabel
4560 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004561 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004562 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004563 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004564 auto data_channel_it = rtp_data_channels_.find(label);
4565 if (data_channel_it == rtp_data_channels_.end()) {
4566 // This is a new data channel.
4567 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4568 } else {
4569 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4570 }
4571 existing_channels.push_back(label);
4572 }
4573
4574 UpdateClosingRtpDataChannels(existing_channels, false);
4575}
4576
4577void PeerConnection::UpdateClosingRtpDataChannels(
4578 const std::vector<std::string>& active_channels,
4579 bool is_local_update) {
4580 auto it = rtp_data_channels_.begin();
4581 while (it != rtp_data_channels_.end()) {
4582 DataChannel* data_channel = it->second;
4583 if (std::find(active_channels.begin(), active_channels.end(),
4584 data_channel->label()) != active_channels.end()) {
4585 ++it;
4586 continue;
4587 }
4588
4589 if (is_local_update) {
4590 data_channel->SetSendSsrc(0);
4591 } else {
4592 data_channel->RemotePeerRequestClose();
4593 }
4594
4595 if (data_channel->state() == DataChannel::kClosed) {
4596 rtp_data_channels_.erase(it);
4597 it = rtp_data_channels_.begin();
4598 } else {
4599 ++it;
4600 }
4601 }
4602}
4603
4604void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4605 uint32_t remote_ssrc) {
4606 rtc::scoped_refptr<DataChannel> channel(
4607 InternalCreateDataChannel(label, nullptr));
4608 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004609 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004610 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004611 return;
4612 }
4613 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004614 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4615 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004616 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004617}
4618
4619rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4620 const std::string& label,
4621 const InternalDataChannelInit* config) {
4622 if (IsClosed()) {
4623 return nullptr;
4624 }
Steve Anton75737c02017-11-06 10:37:17 -08004625 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004626 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004627 << "InternalCreateDataChannel: Data is not supported in this call.";
4628 return nullptr;
4629 }
4630 InternalDataChannelInit new_config =
4631 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004632 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004633 if (new_config.id < 0) {
4634 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004635 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004636 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004637 RTC_LOG(LS_ERROR)
4638 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004639 return nullptr;
4640 }
4641 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004642 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004643 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004644 return nullptr;
4645 }
4646 }
4647
Steve Anton75737c02017-11-06 10:37:17 -08004648 rtc::scoped_refptr<DataChannel> channel(
4649 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004650 if (!channel) {
4651 sid_allocator_.ReleaseSid(new_config.id);
4652 return nullptr;
4653 }
4654
4655 if (channel->data_channel_type() == cricket::DCT_RTP) {
4656 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004657 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4658 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004659 return nullptr;
4660 }
4661 rtp_data_channels_[channel->label()] = channel;
4662 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004663 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004664 sctp_data_channels_.push_back(channel);
4665 channel->SignalClosed.connect(this,
4666 &PeerConnection::OnSctpDataChannelClosed);
4667 }
4668
Steve Anton2d8609c2018-01-23 16:38:46 -08004669 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004670 return channel;
4671}
4672
4673bool PeerConnection::HasDataChannels() const {
4674 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4675}
4676
4677void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4678 for (const auto& channel : sctp_data_channels_) {
4679 if (channel->id() < 0) {
4680 int sid;
4681 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004682 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004683 continue;
4684 }
4685 channel->SetSctpSid(sid);
4686 }
4687 }
4688}
4689
4690void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004691 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004692 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4693 ++it) {
4694 if (it->get() == channel) {
4695 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004696 // After the closing procedure is done, it's safe to use this ID for
4697 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004698 sid_allocator_.ReleaseSid(channel->id());
4699 }
deadbeefbd292462015-12-14 18:15:29 -08004700 // Since this method is triggered by a signal from the DataChannel,
4701 // we can't free it directly here; we need to free it asynchronously.
4702 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004703 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004704 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4705 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004706 return;
4707 }
4708 }
4709}
4710
deadbeefab9b2d12015-10-14 11:33:11 -07004711void PeerConnection::OnDataChannelDestroyed() {
4712 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4713 // DataChannel may callback to us and try to modify the list.
4714 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4715 temp_rtp_dcs.swap(rtp_data_channels_);
4716 for (const auto& kv : temp_rtp_dcs) {
4717 kv.second->OnTransportChannelDestroyed();
4718 }
4719
4720 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4721 temp_sctp_dcs.swap(sctp_data_channels_);
4722 for (const auto& channel : temp_sctp_dcs) {
4723 channel->OnTransportChannelDestroyed();
4724 }
4725}
4726
4727void PeerConnection::OnDataChannelOpenMessage(
4728 const std::string& label,
4729 const InternalDataChannelInit& config) {
4730 rtc::scoped_refptr<DataChannel> channel(
4731 InternalCreateDataChannel(label, &config));
4732 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004733 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004734 return;
4735 }
4736
deadbeefa601f5c2016-06-06 14:27:39 -07004737 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4738 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004739 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004740 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004741}
4742
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004743bool PeerConnection::HandleOpenMessage_s(
4744 const cricket::ReceiveDataParams& params,
4745 const rtc::CopyOnWriteBuffer& buffer) {
4746 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4747 // Received OPEN message; parse and signal that a new data channel should
4748 // be created.
4749 std::string label;
4750 InternalDataChannelInit config;
4751 config.id = params.ssrc;
4752 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4753 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4754 << params.ssrc;
4755 return true;
4756 }
4757 config.open_handshake_role = InternalDataChannelInit::kAcker;
4758 OnDataChannelOpenMessage(label, config);
4759 return true;
4760 }
4761 return false;
4762}
4763
Steve Anton4171afb2017-11-20 10:20:22 -08004764rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4765PeerConnection::GetAudioTransceiver() const {
4766 // This method only works with Plan B SDP, where there is a single
4767 // audio/video transceiver.
4768 RTC_DCHECK(!IsUnifiedPlan());
4769 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004770 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004771 return transceiver;
4772 }
4773 }
4774 RTC_NOTREACHED();
4775 return nullptr;
4776}
4777
4778rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4779PeerConnection::GetVideoTransceiver() const {
4780 // This method only works with Plan B SDP, where there is a single
4781 // audio/video transceiver.
4782 RTC_DCHECK(!IsUnifiedPlan());
4783 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004784 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004785 return transceiver;
4786 }
4787 }
4788 RTC_NOTREACHED();
4789 return nullptr;
4790}
4791
4792// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4793// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004794bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004795 switch (type) {
4796 case cricket::MEDIA_TYPE_AUDIO:
4797 return !GetAudioTransceiver()->internal()->senders().empty();
4798 case cricket::MEDIA_TYPE_VIDEO:
4799 return !GetVideoTransceiver()->internal()->senders().empty();
4800 case cricket::MEDIA_TYPE_DATA:
4801 return false;
4802 }
4803 RTC_NOTREACHED();
4804 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004805}
4806
Steve Anton4171afb2017-11-20 10:20:22 -08004807rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4808PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4809 for (auto transceiver : transceivers_) {
4810 for (auto sender : transceiver->internal()->senders()) {
4811 if (sender->track() == track) {
4812 return sender;
4813 }
4814 }
4815 }
4816 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004817}
4818
Steve Anton4171afb2017-11-20 10:20:22 -08004819rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4820PeerConnection::FindSenderById(const std::string& sender_id) const {
4821 for (auto transceiver : transceivers_) {
4822 for (auto sender : transceiver->internal()->senders()) {
4823 if (sender->id() == sender_id) {
4824 return sender;
4825 }
4826 }
4827 }
4828 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004829}
4830
Steve Anton4171afb2017-11-20 10:20:22 -08004831rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4832PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4833 for (auto transceiver : transceivers_) {
4834 for (auto receiver : transceiver->internal()->receivers()) {
4835 if (receiver->id() == receiver_id) {
4836 return receiver;
4837 }
4838 }
4839 }
4840 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004841}
4842
Steve Anton4171afb2017-11-20 10:20:22 -08004843std::vector<PeerConnection::RtpSenderInfo>*
4844PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4845 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4846 media_type == cricket::MEDIA_TYPE_VIDEO);
4847 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4848 ? &remote_audio_sender_infos_
4849 : &remote_video_sender_infos_;
4850}
4851
4852std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004853 cricket::MediaType media_type) {
4854 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4855 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004856 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4857 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004858}
4859
Steve Anton4171afb2017-11-20 10:20:22 -08004860const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4861 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004862 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004863 const std::string sender_id) const {
4864 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004865 if (sender_info.stream_id == stream_id &&
4866 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004867 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004868 }
4869 }
4870 return nullptr;
4871}
4872
4873DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4874 for (const auto& channel : sctp_data_channels_) {
4875 if (channel->id() == sid) {
4876 return channel;
4877 }
4878 }
4879 return nullptr;
4880}
4881
deadbeef91dd5672016-05-18 16:55:30 -07004882bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004883 const cricket::ServerAddresses& stun_servers,
4884 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004885 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004886 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004887 // To handle both internal and externally created port allocator, we will
4888 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004889 port_allocator_flags_ = port_allocator_->flags();
4890 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4891 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4892 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004893 // If the disable-IPv6 flag was specified, we'll not override it
4894 // by experiment.
4895 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004896 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004897 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4898 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004899 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004900 }
4901
zhihuangb09b3f92017-03-07 14:40:51 -08004902 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004903 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004904 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004905 }
4906
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004907 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004908 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004909 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004910 }
4911
honghaiz60347052016-05-31 18:29:12 -07004912 if (configuration.candidate_network_policy ==
4913 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004914 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004915 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004916 }
4917
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004918 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004919 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004920 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4921 }
4922
Qingsi Wanga2d60672018-04-11 16:57:45 -07004923 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004924 // No step delay is used while allocating ports.
4925 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4926 port_allocator_->set_candidate_filter(
4927 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004928 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004929
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004930 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004931 for (auto& turn_server : turn_servers_copy) {
4932 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004933 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004934 // Call this last since it may create pooled allocator sessions using the
4935 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004936 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004937 stun_servers, std::move(turn_servers_copy),
4938 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4939 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004940 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004941 return true;
4942}
4943
deadbeef91dd5672016-05-18 16:55:30 -07004944bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004945 const cricket::ServerAddresses& stun_servers,
4946 const std::vector<cricket::RelayServerConfig>& turn_servers,
4947 IceTransportsType type,
4948 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004949 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004950 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004951 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004952 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004953 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004954 // According to JSEP, after setLocalDescription, changing the candidate pool
4955 // size is not allowed, and changing the set of ICE servers will not result
4956 // in new candidates being gathered.
4957 if (local_description()) {
4958 port_allocator_->FreezeCandidatePool();
4959 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004960 // Add the custom tls turn servers if they exist.
4961 auto turn_servers_copy = turn_servers;
4962 for (auto& turn_server : turn_servers_copy) {
4963 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4964 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004965 // Call this last since it may create pooled allocator sessions using the
4966 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004967 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004968 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4969 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004970}
4971
Steve Antonba818672017-11-06 10:21:57 -08004972cricket::ChannelManager* PeerConnection::channel_manager() const {
4973 return factory_->channel_manager();
4974}
4975
Elad Alon99c3fe52017-10-13 16:29:40 +02004976bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004977 std::unique_ptr<RtcEventLogOutput> output,
4978 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004979 if (!event_log_) {
4980 return false;
4981 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004982 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004983}
4984
4985void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004986 if (event_log_) {
4987 event_log_->StopLogging();
4988 }
ivoc14d5dbe2016-07-04 07:06:55 -07004989}
nisseeaabdf62017-05-05 02:23:02 -07004990
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004991cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08004992 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004993 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004994 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08004995 if (channel && channel->content_name() == content_name) {
4996 return channel;
4997 }
Steve Anton75737c02017-11-06 10:37:17 -08004998 }
4999 if (rtp_data_channel() &&
5000 rtp_data_channel()->content_name() == content_name) {
5001 return rtp_data_channel();
5002 }
5003 return nullptr;
5004}
5005
5006bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005007 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005008 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005009 RTC_LOG(LS_INFO)
5010 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005011 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005012 return false;
5013 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005014 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005015 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005016 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005017 return false;
5018 }
5019
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005020 absl::optional<rtc::SSLRole> dtls_role;
5021 if (sctp_mid_) {
5022 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5023 } else if (is_caller_) {
5024 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5025 }
Zhi Huange830e682018-03-30 10:48:35 -07005026 if (dtls_role) {
5027 *role = *dtls_role;
5028 return true;
5029 }
5030 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005031}
5032
5033bool PeerConnection::GetSslRole(const std::string& content_name,
5034 rtc::SSLRole* role) {
5035 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005036 RTC_LOG(LS_INFO)
5037 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005038 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005039 return false;
5040 }
5041
Zhi Huange830e682018-03-30 10:48:35 -07005042 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5043 if (dtls_role) {
5044 *role = *dtls_role;
5045 return true;
5046 }
5047 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005048}
5049
Steve Antonf8470812017-12-04 10:46:21 -08005050void PeerConnection::SetSessionError(SessionError error,
5051 const std::string& error_desc) {
5052 RTC_DCHECK_RUN_ON(signaling_thread());
5053 if (error != session_error_) {
5054 session_error_ = error;
5055 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005056 }
5057}
5058
Zhi Huange830e682018-03-30 10:48:35 -07005059RTCError PeerConnection::UpdateSessionState(
5060 SdpType type,
5061 cricket::ContentSource source,
5062 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005063 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005064
5065 // If there's already a pending error then no state transition should happen.
5066 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005067 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005068
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005069 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005070 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005071 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005072 }
5073
5074 // Update the signaling state according to the specified state machine (see
5075 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005076 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005077 ChangeSignalingState(source == cricket::CS_LOCAL
5078 ? PeerConnectionInterface::kHaveLocalOffer
5079 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005080 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005081 ChangeSignalingState(source == cricket::CS_LOCAL
5082 ? PeerConnectionInterface::kHaveLocalPrAnswer
5083 : PeerConnectionInterface::kHaveRemotePrAnswer);
5084 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005085 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005086 ChangeSignalingState(PeerConnectionInterface::kStable);
5087 }
5088
5089 // Update internal objects according to the session description's media
5090 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005091 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005092 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005093 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005094 }
5095
Steve Anton8a006912017-12-04 15:25:56 -08005096 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005097}
5098
Steve Anton8a006912017-12-04 15:25:56 -08005099RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005100 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005101 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005102 const SessionDescriptionInterface* sdesc =
5103 (source == cricket::CS_LOCAL ? local_description()
5104 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005105 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005106
5107 // Push down the new SDP media section for each audio/video transceiver.
5108 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005109 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005110 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005111 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005112 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005113 continue;
5114 }
5115 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005116 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005117 if (!content_desc) {
5118 continue;
5119 }
5120 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005121 bool success = (source == cricket::CS_LOCAL)
5122 ? channel->SetLocalContent(content_desc, type, &error)
5123 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005124 if (!success) {
5125 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5126 }
5127 }
5128
5129 // If using the RtpDataChannel, push down the new SDP section for it too.
5130 if (rtp_data_channel_) {
5131 const ContentInfo* data_content =
5132 cricket::GetFirstDataContent(sdesc->description());
5133 if (data_content && !data_content->rejected) {
5134 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005135 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005136 if (data_desc) {
5137 std::string error;
5138 bool success =
5139 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005140 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005141 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005142 if (!success) {
5143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5144 std::move(error));
5145 }
Steve Anton75737c02017-11-06 10:37:17 -08005146 }
5147 }
5148 }
Steve Antoned10bd92017-12-05 10:52:59 -08005149
Steve Anton75737c02017-11-06 10:37:17 -08005150 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5151 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5152 if (sctp_transport_ && local_description() && remote_description() &&
5153 cricket::GetFirstDataContent(local_description()->description()) &&
5154 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005155 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005156 RTC_FROM_HERE,
5157 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005158 if (!success) {
5159 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5160 "Failed to push down SCTP parameters.");
5161 }
Steve Anton75737c02017-11-06 10:37:17 -08005162 }
Steve Antoned10bd92017-12-05 10:52:59 -08005163
Steve Anton8a006912017-12-04 15:25:56 -08005164 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005165}
5166
5167bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5168 RTC_DCHECK(network_thread()->IsCurrent());
5169 RTC_DCHECK(local_description());
5170 RTC_DCHECK(remote_description());
5171 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5172 // When we support "max-message-size", that would also be pushed down here.
5173 return sctp_transport_->Start(
5174 GetSctpPort(local_description()->description()),
5175 GetSctpPort(remote_description()->description()));
5176}
5177
Steve Anton8a006912017-12-04 15:25:56 -08005178RTCError PeerConnection::PushdownTransportDescription(
5179 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005180 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005181 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005182
Zhi Huange830e682018-03-30 10:48:35 -07005183 if (source == cricket::CS_LOCAL) {
5184 const SessionDescriptionInterface* sdesc = local_description();
5185 RTC_DCHECK(sdesc);
5186 return transport_controller_->SetLocalDescription(type,
5187 sdesc->description());
5188 } else {
5189 const SessionDescriptionInterface* sdesc = remote_description();
5190 RTC_DCHECK(sdesc);
5191 return transport_controller_->SetRemoteDescription(type,
5192 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005193 }
Steve Anton75737c02017-11-06 10:37:17 -08005194}
5195
5196bool PeerConnection::GetTransportDescription(
5197 const SessionDescription* description,
5198 const std::string& content_name,
5199 cricket::TransportDescription* tdesc) {
5200 if (!description || !tdesc) {
5201 return false;
5202 }
5203 const TransportInfo* transport_info =
5204 description->GetTransportInfoByName(content_name);
5205 if (!transport_info) {
5206 return false;
5207 }
5208 *tdesc = transport_info->description;
5209 return true;
5210}
5211
Steve Anton75737c02017-11-06 10:37:17 -08005212cricket::IceConfig PeerConnection::ParseIceConfig(
5213 const PeerConnectionInterface::RTCConfiguration& config) const {
5214 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005215 switch (config.continual_gathering_policy) {
5216 case PeerConnectionInterface::GATHER_ONCE:
5217 gathering_policy = cricket::GATHER_ONCE;
5218 break;
5219 case PeerConnectionInterface::GATHER_CONTINUALLY:
5220 gathering_policy = cricket::GATHER_CONTINUALLY;
5221 break;
5222 default:
5223 RTC_NOTREACHED();
5224 gathering_policy = cricket::GATHER_ONCE;
5225 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005226
Steve Anton75737c02017-11-06 10:37:17 -08005227 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005228 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5229 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005230 ice_config.prioritize_most_likely_candidate_pairs =
5231 config.prioritize_most_likely_ice_candidate_pairs;
5232 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005233 RTCConfigurationToIceConfigOptionalInt(
5234 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005235 ice_config.continual_gathering_policy = gathering_policy;
5236 ice_config.presume_writable_when_fully_relayed =
5237 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005238 ice_config.ice_check_interval_strong_connectivity =
5239 config.ice_check_interval_strong_connectivity;
5240 ice_config.ice_check_interval_weak_connectivity =
5241 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005242 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005243 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5244 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005245 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005246 ice_config.regather_all_networks_interval_range =
5247 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005248 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005249 return ice_config;
5250}
5251
Steve Antona41959e2018-11-28 11:15:33 -08005252static absl::string_view GetTrackIdBySsrc(
5253 const SessionDescriptionInterface* session_description,
5254 uint32_t ssrc) {
5255 if (!session_description) {
5256 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005257 }
Steve Antona41959e2018-11-28 11:15:33 -08005258 for (const cricket::ContentInfo& content :
5259 session_description->description()->contents()) {
5260 const cricket::MediaContentDescription& media =
5261 *content.media_description();
5262 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5263 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5264 const cricket::StreamParams* stream_params =
5265 cricket::GetStreamBySsrc(media.streams(), ssrc);
5266 if (stream_params) {
5267 return stream_params->id;
5268 }
5269 }
5270 }
5271 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005272}
5273
Steve Antona41959e2018-11-28 11:15:33 -08005274absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5275 return GetTrackIdBySsrc(local_description(), ssrc);
5276}
5277
5278absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5279 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005280}
5281
5282bool PeerConnection::SendData(const cricket::SendDataParams& params,
5283 const rtc::CopyOnWriteBuffer& payload,
5284 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005285 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5286 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5287 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005288 return false;
5289 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005290 if (media_transport_) {
5291 SendDataParams send_params;
5292 send_params.type = ToWebrtcDataMessageType(params.type);
5293 send_params.ordered = params.ordered;
5294 if (params.max_rtx_count >= 0) {
5295 send_params.max_rtx_count = params.max_rtx_count;
5296 } else if (params.max_rtx_ms >= 0) {
5297 send_params.max_rtx_ms = params.max_rtx_ms;
5298 }
5299 return media_transport_->SendData(params.sid, send_params, payload).ok();
5300 }
Steve Anton75737c02017-11-06 10:37:17 -08005301 return rtp_data_channel_
5302 ? rtp_data_channel_->SendData(params, payload, result)
5303 : network_thread()->Invoke<bool>(
5304 RTC_FROM_HERE,
5305 Bind(&cricket::SctpTransportInternal::SendData,
5306 sctp_transport_.get(), params, payload, result));
5307}
5308
5309bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005310 RTC_DCHECK_RUN_ON(signaling_thread());
5311 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005312 // Don't log an error here, because DataChannels are expected to call
5313 // ConnectDataChannel in this state. It's the only way to initially tell
5314 // whether or not the underlying transport is ready.
5315 return false;
5316 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005317 if (media_transport_) {
5318 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5319 &DataChannel::OnChannelReady);
5320 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5321 &DataChannel::OnDataReceived);
5322 SignalMediaTransportChannelClosing_s.connect(
5323 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5324 SignalMediaTransportChannelClosed_s.connect(
5325 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5326 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005327 rtp_data_channel_->SignalReadyToSendData.connect(
5328 webrtc_data_channel, &DataChannel::OnChannelReady);
5329 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5330 &DataChannel::OnDataReceived);
5331 } else {
5332 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5333 &DataChannel::OnChannelReady);
5334 SignalSctpDataReceived.connect(webrtc_data_channel,
5335 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005336 SignalSctpClosingProcedureStartedRemotely.connect(
5337 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5338 SignalSctpClosingProcedureComplete.connect(
5339 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005340 }
5341 return true;
5342}
5343
5344void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005345 RTC_DCHECK_RUN_ON(signaling_thread());
5346 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005347 RTC_LOG(LS_ERROR)
5348 << "DisconnectDataChannel called when rtp_data_channel_ and "
5349 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005350 return;
5351 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005352 if (media_transport_) {
5353 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5354 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5355 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5356 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5357 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005358 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5359 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5360 } else {
5361 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5362 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005363 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5364 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005365 }
5366}
5367
5368void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005369 if (media_transport_) {
5370 // No-op. Media transport does not need to add streams.
5371 return;
5372 }
Steve Anton75737c02017-11-06 10:37:17 -08005373 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005374 RTC_LOG(LS_ERROR)
5375 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005376 return;
5377 }
5378 network_thread()->Invoke<void>(
5379 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5380 sctp_transport_.get(), sid));
5381}
5382
5383void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005384 if (media_transport_) {
5385 media_transport_->CloseChannel(sid);
5386 return;
5387 }
Steve Anton75737c02017-11-06 10:37:17 -08005388 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005389 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005390 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005391 return;
5392 }
5393 network_thread()->Invoke<void>(
5394 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5395 sctp_transport_.get(), sid));
5396}
5397
5398bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005399 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005400 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005401 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005402 sctp_ready_to_send_data_;
5403}
5404
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005405void PeerConnection::OnDataReceived(int channel_id,
5406 DataMessageType type,
5407 const rtc::CopyOnWriteBuffer& buffer) {
5408 cricket::ReceiveDataParams params;
5409 params.sid = channel_id;
5410 params.type = ToCricketDataMessageType(type);
5411 media_transport_invoker_->AsyncInvoke<void>(
5412 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5413 RTC_DCHECK_RUN_ON(signaling_thread());
5414 if (!HandleOpenMessage_s(params, buffer)) {
5415 SignalMediaTransportReceivedData_s(params, buffer);
5416 }
5417 });
5418}
5419
5420void PeerConnection::OnChannelClosing(int channel_id) {
5421 media_transport_invoker_->AsyncInvoke<void>(
5422 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5423 RTC_DCHECK_RUN_ON(signaling_thread());
5424 SignalMediaTransportChannelClosing_s(channel_id);
5425 });
5426}
5427
5428void PeerConnection::OnChannelClosed(int channel_id) {
5429 media_transport_invoker_->AsyncInvoke<void>(
5430 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5431 RTC_DCHECK_RUN_ON(signaling_thread());
5432 SignalMediaTransportChannelClosed_s(channel_id);
5433 });
5434}
5435
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005436absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005437 if (sctp_mid_ && transport_controller_) {
5438 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5439 if (dtls_transport) {
5440 return dtls_transport->transport_name();
5441 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005442 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005443 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005444 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005445}
5446
Qingsi Wang72a43a12018-02-20 16:03:18 -08005447cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5448 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005449 network_thread()->Invoke<void>(
5450 RTC_FROM_HERE,
5451 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5452 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005453 return candidate_states_list;
5454}
5455
Steve Anton5dfde182018-02-06 10:34:40 -08005456std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5457 const {
5458 std::map<std::string, std::string> transport_names_by_mid;
5459 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005460 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005461 if (channel) {
5462 transport_names_by_mid[channel->content_name()] =
5463 channel->transport_name();
5464 }
Steve Anton75737c02017-11-06 10:37:17 -08005465 }
Steve Anton5dfde182018-02-06 10:34:40 -08005466 if (rtp_data_channel_) {
5467 transport_names_by_mid[rtp_data_channel_->content_name()] =
5468 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005469 }
5470 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005471 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005472 RTC_DCHECK(transport_name);
5473 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005474 }
Steve Anton5dfde182018-02-06 10:34:40 -08005475 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005476}
5477
Steve Anton5dfde182018-02-06 10:34:40 -08005478std::map<std::string, cricket::TransportStats>
5479PeerConnection::GetTransportStatsByNames(
5480 const std::set<std::string>& transport_names) {
5481 if (!network_thread()->IsCurrent()) {
5482 return network_thread()
5483 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5484 RTC_FROM_HERE,
5485 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005486 }
Steve Anton5dfde182018-02-06 10:34:40 -08005487 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5488 for (const std::string& transport_name : transport_names) {
5489 cricket::TransportStats transport_stats;
5490 bool success =
5491 transport_controller_->GetStats(transport_name, &transport_stats);
5492 if (success) {
5493 transport_stats_by_name[transport_name] = std::move(transport_stats);
5494 } else {
5495 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5496 << transport_name;
5497 }
5498 }
5499 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005500}
5501
5502bool PeerConnection::GetLocalCertificate(
5503 const std::string& transport_name,
5504 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005505 if (!certificate) {
5506 return false;
5507 }
5508 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5509 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005510}
5511
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005512std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005513 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005514 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005515}
5516
5517cricket::DataChannelType PeerConnection::data_channel_type() const {
5518 return data_channel_type_;
5519}
5520
5521bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5522 return pending_ice_restarts_.find(content_name) !=
5523 pending_ice_restarts_.end();
5524}
5525
Steve Anton75737c02017-11-06 10:37:17 -08005526bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5527 return transport_controller_->NeedsIceRestart(content_name);
5528}
5529
5530void PeerConnection::OnCertificateReady(
5531 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5532 transport_controller_->SetLocalCertificate(certificate);
5533}
5534
5535void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005536 SetSessionError(SessionError::kTransport,
5537 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005538}
5539
Alex Loiko9289eda2018-11-23 16:18:59 +00005540void PeerConnection::OnTransportControllerConnectionState(
5541 cricket::IceConnectionState state) {
5542 switch (state) {
5543 case cricket::kIceConnectionConnecting:
5544 // If the current state is Connected or Completed, then there were
5545 // writable channels but now there are not, so the next state must
5546 // be Disconnected.
5547 // kIceConnectionConnecting is currently used as the default,
5548 // un-connected state by the TransportController, so its only use is
5549 // detecting disconnections.
5550 if (ice_connection_state_ ==
5551 PeerConnectionInterface::kIceConnectionConnected ||
5552 ice_connection_state_ ==
5553 PeerConnectionInterface::kIceConnectionCompleted) {
5554 SetIceConnectionState(
5555 PeerConnectionInterface::kIceConnectionDisconnected);
5556 }
5557 break;
5558 case cricket::kIceConnectionFailed:
5559 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5560 break;
5561 case cricket::kIceConnectionConnected:
5562 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5563 "all transports are writable.";
5564 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5565 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5566 break;
5567 case cricket::kIceConnectionCompleted:
5568 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5569 "all transports are complete.";
5570 if (ice_connection_state_ !=
5571 PeerConnectionInterface::kIceConnectionConnected) {
5572 // If jumping directly from "checking" to "connected",
5573 // signal "connected" first.
5574 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5575 }
5576 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5577 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5578 ReportTransportStats();
5579 break;
5580 default:
5581 RTC_NOTREACHED();
5582 }
5583}
5584
Steve Anton75737c02017-11-06 10:37:17 -08005585void PeerConnection::OnTransportControllerCandidatesGathered(
5586 const std::string& transport_name,
5587 const cricket::Candidates& candidates) {
5588 RTC_DCHECK(signaling_thread()->IsCurrent());
5589 int sdp_mline_index;
5590 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005591 RTC_LOG(LS_ERROR)
5592 << "OnTransportControllerCandidatesGathered: content name "
5593 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005594 return;
5595 }
5596
5597 for (cricket::Candidates::const_iterator citer = candidates.begin();
5598 citer != candidates.end(); ++citer) {
5599 // Use transport_name as the candidate media id.
5600 std::unique_ptr<JsepIceCandidate> candidate(
5601 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5602 if (local_description()) {
5603 mutable_local_description()->AddCandidate(candidate.get());
5604 }
5605 OnIceCandidate(std::move(candidate));
5606 }
5607}
5608
5609void PeerConnection::OnTransportControllerCandidatesRemoved(
5610 const std::vector<cricket::Candidate>& candidates) {
5611 RTC_DCHECK(signaling_thread()->IsCurrent());
5612 // Sanity check.
5613 for (const cricket::Candidate& candidate : candidates) {
5614 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005615 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005616 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005617 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005618 return;
5619 }
5620 }
5621
5622 if (local_description()) {
5623 mutable_local_description()->RemoveCandidates(candidates);
5624 }
5625 OnIceCandidatesRemoved(candidates);
5626}
5627
5628void PeerConnection::OnTransportControllerDtlsHandshakeError(
5629 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005630 RTC_HISTOGRAM_ENUMERATION(
5631 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5632 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005633}
5634
Steve Antoned10bd92017-12-05 10:52:59 -08005635void PeerConnection::EnableSending() {
5636 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005637 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005638 if (channel && !channel->enabled()) {
5639 channel->Enable(true);
5640 }
Steve Anton75737c02017-11-06 10:37:17 -08005641 }
5642
Steve Anton4171afb2017-11-20 10:20:22 -08005643 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005644 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005645 }
Steve Anton75737c02017-11-06 10:37:17 -08005646}
5647
5648// Returns the media index for a local ice candidate given the content name.
5649bool PeerConnection::GetLocalCandidateMediaIndex(
5650 const std::string& content_name,
5651 int* sdp_mline_index) {
5652 if (!local_description() || !sdp_mline_index) {
5653 return false;
5654 }
5655
5656 bool content_found = false;
5657 const ContentInfos& contents = local_description()->description()->contents();
5658 for (size_t index = 0; index < contents.size(); ++index) {
5659 if (contents[index].name == content_name) {
5660 *sdp_mline_index = static_cast<int>(index);
5661 content_found = true;
5662 break;
5663 }
5664 }
5665 return content_found;
5666}
5667
5668bool PeerConnection::UseCandidatesInSessionDescription(
5669 const SessionDescriptionInterface* remote_desc) {
5670 if (!remote_desc) {
5671 return true;
5672 }
5673 bool ret = true;
5674
5675 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5676 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5677 for (size_t n = 0; n < candidates->count(); ++n) {
5678 const IceCandidateInterface* candidate = candidates->at(n);
5679 bool valid = false;
5680 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5681 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005682 RTC_LOG(LS_INFO)
5683 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005684 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005685 }
5686 continue;
5687 }
5688 ret = UseCandidate(candidate);
5689 if (!ret) {
5690 break;
5691 }
5692 }
5693 }
5694 return ret;
5695}
5696
5697bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5698 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5699 size_t remote_content_size =
5700 remote_description()->description()->contents().size();
5701 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005702 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005703 return false;
5704 }
5705
5706 cricket::ContentInfo content =
5707 remote_description()->description()->contents()[mediacontent_index];
5708 std::vector<cricket::Candidate> candidates;
5709 candidates.push_back(candidate->candidate());
5710 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005711 RTCError error =
5712 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005713 if (error.ok()) {
5714 // Candidates successfully submitted for checking.
5715 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5716 ice_connection_state_ ==
5717 PeerConnectionInterface::kIceConnectionDisconnected) {
5718 // If state is New, then the session has just gotten its first remote ICE
5719 // candidates, so go to Checking.
5720 // If state is Disconnected, the session is re-using old candidates or
5721 // receiving additional ones, so go to Checking.
5722 // If state is Connected, stay Connected.
5723 // TODO(bemasc): If state is Connected, and the new candidates are for a
5724 // newly added transport, then the state actually _should_ move to
5725 // checking. Add a way to distinguish that case.
5726 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5727 }
5728 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005729 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005730 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005731 }
5732 return true;
5733}
5734
5735void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005736 // Destroy video channel first since it may have a pointer to the
5737 // voice channel.
5738 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005739 if (!video_info || video_info->rejected) {
5740 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005741 }
5742
Steve Anton6fec8802017-12-04 10:37:29 -08005743 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5744 if (!audio_info || audio_info->rejected) {
5745 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005746 }
5747
5748 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5749 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005750 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005751 }
5752}
5753
Steve Antondcc3c022017-12-22 16:02:54 -08005754RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5755 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005756 const cricket::ContentGroup* bundle_group = nullptr;
5757 if (configuration_.bundle_policy ==
5758 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005759 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005760 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005761 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5762 "max-bundle configured but session description "
5763 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005764 }
5765 }
Steve Antondcc3c022017-12-22 16:02:54 -08005766 return std::move(bundle_group);
5767}
5768
5769RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005770 // Creating the media channels. Transports should already have been created
5771 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005772 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005773 if (voice && !voice->rejected &&
5774 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005775 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005776 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005777 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5778 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005779 }
5780 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5781 }
5782
Steve Antondcc3c022017-12-22 16:02:54 -08005783 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005784 if (video && !video->rejected &&
5785 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005786 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005787 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005788 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5789 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005790 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005791 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005792 }
5793
Steve Antondcc3c022017-12-22 16:02:54 -08005794 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005795 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005796 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005797 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005798 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5799 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005800 }
5801 }
5802
Steve Anton8a006912017-12-04 15:25:56 -08005803 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005804}
5805
Steve Anton4171afb2017-11-20 10:20:22 -08005806// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005807cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005808 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005809 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005810 MediaTransportInterface* media_transport = nullptr;
5811 if (configuration_.use_media_transport) {
5812 media_transport = GetMediaTransport(mid);
5813 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005814
Steve Anton75737c02017-11-06 10:37:17 -08005815 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005816 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005817 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5818 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005819 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005820 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005821 }
Steve Anton75737c02017-11-06 10:37:17 -08005822 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5823 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005824 voice_channel->SignalSentPacket.connect(this,
5825 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005826 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005827
Steve Antoneda6ccd2017-12-04 10:21:55 -08005828 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005829}
5830
Steve Anton4171afb2017-11-20 10:20:22 -08005831// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005832cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005833 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005834 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5835
5836 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005837 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005838 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005839 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5840 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005841 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005842 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005843 }
Steve Anton75737c02017-11-06 10:37:17 -08005844 video_channel->SignalDtlsSrtpSetupFailure.connect(
5845 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005846 video_channel->SignalSentPacket.connect(this,
5847 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005848 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005849
Steve Antoneda6ccd2017-12-04 10:21:55 -08005850 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005851}
5852
Zhi Huange830e682018-03-30 10:48:35 -07005853bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005854 switch (data_channel_type_) {
5855 case cricket::DCT_MEDIA_TRANSPORT:
5856 if (network_thread()->Invoke<bool>(
5857 RTC_FROM_HERE,
5858 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5859 this, mid))) {
5860 for (const auto& channel : sctp_data_channels_) {
5861 channel->OnTransportChannelCreated();
5862 }
5863 return true;
5864 }
Steve Anton75737c02017-11-06 10:37:17 -08005865 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005866 case cricket::DCT_SCTP:
5867 if (!sctp_factory_) {
5868 RTC_LOG(LS_ERROR)
5869 << "Trying to create SCTP transport, but didn't compile with "
5870 "SCTP support (HAVE_SCTP)";
5871 return false;
5872 }
5873 if (!network_thread()->Invoke<bool>(
5874 RTC_FROM_HERE,
5875 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5876 return false;
5877 }
5878 for (const auto& channel : sctp_data_channels_) {
5879 channel->OnTransportChannelCreated();
5880 }
5881 return true;
5882 case cricket::DCT_RTP:
5883 default:
5884 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5885 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5886 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5887 SrtpRequired(), GetCryptoOptions());
5888 if (!rtp_data_channel_) {
5889 return false;
5890 }
5891 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5892 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5893 rtp_data_channel_->SignalSentPacket.connect(
5894 this, &PeerConnection::OnSentPacket_w);
5895 rtp_data_channel_->SetRtpTransport(rtp_transport);
5896 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005897 }
5898
Steve Anton75737c02017-11-06 10:37:17 -08005899 return true;
5900}
5901
5902Call::Stats PeerConnection::GetCallStats() {
5903 if (!worker_thread()->IsCurrent()) {
5904 return worker_thread()->Invoke<Call::Stats>(
5905 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5906 }
5907 if (call_) {
5908 return call_->GetStats();
5909 } else {
5910 return Call::Stats();
5911 }
5912}
5913
Zhi Huange830e682018-03-30 10:48:35 -07005914bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005915 RTC_DCHECK(network_thread()->IsCurrent());
5916 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005917 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005918 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005919 RTC_DCHECK(dtls_transport);
5920 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005921 RTC_DCHECK(sctp_transport_);
5922 sctp_invoker_.reset(new rtc::AsyncInvoker());
5923 sctp_transport_->SignalReadyToSendData.connect(
5924 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5925 sctp_transport_->SignalDataReceived.connect(
5926 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005927 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5928 // another thread. Would be nice if there was a helper class similar to
5929 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5930 // code.
5931 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5932 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5933 sctp_transport_->SignalClosingProcedureComplete.connect(
5934 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005935 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005936 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005937 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005938}
5939
5940void PeerConnection::DestroySctpTransport_n() {
5941 RTC_DCHECK(network_thread()->IsCurrent());
5942 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005943 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005944 sctp_invoker_.reset(nullptr);
5945 sctp_ready_to_send_data_ = false;
5946}
5947
5948void PeerConnection::OnSctpTransportReadyToSendData_n() {
5949 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5950 RTC_DCHECK(network_thread()->IsCurrent());
5951 // Note: Cannot use rtc::Bind here because it will grab a reference to
5952 // PeerConnection and potentially cause PeerConnection to live longer than
5953 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5954 // be destroyed before PeerConnection is destroyed, and at that point all
5955 // pending tasks will be cleared.
5956 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5957 OnSctpTransportReadyToSendData_s(true);
5958 });
5959}
5960
5961void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5962 RTC_DCHECK(signaling_thread()->IsCurrent());
5963 sctp_ready_to_send_data_ = ready;
5964 SignalSctpReadyToSendData(ready);
5965}
5966
5967void PeerConnection::OnSctpTransportDataReceived_n(
5968 const cricket::ReceiveDataParams& params,
5969 const rtc::CopyOnWriteBuffer& payload) {
5970 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5971 RTC_DCHECK(network_thread()->IsCurrent());
5972 // Note: Cannot use rtc::Bind here because it will grab a reference to
5973 // PeerConnection and potentially cause PeerConnection to live longer than
5974 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5975 // be destroyed before PeerConnection is destroyed, and at that point all
5976 // pending tasks will be cleared.
5977 sctp_invoker_->AsyncInvoke<void>(
5978 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5979 OnSctpTransportDataReceived_s(params, payload);
5980 });
5981}
5982
5983void PeerConnection::OnSctpTransportDataReceived_s(
5984 const cricket::ReceiveDataParams& params,
5985 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005986 RTC_DCHECK_RUN_ON(signaling_thread());
5987 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005988 SignalSctpDataReceived(params, payload);
5989 }
5990}
5991
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005992void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005993 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5994 RTC_DCHECK(network_thread()->IsCurrent());
5995 sctp_invoker_->AsyncInvoke<void>(
5996 RTC_FROM_HERE, signaling_thread(),
5997 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005998 &SignalSctpClosingProcedureStartedRemotely, sid));
5999}
6000
6001void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6002 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6003 RTC_DCHECK(network_thread()->IsCurrent());
6004 sctp_invoker_->AsyncInvoke<void>(
6005 RTC_FROM_HERE, signaling_thread(),
6006 rtc::Bind(&sigslot::signal1<int>::operator(),
6007 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006008}
6009
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006010bool PeerConnection::SetupMediaTransportForDataChannels_n(
6011 const std::string& mid) {
6012 media_transport_ = transport_controller_->GetMediaTransport(mid);
6013 if (!media_transport_) {
6014 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6015 return false;
6016 }
6017
6018 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6019 media_transport_->SetDataSink(this);
6020 media_transport_data_mid_ = mid;
6021 transport_controller_->SignalMediaTransportStateChanged.connect(
6022 this, &PeerConnection::OnMediaTransportStateChanged_n);
6023 // Check the initial state right away, in case transport is already writable.
6024 OnMediaTransportStateChanged_n();
6025 return true;
6026}
6027
6028void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6029 if (!media_transport_) {
6030 return;
6031 }
6032 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6033 media_transport_data_mid_.reset();
6034 media_transport_->SetDataSink(nullptr);
6035 media_transport_invoker_ = nullptr;
6036 media_transport_ = nullptr;
6037}
6038
6039void PeerConnection::OnMediaTransportStateChanged_n() {
6040 if (!media_transport_data_mid_ ||
6041 transport_controller_->GetMediaTransportState(
6042 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6043 return;
6044 }
6045 media_transport_invoker_->AsyncInvoke<void>(
6046 RTC_FROM_HERE, signaling_thread(), [this] {
6047 RTC_DCHECK_RUN_ON(signaling_thread());
6048 media_transport_ready_to_send_data_ = true;
6049 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6050 });
6051}
6052
Steve Anton75737c02017-11-06 10:37:17 -08006053// Returns false if bundle is enabled and rtcp_mux is disabled.
6054bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6055 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6056 if (!bundle_enabled)
6057 return true;
6058
6059 const cricket::ContentGroup* bundle_group =
6060 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6061 RTC_DCHECK(bundle_group != NULL);
6062
6063 const cricket::ContentInfos& contents = desc->contents();
6064 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6065 citer != contents.end(); ++citer) {
6066 const cricket::ContentInfo* content = (&*citer);
6067 RTC_DCHECK(content != NULL);
6068 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006069 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006070 if (!HasRtcpMuxEnabled(content))
6071 return false;
6072 }
6073 }
6074 // RTCP-MUX is enabled in all the contents.
6075 return true;
6076}
6077
6078bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006079 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006080}
6081
Steve Anton8a006912017-12-04 15:25:56 -08006082RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006083 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006084 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006085 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006086 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006087 }
6088
6089 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006090 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006091 }
6092
Steve Anton3828c062017-12-06 10:34:51 -08006093 SdpType type = sdesc->GetType();
6094 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6095 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006096 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006097 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006098 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006099 }
6100
6101 // Verify crypto settings.
6102 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006103 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6104 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006105 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006106 if (!crypto_error.ok()) {
6107 return crypto_error;
6108 }
Steve Anton75737c02017-11-06 10:37:17 -08006109 }
6110
6111 // Verify ice-ufrag and ice-pwd.
6112 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006113 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6114 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006115 }
6116
6117 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006118 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6119 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006120 }
6121
6122 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6123 // m-lines that do not rtcp-mux enabled.
6124
6125 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006126 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006127 // With an answer we want to compare the new answer session description with
6128 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006129 const cricket::SessionDescription* offer_desc =
6130 (source == cricket::CS_LOCAL) ? remote_description()->description()
6131 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006132 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6133 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6134 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006135 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6136 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006137 }
6138 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006139 // The re-offers should respect the order of m= sections in current
6140 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006141 // With a re-offer, either the current local or current remote descriptions
6142 // could be the most up to date, so we would like to check against both of
6143 // them if they exist. It could be the case that one of them has a 0 port
6144 // for a media section, but the other does not. This is important to check
6145 // against in the case that we are recycling an m= section.
6146 const cricket::SessionDescription* current_desc = nullptr;
6147 const cricket::SessionDescription* secondary_current_desc = nullptr;
6148 if (local_description()) {
6149 current_desc = local_description()->description();
6150 if (remote_description()) {
6151 secondary_current_desc = remote_description()->description();
6152 }
6153 } else if (remote_description()) {
6154 current_desc = remote_description()->description();
6155 }
Steve Anton75737c02017-11-06 10:37:17 -08006156 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006157 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6158 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006159 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6160 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006161 }
6162 }
6163
Steve Antonba42e992018-04-09 14:10:01 -07006164 if (IsUnifiedPlan()) {
6165 // Ensure that each audio and video media section has at most one
6166 // "StreamParams". This will return an error if receiving a session
6167 // description from a "Plan B" endpoint which adds multiple tracks of the
6168 // same type. With Unified Plan, there can only be at most one track per
6169 // media section.
6170 for (const ContentInfo& content : sdesc->description()->contents()) {
6171 const MediaContentDescription& desc = *content.description;
6172 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6173 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6174 desc.streams().size() > 1u) {
6175 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6176 "Media section has more than one track specified "
6177 "with a=ssrc lines which is not supported with "
6178 "Unified Plan.");
6179 }
6180 }
6181 }
6182
Steve Anton8a006912017-12-04 15:25:56 -08006183 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006184}
6185
Steve Anton3828c062017-12-06 10:34:51 -08006186bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006187 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006188 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006189 return (state == PeerConnectionInterface::kStable) ||
6190 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006191 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006192 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006193 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6194 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6195 }
6196}
6197
Steve Anton3828c062017-12-06 10:34:51 -08006198bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006199 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006200 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006201 return (state == PeerConnectionInterface::kStable) ||
6202 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006203 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006204 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006205 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6206 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6207 }
6208}
6209
Steve Antonf8470812017-12-04 10:46:21 -08006210const char* PeerConnection::SessionErrorToString(SessionError error) const {
6211 switch (error) {
6212 case SessionError::kNone:
6213 return "ERROR_NONE";
6214 case SessionError::kContent:
6215 return "ERROR_CONTENT";
6216 case SessionError::kTransport:
6217 return "ERROR_TRANSPORT";
6218 }
6219 RTC_NOTREACHED();
6220 return "";
6221}
6222
Steve Anton75737c02017-11-06 10:37:17 -08006223std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006224 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006225 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6226 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006227 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006228}
6229
Steve Anton8e20f172018-03-06 10:55:04 -08006230void PeerConnection::ReportSdpFormatReceived(
6231 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006232 int num_audio_mlines = 0;
6233 int num_video_mlines = 0;
6234 int num_audio_tracks = 0;
6235 int num_video_tracks = 0;
6236 for (const ContentInfo& content : remote_offer.description()->contents()) {
6237 cricket::MediaType media_type = content.media_description()->type();
6238 int num_tracks = std::max(
6239 1, static_cast<int>(content.media_description()->streams().size()));
6240 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6241 num_audio_mlines += 1;
6242 num_audio_tracks += num_tracks;
6243 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6244 num_video_mlines += 1;
6245 num_video_tracks += num_tracks;
6246 }
6247 }
6248 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6249 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6250 format = kSdpFormatReceivedComplexUnifiedPlan;
6251 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6252 format = kSdpFormatReceivedComplexPlanB;
6253 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6254 format = kSdpFormatReceivedSimple;
6255 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006256 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6257 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006258}
6259
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006260void PeerConnection::NoteUsageEvent(UsageEvent event) {
6261 RTC_DCHECK_RUN_ON(signaling_thread());
6262 usage_event_accumulator_ |= static_cast<int>(event);
6263}
6264
6265void PeerConnection::ReportUsagePattern() const {
6266 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006267 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6268 usage_event_accumulator_,
6269 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006270 const int bad_bits =
6271 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6272 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6273 const int good_bits =
6274 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6275 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6276 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6277 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6278 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006279 // If called after close(), we can't report, because observer may have
6280 // been deallocated, and therefore pointer is null. Write to log instead.
6281 if (observer_) {
6282 Observer()->OnInterestingUsage(usage_event_accumulator_);
6283 } else {
6284 RTC_LOG(LS_INFO) << "Interesting usage signature "
6285 << usage_event_accumulator_
6286 << " observed after observer shutdown";
6287 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006288 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006289}
6290
Steve Anton0ffaaa22018-02-23 10:31:30 -08006291void PeerConnection::ReportNegotiatedSdpSemantics(
6292 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006293 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006294 switch (answer.description()->msid_signaling()) {
6295 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006296 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006297 break;
6298 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006299 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006300 break;
6301 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006302 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006303 break;
6304 case cricket::kMsidSignalingMediaSection |
6305 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006306 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006307 break;
6308 default:
6309 RTC_NOTREACHED();
6310 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006311 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6312 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006313}
6314
Steve Anton75737c02017-11-06 10:37:17 -08006315// We need to check the local/remote description for the Transport instead of
6316// the session, because a new Transport added during renegotiation may have
6317// them unset while the session has them set from the previous negotiation.
6318// Not doing so may trigger the auto generation of transport description and
6319// mess up DTLS identity information, ICE credential, etc.
6320bool PeerConnection::ReadyToUseRemoteCandidate(
6321 const IceCandidateInterface* candidate,
6322 const SessionDescriptionInterface* remote_desc,
6323 bool* valid) {
6324 *valid = true;
6325
6326 const SessionDescriptionInterface* current_remote_desc =
6327 remote_desc ? remote_desc : remote_description();
6328
6329 if (!current_remote_desc) {
6330 return false;
6331 }
6332
6333 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6334 size_t remote_content_size =
6335 current_remote_desc->description()->contents().size();
6336 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006337 RTC_LOG(LS_ERROR)
6338 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6339 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006340
6341 *valid = false;
6342 return false;
6343 }
6344
6345 cricket::ContentInfo content =
6346 current_remote_desc->description()->contents()[mediacontent_index];
6347
6348 const std::string transport_name = GetTransportName(content.name);
6349 if (transport_name.empty()) {
6350 return false;
6351 }
Zhi Huange830e682018-03-30 10:48:35 -07006352 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006353}
6354
6355bool PeerConnection::SrtpRequired() const {
6356 return dtls_enabled_ ||
6357 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6358}
6359
6360void PeerConnection::OnTransportControllerGatheringState(
6361 cricket::IceGatheringState state) {
6362 RTC_DCHECK(signaling_thread()->IsCurrent());
6363 if (state == cricket::kIceGatheringGathering) {
6364 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6365 } else if (state == cricket::kIceGatheringComplete) {
6366 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6367 }
6368}
6369
6370void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006371 std::map<std::string, std::set<cricket::MediaType>>
6372 media_types_by_transport_name;
6373 for (auto transceiver : transceivers_) {
6374 if (transceiver->internal()->channel()) {
6375 const std::string& transport_name =
6376 transceiver->internal()->channel()->transport_name();
6377 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006378 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006379 }
Steve Anton75737c02017-11-06 10:37:17 -08006380 }
6381 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006382 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6383 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006384 }
Zhi Huange830e682018-03-30 10:48:35 -07006385
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006386 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006387 if (transport_name) {
6388 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006389 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006390 }
Zhi Huange830e682018-03-30 10:48:35 -07006391
Steve Antonc7b964c2018-02-01 14:39:45 -08006392 for (const auto& entry : media_types_by_transport_name) {
6393 const std::string& transport_name = entry.first;
6394 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006395 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006396 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006397 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006398 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006399 }
6400 }
6401}
6402// Walk through the ConnectionInfos to gather best connection usage
6403// for IPv4 and IPv6.
6404void PeerConnection::ReportBestConnectionState(
6405 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006406 for (const cricket::TransportChannelStats& channel_stats :
6407 stats.channel_stats) {
6408 for (const cricket::ConnectionInfo& connection_info :
6409 channel_stats.connection_infos) {
6410 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006411 continue;
6412 }
6413
Steve Antonc7b964c2018-02-01 14:39:45 -08006414 const cricket::Candidate& local = connection_info.local_candidate;
6415 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006416
6417 // Increment the counter for IceCandidatePairType.
6418 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6419 (local.type() == RELAY_PORT_TYPE &&
6420 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006421 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6422 GetIceCandidatePairCounter(local, remote),
6423 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006424 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006425 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6426 GetIceCandidatePairCounter(local, remote),
6427 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006428 } else {
6429 RTC_CHECK(0);
6430 }
Steve Anton75737c02017-11-06 10:37:17 -08006431
6432 // Increment the counter for IP type.
6433 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006434 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6435 kBestConnections_IPv4,
6436 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006437 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006438 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6439 kBestConnections_IPv6,
6440 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006441 } else {
6442 RTC_CHECK(0);
6443 }
6444
6445 return;
6446 }
6447 }
6448}
6449
6450void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006451 const cricket::TransportStats& stats,
6452 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006453 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6454 return;
6455 }
6456
6457 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6458 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6459 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6460 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6461 return;
6462 }
6463
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006464 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6465 for (cricket::MediaType media_type : media_types) {
6466 switch (media_type) {
6467 case cricket::MEDIA_TYPE_AUDIO:
6468 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6469 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6470 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6471 break;
6472 case cricket::MEDIA_TYPE_VIDEO:
6473 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6474 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6475 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6476 break;
6477 case cricket::MEDIA_TYPE_DATA:
6478 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6479 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6480 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6481 break;
6482 default:
6483 RTC_NOTREACHED();
6484 continue;
6485 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006486 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006487 }
6488
6489 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6490 for (cricket::MediaType media_type : media_types) {
6491 switch (media_type) {
6492 case cricket::MEDIA_TYPE_AUDIO:
6493 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6494 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6495 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6496 break;
6497 case cricket::MEDIA_TYPE_VIDEO:
6498 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6499 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6500 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6501 break;
6502 case cricket::MEDIA_TYPE_DATA:
6503 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6504 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6505 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6506 break;
6507 default:
6508 RTC_NOTREACHED();
6509 continue;
6510 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006511 }
Steve Anton75737c02017-11-06 10:37:17 -08006512 }
6513}
6514
6515void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6516 RTC_DCHECK(worker_thread()->IsCurrent());
6517 RTC_DCHECK(call_);
6518 call_->OnSentPacket(sent_packet);
6519}
6520
6521const std::string PeerConnection::GetTransportName(
6522 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006523 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006524 if (channel) {
6525 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006526 }
Steve Anton6fec8802017-12-04 10:37:29 -08006527 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006528 RTC_DCHECK(sctp_mid_);
6529 if (content_name == *sctp_mid_) {
6530 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006531 }
6532 }
6533 // Return an empty string if failed to retrieve the transport name.
6534 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006535}
6536
Steve Anton6fec8802017-12-04 10:37:29 -08006537void PeerConnection::DestroyTransceiverChannel(
6538 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6539 transceiver) {
6540 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006541
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006542 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006543 if (channel) {
6544 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006545 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006546 }
6547}
6548
6549void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006550 if (rtp_data_channel_) {
6551 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006552 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006553 rtp_data_channel_ = nullptr;
6554 }
6555
6556 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6557 // grab a reference to this PeerConnection. If this is called from the
6558 // PeerConnection destructor, the RefCountedObject vtable will have already
6559 // been destroyed (since it is a subclass of PeerConnection) and using
6560 // rtc::Bind will cause "Pure virtual function called" error to appear.
6561
6562 if (sctp_transport_) {
6563 OnDataChannelDestroyed();
6564 network_thread()->Invoke<void>(RTC_FROM_HERE,
6565 [this] { DestroySctpTransport_n(); });
6566 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006567
6568 if (media_transport_) {
6569 OnDataChannelDestroyed();
6570 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6571 RTC_DCHECK_RUN_ON(network_thread());
6572 TeardownMediaTransportForDataChannels_n();
6573 });
6574 }
Steve Anton6fec8802017-12-04 10:37:29 -08006575}
6576
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006577void PeerConnection::DestroyChannelInterface(
6578 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006579 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006580 switch (channel->media_type()) {
6581 case cricket::MEDIA_TYPE_AUDIO:
6582 channel_manager()->DestroyVoiceChannel(
6583 static_cast<cricket::VoiceChannel*>(channel));
6584 break;
6585 case cricket::MEDIA_TYPE_VIDEO:
6586 channel_manager()->DestroyVideoChannel(
6587 static_cast<cricket::VideoChannel*>(channel));
6588 break;
6589 case cricket::MEDIA_TYPE_DATA:
6590 channel_manager()->DestroyRtpDataChannel(
6591 static_cast<cricket::RtpDataChannel*>(channel));
6592 break;
6593 default:
6594 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6595 break;
6596 }
Zhi Huange830e682018-03-30 10:48:35 -07006597}
Steve Anton6fec8802017-12-04 10:37:29 -08006598
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006599bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006600 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006601 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006602 cricket::DtlsTransportInternal* dtls_transport,
6603 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006604 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006605 auto base_channel = GetChannel(mid);
6606 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006607 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006608 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006609 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006610 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006611 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006612
6613 call_->MediaTransportChange(media_transport);
6614
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006615 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006616}
6617
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006618PeerConnectionObserver* PeerConnection::Observer() const {
6619 // In earlier production code, the pointer was not cleared on close,
6620 // which might have led to undefined behavior if the observer was not
6621 // deallocated, or strange crashes if it was.
6622 // We use CHECK in order to catch such behavior if it exists.
6623 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6624 RTC_CHECK(observer_);
6625 return observer_;
6626}
6627
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006628CryptoOptions PeerConnection::GetCryptoOptions() {
6629 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6630 // after it has been removed.
6631 return configuration_.crypto_options.has_value()
6632 ? *configuration_.crypto_options
6633 : factory_->options().crypto_options;
6634}
6635
Harald Alvestrand89061872018-01-02 14:08:34 +01006636void PeerConnection::ClearStatsCache() {
6637 if (stats_collector_) {
6638 stats_collector_->ClearCachedStatsReport();
6639 }
6640}
6641
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006642void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006643 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6644 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006645}
6646
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006647} // namespace webrtc