blob: f24073dbf3610573780dc5e74362200f4cfb6537 [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;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800705 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200706 absl::optional<int> stun_candidate_keepalive_interval;
707 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200708 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800709 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200710 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700711 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700712 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700713 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700714 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100715 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800716 };
717 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
718 "Did you add something to RTCConfiguration and forget to "
719 "update operator==?");
720 return type == o.type && servers == o.servers &&
721 bundle_policy == o.bundle_policy &&
722 rtcp_mux_policy == o.rtcp_mux_policy &&
723 tcp_candidate_policy == o.tcp_candidate_policy &&
724 candidate_network_policy == o.candidate_network_policy &&
725 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
726 audio_jitter_buffer_fast_accelerate ==
727 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100728 audio_jitter_buffer_min_delay_ms ==
729 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800730 ice_connection_receiving_timeout ==
731 o.ice_connection_receiving_timeout &&
732 ice_backup_candidate_pair_ping_interval ==
733 o.ice_backup_candidate_pair_ping_interval &&
734 continual_gathering_policy == o.continual_gathering_policy &&
735 certificates == o.certificates &&
736 prioritize_most_likely_ice_candidate_pairs ==
737 o.prioritize_most_likely_ice_candidate_pairs &&
738 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800739 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700740 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100741 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800742 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800743 screencast_min_bitrate == o.screencast_min_bitrate &&
744 combined_audio_video_bwe == o.combined_audio_video_bwe &&
745 enable_dtls_srtp == o.enable_dtls_srtp &&
746 ice_candidate_pool_size == o.ice_candidate_pool_size &&
747 prune_turn_ports == o.prune_turn_ports &&
748 presume_writable_when_fully_relayed ==
749 o.presume_writable_when_fully_relayed &&
750 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800751 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800752 ice_check_interval_strong_connectivity ==
753 o.ice_check_interval_strong_connectivity &&
754 ice_check_interval_weak_connectivity ==
755 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700756 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700757 ice_unwritable_timeout == o.ice_unwritable_timeout &&
758 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800759 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800760 stun_candidate_keepalive_interval ==
761 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200762 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800763 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800764 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700765 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700766 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700767 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700768 use_media_transport_for_data_channels ==
769 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100770 crypto_options == o.crypto_options &&
771 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800772}
773
774bool PeerConnectionInterface::RTCConfiguration::operator!=(
775 const PeerConnectionInterface::RTCConfiguration& o) const {
776 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800777}
778
zhihuang8f65cdf2016-05-06 18:40:30 -0700779// Generate a RTCP CNAME when a PeerConnection is created.
780std::string GenerateRtcpCname() {
781 std::string cname;
782 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100783 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800784 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700785 }
786 return cname;
787}
788
zhihuang1c378ed2017-08-17 14:10:50 -0700789bool ValidateOfferAnswerOptions(
790 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
791 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
792 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700793}
794
zhihuang1c378ed2017-08-17 14:10:50 -0700795// From |rtc_options|, fill parts of |session_options| shared by all generated
796// m= sections (in other words, nothing that involves a map/array).
797void ExtractSharedMediaSessionOptions(
798 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
799 cricket::MediaSessionOptions* session_options) {
800 session_options->vad_enabled = rtc_options.voice_activity_detection;
801 session_options->bundle_enabled = rtc_options.use_rtp_mux;
802}
zhihuanga77e6bb2017-08-14 18:17:48 -0700803
zhihuang38ede132017-06-15 12:52:32 -0700804PeerConnection::PeerConnection(PeerConnectionFactory* factory,
805 std::unique_ptr<RtcEventLog> event_log,
806 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000807 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700808 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700809 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700810 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700811 remote_streams_(StreamCollection::Create()),
812 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813
814PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100815 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800816 RTC_DCHECK_RUN_ON(signaling_thread());
817
Steve Anton8af21862017-12-15 11:20:13 -0800818 // Need to stop transceivers before destroying the stats collector because
819 // AudioRtpSender has a reference to the StatsCollector it will update when
820 // stopping.
821 for (auto transceiver : transceivers_) {
822 transceiver->Stop();
823 }
Steve Anton4171afb2017-11-20 10:20:22 -0800824
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700825 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800826 if (stats_collector_) {
827 stats_collector_->WaitForPendingRequest();
828 stats_collector_ = nullptr;
829 }
Steve Anton75737c02017-11-06 10:37:17 -0800830
Steve Anton8af21862017-12-15 11:20:13 -0800831 // Don't destroy BaseChannels until after stats has been cleaned up so that
832 // the last stats request can still read from the channels.
833 DestroyAllChannels();
834
Mirko Bonadei675513b2017-11-09 11:09:25 +0100835 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800836
837 webrtc_session_desc_factory_.reset();
838 sctp_invoker_.reset();
839 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800840 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800841 transport_controller_.reset();
842
deadbeef91dd5672016-05-18 16:55:30 -0700843 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700844 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700845 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700846 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700847 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700848 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800849 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700850 event_log_.reset();
851 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852}
853
Steve Anton8af21862017-12-15 11:20:13 -0800854void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800855 // Destroy video channels first since they may have a pointer to a voice
856 // channel.
857 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800858 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800859 DestroyTransceiverChannel(transceiver);
860 }
861 }
862 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800863 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800864 DestroyTransceiverChannel(transceiver);
865 }
866 }
867 DestroyDataChannel();
868}
869
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000871 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700872 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100873 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700874
875 RTCError config_error = ValidateConfiguration(configuration);
876 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100877 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700878 return false;
879 }
880
Benjamin Wrightcab58882018-05-02 15:12:47 -0700881 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100882 RTC_LOG(LS_ERROR)
883 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100884 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800885 return false;
886 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200887
Benjamin Wrightcab58882018-05-02 15:12:47 -0700888 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800889 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100890 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100891 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800892 return false;
893 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700894
Benjamin Wrightcab58882018-05-02 15:12:47 -0700895 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700896 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700898 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800899
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200900 cricket::ServerAddresses stun_servers;
901 std::vector<cricket::RelayServerConfig> turn_servers;
902
903 RTCErrorType parse_error =
904 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
905 if (parse_error != RTCErrorType::NONE) {
906 return false;
907 }
908
deadbeef91dd5672016-05-18 16:55:30 -0700909 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700910 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700911 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200912 RTC_FROM_HERE,
913 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
914 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915 return false;
916 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200917 // If initialization was successful, note if STUN or TURN servers
918 // were supplied.
919 if (!stun_servers.empty()) {
920 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
921 }
922 if (!turn_servers.empty()) {
923 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
924 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700926 // Send information about IPv4/IPv6 status.
927 PeerConnectionAddressFamilyCounter address_family;
928 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
929 address_family = kPeerConnection_IPv6;
930 } else {
931 address_family = kPeerConnection_IPv4;
932 }
933 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
934 kPeerConnectionAddressFamilyCounter_Max);
935
Zhi Huange830e682018-03-30 10:48:35 -0700936 const PeerConnectionFactoryInterface::Options& options = factory_->options();
937
Steve Anton75737c02017-11-06 10:37:17 -0800938 // RFC 3264: The numeric value of the session id and version in the
939 // o line MUST be representable with a "64 bit signed integer".
940 // Due to this constraint session id |session_id_| is max limited to
941 // LLONG_MAX.
942 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700943 JsepTransportController::Config config;
944 config.redetermine_role_on_ice_restart =
945 configuration.redetermine_role_on_ice_restart;
946 config.ssl_max_version = factory_->options().ssl_max_version;
947 config.disable_encryption = options.disable_encryption;
948 config.bundle_policy = configuration.bundle_policy;
949 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700950 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
951 // stub.
952 config.crypto_options = configuration.crypto_options.has_value()
953 ? *configuration.crypto_options
954 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700955 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700956 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700957#if defined(ENABLE_EXTERNAL_AUTH)
958 config.enable_external_auth = true;
959#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700960 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700961
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700962 if (configuration.use_media_transport ||
963 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700964 if (!factory_->media_transport_factory()) {
965 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700966 << "PeerConnecton is initialized with use_media_transport = true or "
967 << "use_media_transport_for_data_channels = true "
968 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700969 return false;
970 }
971
972 config.media_transport_factory = factory_->media_transport_factory();
973 }
974
Zhi Huange830e682018-03-30 10:48:35 -0700975 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700976 signaling_thread(), network_thread(), port_allocator_.get(),
977 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700978 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +0000979 this, &PeerConnection::OnTransportControllerConnectionState);
980 transport_controller_->SignalStandardizedIceConnectionState.connect(
981 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +0200982 transport_controller_->SignalConnectionState.connect(
983 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700984 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800985 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700986 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800987 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700988 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800989 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
990 transport_controller_->SignalDtlsHandshakeError.connect(
991 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
992
993 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700994
deadbeefab9b2d12015-10-14 11:33:11 -0700995 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700996 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000997
Steve Antonba818672017-11-06 10:21:57 -0800998 configuration_ = configuration;
999
Steve Anton75737c02017-11-06 10:37:17 -08001000 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1001 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1002 if (!configuration.certificates.empty()) {
1003 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1004 // just picking the first one. The decision should be made based on the DTLS
1005 // handshake. The DTLS negotiations need to know about all certificates.
1006 certificate = configuration.certificates[0];
1007 }
1008
Steve Antond25da372017-11-06 14:50:29 -08001009 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001010
1011 if (options.disable_encryption) {
1012 dtls_enabled_ = false;
1013 } else {
1014 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001015 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001016 // |configuration| can override the default |dtls_enabled_| value.
1017 if (configuration.enable_dtls_srtp) {
1018 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1019 }
1020 }
1021
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001022 if (configuration.use_media_transport_for_data_channels) {
1023 if (configuration.enable_rtp_data_channel) {
1024 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1025 "use_media_transport_for_data_channels are "
1026 "incompatible and cannot both be set to true";
1027 return false;
1028 }
1029 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1030 } else if (configuration.enable_rtp_data_channel) {
1031 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1032 // set. It takes precendence over the disable_sctp_data_channels
1033 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001034 data_channel_type_ = cricket::DCT_RTP;
1035 } else {
1036 // DTLS has to be enabled to use SCTP.
1037 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1038 data_channel_type_ = cricket::DCT_SCTP;
1039 }
1040 }
1041
1042 video_options_.screencast_min_bitrate_kbps =
1043 configuration.screencast_min_bitrate;
1044 audio_options_.combined_audio_video_bwe =
1045 configuration.combined_audio_video_bwe;
1046
1047 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001048 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001049
1050 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001051 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001052
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001053 audio_options_.audio_jitter_buffer_min_delay_ms =
1054 configuration.audio_jitter_buffer_min_delay_ms;
1055
Steve Anton75737c02017-11-06 10:37:17 -08001056 // Whether the certificate generator/certificate is null or not determines
1057 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1058 // the right instructions by clearing the variables if needed.
1059 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001060 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001061 certificate = nullptr;
1062 } else if (certificate) {
1063 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001064 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001065 }
1066
1067 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1068 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001069 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001070 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1071 this, &PeerConnection::OnCertificateReady);
1072
1073 if (options.disable_encryption) {
1074 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1075 }
1076
1077 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001078 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001079 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080
Steve Anton4171afb2017-11-20 10:20:22 -08001081 // Add default audio/video transceivers for Plan B SDP.
1082 if (!IsUnifiedPlan()) {
1083 transceivers_.push_back(
1084 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1085 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1086 transceivers_.push_back(
1087 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1088 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1089 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001090 int delay_ms =
1091 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001092 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1093 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001094 return true;
1095}
1096
Steve Anton038834f2017-07-14 15:59:59 -07001097RTCError PeerConnection::ValidateConfiguration(
1098 const RTCConfiguration& config) const {
1099 if (config.ice_regather_interval_range &&
1100 config.continual_gathering_policy == GATHER_ONCE) {
1101 return RTCError(RTCErrorType::INVALID_PARAMETER,
1102 "ice_regather_interval_range specified but continual "
1103 "gathering policy is GATHER_ONCE");
1104 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001105 auto result =
1106 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1107 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001108}
1109
Yves Gerey665174f2018-06-19 15:03:05 +02001110rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001111 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1112 "Plan SdpSemantics. Please use GetSenders "
1113 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001114 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115}
1116
Yves Gerey665174f2018-06-19 15:03:05 +02001117rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001118 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1119 "Plan SdpSemantics. Please use GetReceivers "
1120 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001121 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001122}
1123
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001124bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001125 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1126 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001127 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001128 if (IsClosed()) {
1129 return false;
1130 }
deadbeefab9b2d12015-10-14 11:33:11 -07001131 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001132 return false;
1133 }
deadbeefab9b2d12015-10-14 11:33:11 -07001134
1135 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001136 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1137 observer->SignalAudioTrackAdded.connect(this,
1138 &PeerConnection::OnAudioTrackAdded);
1139 observer->SignalAudioTrackRemoved.connect(
1140 this, &PeerConnection::OnAudioTrackRemoved);
1141 observer->SignalVideoTrackAdded.connect(this,
1142 &PeerConnection::OnVideoTrackAdded);
1143 observer->SignalVideoTrackRemoved.connect(
1144 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001145 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001146
deadbeefab9b2d12015-10-14 11:33:11 -07001147 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001148 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001149 }
1150 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001151 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001152 }
1153
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001154 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001155 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001156 return true;
1157}
1158
1159void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001160 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1161 "Plan SdpSemantics. Please use RemoveTrack "
1162 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001163 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001164 if (!IsClosed()) {
1165 for (const auto& track : local_stream->GetAudioTracks()) {
1166 RemoveAudioTrack(track.get(), local_stream);
1167 }
1168 for (const auto& track : local_stream->GetVideoTracks()) {
1169 RemoveVideoTrack(track.get(), local_stream);
1170 }
deadbeefab9b2d12015-10-14 11:33:11 -07001171 }
deadbeefab9b2d12015-10-14 11:33:11 -07001172 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001173 stream_observers_.erase(
1174 std::remove_if(
1175 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001176 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001177 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001178 }),
1179 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001180
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001181 if (IsClosed()) {
1182 return;
1183 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001184 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001185}
1186
Steve Anton2d6c76a2018-01-05 17:10:52 -08001187RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001188 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001189 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001190 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001191 if (!track) {
1192 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1193 }
1194 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1195 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1196 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1197 "Track has invalid kind: " + track->kind());
1198 }
Steve Antonf9381f02017-12-14 10:23:57 -08001199 if (IsClosed()) {
1200 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1201 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001202 }
Steve Anton4171afb2017-11-20 10:20:22 -08001203 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001204 LOG_AND_RETURN_ERROR(
1205 RTCErrorType::INVALID_PARAMETER,
1206 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001207 }
Steve Antonf9381f02017-12-14 10:23:57 -08001208 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001209 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1210 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001211 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001212 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001213 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001214 }
1215 return sender_or_error;
1216}
deadbeefe1f9d832016-01-14 15:35:42 -08001217
Steve Antonf9381f02017-12-14 10:23:57 -08001218RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1219PeerConnection::AddTrackPlanB(
1220 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001221 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001222 if (stream_ids.size() > 1u) {
1223 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1224 "AddTrack with more than one stream is not "
1225 "supported with Plan B semantics.");
1226 }
1227 std::vector<std::string> adjusted_stream_ids = stream_ids;
1228 if (adjusted_stream_ids.empty()) {
1229 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1230 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001231 cricket::MediaType media_type =
1232 (track->kind() == MediaStreamTrackInterface::kAudioKind
1233 ? cricket::MEDIA_TYPE_AUDIO
1234 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001235 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001236 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001237 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001238 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001239 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001240 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001241 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001242 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001243 if (sender_info) {
1244 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001245 }
Steve Antonf9381f02017-12-14 10:23:57 -08001246 } else {
1247 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001248 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001249 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001250 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001251 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001252 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001253 if (sender_info) {
1254 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001255 }
deadbeefe1f9d832016-01-14 15:35:42 -08001256 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001257 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001258}
deadbeefe1f9d832016-01-14 15:35:42 -08001259
Steve Antonf9381f02017-12-14 10:23:57 -08001260RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1261PeerConnection::AddTrackUnifiedPlan(
1262 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001263 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001264 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1265 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001266 RTC_LOG(LS_INFO) << "Reusing an existing "
1267 << cricket::MediaTypeToString(transceiver->media_type())
1268 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001269 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001270 transceiver->internal()->set_direction(
1271 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001272 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001273 transceiver->internal()->set_direction(
1274 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001275 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001276 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001277 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001278 } else {
1279 cricket::MediaType media_type =
1280 (track->kind() == MediaStreamTrackInterface::kAudioKind
1281 ? cricket::MEDIA_TYPE_AUDIO
1282 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001283 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1284 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001285 std::string sender_id = track->id();
1286 // Avoid creating a sender with an existing ID by generating a random ID.
1287 // This can happen if this is the second time AddTrack has created a sender
1288 // for this track.
1289 if (FindSenderById(sender_id)) {
1290 sender_id = rtc::CreateRandomUuid();
1291 }
Florent Castelli892acf02018-10-01 22:47:20 +02001292 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001293 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1294 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001295 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001296 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001297 }
Steve Antonf9381f02017-12-14 10:23:57 -08001298 return transceiver->sender();
1299}
1300
1301rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1302PeerConnection::FindFirstTransceiverForAddedTrack(
1303 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1304 RTC_DCHECK(track);
1305 for (auto transceiver : transceivers_) {
1306 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001307 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001308 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001309 !transceiver->internal()->has_ever_been_used_to_send() &&
1310 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001311 return transceiver;
1312 }
1313 }
1314 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001315}
1316
1317bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1318 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001319 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001320}
1321
Steve Anton24db5732018-07-23 10:27:33 -07001322RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001323 rtc::scoped_refptr<RtpSenderInterface> sender) {
1324 if (!sender) {
1325 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1326 }
deadbeefe1f9d832016-01-14 15:35:42 -08001327 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001328 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1329 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001330 }
Steve Antonf9381f02017-12-14 10:23:57 -08001331 if (IsUnifiedPlan()) {
1332 auto transceiver = FindTransceiverBySender(sender);
1333 if (!transceiver || !sender->track()) {
1334 return RTCError::OK();
1335 }
1336 sender->SetTrack(nullptr);
1337 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001338 transceiver->internal()->set_direction(
1339 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001340 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001341 transceiver->internal()->set_direction(
1342 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001343 }
Steve Anton4171afb2017-11-20 10:20:22 -08001344 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001345 bool removed;
1346 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1347 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1348 } else {
1349 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1350 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1351 }
1352 if (!removed) {
1353 LOG_AND_RETURN_ERROR(
1354 RTCErrorType::INVALID_PARAMETER,
1355 "Couldn't find sender " + sender->id() + " to remove.");
1356 }
Steve Anton4171afb2017-11-20 10:20:22 -08001357 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001358 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001359 return RTCError::OK();
1360}
1361
1362rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1363PeerConnection::FindTransceiverBySender(
1364 rtc::scoped_refptr<RtpSenderInterface> sender) {
1365 for (auto transceiver : transceivers_) {
1366 if (transceiver->sender() == sender) {
1367 return transceiver;
1368 }
1369 }
1370 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001371}
1372
Steve Anton9158ef62017-11-27 13:01:52 -08001373RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1374PeerConnection::AddTransceiver(
1375 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1376 return AddTransceiver(track, RtpTransceiverInit());
1377}
1378
1379RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1380PeerConnection::AddTransceiver(
1381 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1382 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001383 RTC_CHECK(IsUnifiedPlan())
1384 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001385 if (!track) {
1386 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1387 }
1388 cricket::MediaType media_type;
1389 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1390 media_type = cricket::MEDIA_TYPE_AUDIO;
1391 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1392 media_type = cricket::MEDIA_TYPE_VIDEO;
1393 } else {
1394 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1395 "Track kind is not audio or video");
1396 }
1397 return AddTransceiver(media_type, track, init);
1398}
1399
1400RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1401PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1402 return AddTransceiver(media_type, RtpTransceiverInit());
1403}
1404
1405RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1406PeerConnection::AddTransceiver(cricket::MediaType media_type,
1407 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001408 RTC_CHECK(IsUnifiedPlan())
1409 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001410 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1411 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1412 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1413 "media type is not audio or video");
1414 }
1415 return AddTransceiver(media_type, nullptr, init);
1416}
1417
1418RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1419PeerConnection::AddTransceiver(
1420 cricket::MediaType media_type,
1421 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001422 const RtpTransceiverInit& init,
1423 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001424 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1425 media_type == cricket::MEDIA_TYPE_VIDEO));
1426 if (track) {
1427 RTC_DCHECK_EQ(media_type,
1428 (track->kind() == MediaStreamTrackInterface::kAudioKind
1429 ? cricket::MEDIA_TYPE_AUDIO
1430 : cricket::MEDIA_TYPE_VIDEO));
1431 }
1432
1433 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001434 if (init.send_encodings.size() > 1) {
1435 LOG_AND_RETURN_ERROR(
1436 RTCErrorType::UNSUPPORTED_PARAMETER,
1437 "Attempted to create an encoder with more than 1 encoding parameter.");
1438 }
1439
1440 for (const auto& encoding : init.send_encodings) {
1441 if (encoding.ssrc.has_value()) {
1442 LOG_AND_RETURN_ERROR(
1443 RTCErrorType::UNSUPPORTED_PARAMETER,
1444 "Attempted to set an unimplemented parameter of RtpParameters.");
1445 }
Florent Castelli806e06d2018-12-12 11:56:42 +01001446
1447 if (encoding.codec_payload_type.has_value()) {
1448 LOG_AND_RETURN_ERROR(
1449 RTCErrorType::INVALID_MODIFICATION,
1450 "Attempted to set a read-only value in RtpParameters.");
1451 }
Florent Castelli892acf02018-10-01 22:47:20 +02001452 }
1453
1454 RtpParameters parameters;
1455 parameters.encodings = init.send_encodings;
1456 if (UnimplementedRtpParameterHasValue(parameters)) {
1457 LOG_AND_RETURN_ERROR(
1458 RTCErrorType::UNSUPPORTED_PARAMETER,
1459 "Attempted to set an unimplemented parameter of RtpParameters.");
1460 }
Steve Anton9158ef62017-11-27 13:01:52 -08001461
Steve Anton3d954a62018-04-02 11:27:23 -07001462 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1463 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001464 // Set the sender ID equal to the track ID if the track is specified unless
1465 // that sender ID is already in use.
1466 std::string sender_id =
1467 (track && !FindSenderById(track->id()) ? track->id()
1468 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001469 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1470 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001471 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1472 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1473 transceiver->internal()->set_direction(init.direction);
1474
Steve Anton22da89f2018-01-25 13:58:07 -08001475 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001476 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001477 }
Steve Antonf9381f02017-12-14 10:23:57 -08001478
1479 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1480}
1481
Steve Anton02ee47c2018-01-10 16:26:06 -08001482rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1483PeerConnection::CreateSender(
1484 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001485 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001486 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001487 const std::vector<std::string>& stream_ids,
1488 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001489 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001490 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1491 RTC_DCHECK(!track ||
1492 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1493 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1494 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001495 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001496 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001497 } else {
1498 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1499 RTC_DCHECK(!track ||
1500 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1501 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001502 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001503 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001504 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001505 bool set_track_succeeded = sender->SetTrack(track);
1506 RTC_DCHECK(set_track_succeeded);
1507 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001508 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001509 return sender;
1510}
1511
1512rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1513PeerConnection::CreateReceiver(cricket::MediaType media_type,
1514 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001515 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1516 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001517 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001518 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001519 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1520 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001521 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001522 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001523 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001524 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001525 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1526 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001527 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001528 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001529 return receiver;
1530}
1531
1532rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1533PeerConnection::CreateAndAddTransceiver(
1534 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1535 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1536 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001537 // Ensure that the new sender does not have an ID that is already in use by
1538 // another sender.
1539 // Allow receiver IDs to conflict since those come from remote SDP (which
1540 // could be invalid, but should not cause a crash).
1541 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001542 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1543 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001544 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001545 transceiver->internal()->SignalNegotiationNeeded.connect(
1546 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001547 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001548}
1549
Steve Anton52d86772018-02-20 15:48:12 -08001550void PeerConnection::OnNegotiationNeeded() {
1551 RTC_DCHECK_RUN_ON(signaling_thread());
1552 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001553 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001554}
1555
deadbeeffac06552015-11-25 11:26:01 -08001556rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001557 const std::string& kind,
1558 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001559 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1560 "Plan SdpSemantics. Please use AddTransceiver "
1561 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001562 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001563 if (IsClosed()) {
1564 return nullptr;
1565 }
Steve Anton4171afb2017-11-20 10:20:22 -08001566
Seth Hampson5b4f0752018-04-02 16:31:36 -07001567 // Internally we need to have one stream with Plan B semantics, so we
1568 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001569 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001570 if (stream_id.empty()) {
1571 stream_ids.push_back(rtc::CreateRandomUuid());
1572 RTC_LOG(LS_INFO)
1573 << "No stream_id specified for sender. Generated stream ID: "
1574 << stream_ids[0];
1575 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001576 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001577 }
1578
Steve Anton4171afb2017-11-20 10:20:22 -08001579 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001580 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001581 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001582 auto* audio_sender = new AudioRtpSender(
1583 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001584 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001585 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001586 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001587 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001588 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001589 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001590 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001591 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001592 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001593 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001594 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001595 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001596 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001597 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001598 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001599 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001600
deadbeefe1f9d832016-01-14 15:35:42 -08001601 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001602}
1603
deadbeef70ab1a12015-09-28 16:53:55 -07001604std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1605 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001606 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001607 for (auto sender : GetSendersInternal()) {
1608 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001609 }
1610 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001611}
1612
Steve Anton4171afb2017-11-20 10:20:22 -08001613std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1614PeerConnection::GetSendersInternal() const {
1615 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1616 all_senders;
1617 for (auto transceiver : transceivers_) {
1618 auto senders = transceiver->internal()->senders();
1619 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1620 }
1621 return all_senders;
1622}
1623
deadbeef70ab1a12015-09-28 16:53:55 -07001624std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1625PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001626 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001627 for (const auto& receiver : GetReceiversInternal()) {
1628 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001629 }
1630 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001631}
1632
Steve Anton4171afb2017-11-20 10:20:22 -08001633std::vector<
1634 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1635PeerConnection::GetReceiversInternal() const {
1636 std::vector<
1637 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1638 all_receivers;
1639 for (auto transceiver : transceivers_) {
1640 auto receivers = transceiver->internal()->receivers();
1641 all_receivers.insert(all_receivers.end(), receivers.begin(),
1642 receivers.end());
1643 }
1644 return all_receivers;
1645}
1646
Steve Anton9158ef62017-11-27 13:01:52 -08001647std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1648PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001649 RTC_CHECK(IsUnifiedPlan())
1650 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001651 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1652 for (auto transceiver : transceivers_) {
1653 all_transceivers.push_back(transceiver);
1654 }
1655 return all_transceivers;
1656}
1657
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001658bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001659 MediaStreamTrackInterface* track,
1660 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001661 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001662 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001663 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001664 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001665 return false;
1666 }
1667
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001668 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001669 // The StatsCollector is used to tell if a track is valid because it may
1670 // remember tracks that the PeerConnection previously removed.
1671 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001672 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1673 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001674 return false;
1675 }
Steve Antonad182762018-09-05 20:22:40 +00001676 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1677 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001678 return true;
1679}
1680
hbos74e1a4f2016-09-15 23:33:01 -07001681void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001682 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001683 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001684 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001685 stats_collector_->GetStatsReport(callback);
1686}
1687
Henrik Boström1df1bf82018-03-20 13:24:20 +01001688void PeerConnection::GetStats(
1689 rtc::scoped_refptr<RtpSenderInterface> selector,
1690 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1691 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1692 RTC_DCHECK(callback);
1693 RTC_DCHECK(stats_collector_);
1694 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1695 if (selector) {
1696 for (const auto& proxy_transceiver : transceivers_) {
1697 for (const auto& proxy_sender :
1698 proxy_transceiver->internal()->senders()) {
1699 if (proxy_sender == selector) {
1700 internal_sender = proxy_sender->internal();
1701 break;
1702 }
1703 }
1704 if (internal_sender)
1705 break;
1706 }
1707 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001708 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001709 // belong to the PeerConnection (in Plan B, senders can be removed from the
1710 // PeerConnection). This means that "all the stats objects representing the
1711 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1712 // produces an empty stats report.
1713 stats_collector_->GetStatsReport(internal_sender, callback);
1714}
1715
1716void PeerConnection::GetStats(
1717 rtc::scoped_refptr<RtpReceiverInterface> selector,
1718 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1719 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1720 RTC_DCHECK(callback);
1721 RTC_DCHECK(stats_collector_);
1722 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1723 if (selector) {
1724 for (const auto& proxy_transceiver : transceivers_) {
1725 for (const auto& proxy_receiver :
1726 proxy_transceiver->internal()->receivers()) {
1727 if (proxy_receiver == selector) {
1728 internal_receiver = proxy_receiver->internal();
1729 break;
1730 }
1731 }
1732 if (internal_receiver)
1733 break;
1734 }
1735 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001736 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001737 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1738 // the PeerConnection). This means that "all the stats objects representing
1739 // the selector" is an empty set. Invoking GetStatsReport() with a null
1740 // selector produces an empty stats report.
1741 stats_collector_->GetStatsReport(internal_receiver, callback);
1742}
1743
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001744PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1745 return signaling_state_;
1746}
1747
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001748PeerConnectionInterface::IceConnectionState
1749PeerConnection::ice_connection_state() {
1750 return ice_connection_state_;
1751}
1752
Alex Loiko9289eda2018-11-23 16:18:59 +00001753PeerConnectionInterface::IceConnectionState
1754PeerConnection::standardized_ice_connection_state() {
1755 return standardized_ice_connection_state_;
1756}
1757
Jonas Olsson635474e2018-10-18 15:58:17 +02001758PeerConnectionInterface::PeerConnectionState
1759PeerConnection::peer_connection_state() {
1760 return connection_state_;
1761}
1762
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763PeerConnectionInterface::IceGatheringState
1764PeerConnection::ice_gathering_state() {
1765 return ice_gathering_state_;
1766}
1767
Yves Gerey665174f2018-06-19 15:03:05 +02001768rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001769 const std::string& label,
1770 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001771 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001772
deadbeefab9b2d12015-10-14 11:33:11 -07001773 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001774
kwibergd1fe2812016-04-27 06:47:29 -07001775 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001776 if (config) {
1777 internal_config.reset(new InternalDataChannelInit(*config));
1778 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001779 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001780 InternalCreateDataChannel(label, internal_config.get()));
1781 if (!channel.get()) {
1782 return nullptr;
1783 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001784
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001785 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1786 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001787 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001788 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001789 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001790 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001791 return DataChannelProxy::Create(signaling_thread(), channel.get());
1792}
1793
1794void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001795 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001796 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001797
nisse7ce109a2017-01-31 00:57:56 -08001798 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001799 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001800 return;
1801 }
deadbeefab9b2d12015-10-14 11:33:11 -07001802
Steve Anton8d3444d2017-10-20 15:30:51 -07001803 if (IsClosed()) {
1804 std::string error = "CreateOffer called when PeerConnection is closed.";
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_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001808 return;
1809 }
1810
zhihuang1c378ed2017-08-17 14:10:50 -07001811 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001812 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001813 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001814 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001815 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001816 return;
1817 }
1818
Steve Anton22da89f2018-01-25 13:58:07 -08001819 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1820 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1821 if (IsUnifiedPlan()) {
1822 RTCError error = HandleLegacyOfferOptions(options);
1823 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001824 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001825 return;
1826 }
1827 }
1828
zhihuang1c378ed2017-08-17 14:10:50 -07001829 cricket::MediaSessionOptions session_options;
1830 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001831 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001832}
1833
Steve Anton22da89f2018-01-25 13:58:07 -08001834RTCError PeerConnection::HandleLegacyOfferOptions(
1835 const RTCOfferAnswerOptions& options) {
1836 RTC_DCHECK(IsUnifiedPlan());
1837
1838 if (options.offer_to_receive_audio == 0) {
1839 RemoveRecvDirectionFromReceivingTransceiversOfType(
1840 cricket::MEDIA_TYPE_AUDIO);
1841 } else if (options.offer_to_receive_audio == 1) {
1842 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1843 } else if (options.offer_to_receive_audio > 1) {
1844 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1845 "offer_to_receive_audio > 1 is not supported.");
1846 }
1847
1848 if (options.offer_to_receive_video == 0) {
1849 RemoveRecvDirectionFromReceivingTransceiversOfType(
1850 cricket::MEDIA_TYPE_VIDEO);
1851 } else if (options.offer_to_receive_video == 1) {
1852 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1853 } else if (options.offer_to_receive_video > 1) {
1854 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1855 "offer_to_receive_video > 1 is not supported.");
1856 }
1857
1858 return RTCError::OK();
1859}
1860
1861void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1862 cricket::MediaType media_type) {
1863 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001864 RtpTransceiverDirection new_direction =
1865 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1866 if (new_direction != transceiver->direction()) {
1867 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1868 << " transceiver (MID="
1869 << transceiver->mid().value_or("<not set>") << ") from "
1870 << RtpTransceiverDirectionToString(
1871 transceiver->direction())
1872 << " to "
1873 << RtpTransceiverDirectionToString(new_direction)
1874 << " since CreateOffer specified offer_to_receive=0";
1875 transceiver->internal()->set_direction(new_direction);
1876 }
Steve Anton22da89f2018-01-25 13:58:07 -08001877 }
1878}
1879
1880void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1881 cricket::MediaType media_type) {
1882 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001883 RTC_LOG(LS_INFO)
1884 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1885 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001886 RtpTransceiverInit init;
1887 init.direction = RtpTransceiverDirection::kRecvOnly;
1888 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1889 }
1890}
1891
1892std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1893PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1894 std::vector<
1895 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1896 receiving_transceivers;
1897 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001898 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001899 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1900 receiving_transceivers.push_back(transceiver);
1901 }
1902 }
1903 return receiving_transceivers;
1904}
1905
htaa2a49d92016-03-04 02:51:39 -08001906void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1907 const RTCOfferAnswerOptions& options) {
1908 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001909 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001910 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001911 return;
1912 }
1913
Steve Antondffead82018-02-06 10:31:29 -08001914 if (!(signaling_state_ == kHaveRemoteOffer ||
1915 signaling_state_ == kHaveLocalPrAnswer)) {
1916 std::string error =
1917 "PeerConnection cannot create an answer in a state other than "
1918 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001919 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001920 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001921 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001922 return;
1923 }
1924
Steve Antondffead82018-02-06 10:31:29 -08001925 // The remote description should be set if we're in the right state.
1926 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001927
Steve Anton22da89f2018-01-25 13:58:07 -08001928 if (IsUnifiedPlan()) {
1929 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1930 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1931 "supported with Unified Plan semantics. Use the "
1932 "RtpTransceiver API instead.";
1933 }
1934 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1935 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1936 "supported with Unified Plan semantics. Use the "
1937 "RtpTransceiver API instead.";
1938 }
1939 }
1940
htaa2a49d92016-03-04 02:51:39 -08001941 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001942 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001943
Steve Antond25da372017-11-06 14:50:29 -08001944 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945}
1946
1947void PeerConnection::SetLocalDescription(
1948 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001949 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001950 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001951
Steve Anton80dd7b52018-02-16 17:08:42 -08001952 // The SetLocalDescription contract is that we take ownership of the session
1953 // description regardless of the outcome, so wrap it in a unique_ptr right
1954 // away. Ideally, SetLocalDescription's signature will be changed to take the
1955 // description as a unique_ptr argument to formalize this agreement.
1956 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1957
nisse7ce109a2017-01-31 00:57:56 -08001958 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001959 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960 return;
1961 }
Steve Anton8a006912017-12-04 15:25:56 -08001962
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001963 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001964 PostSetSessionDescriptionFailure(
1965 observer,
1966 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967 return;
1968 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001969
Steve Anton80dd7b52018-02-16 17:08:42 -08001970 // If a session error has occurred the PeerConnection is in a possibly
1971 // inconsistent state so fail right away.
1972 if (session_error() != SessionError::kNone) {
1973 std::string error_message = GetSessionErrorMsg();
1974 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001975 PostSetSessionDescriptionFailure(
1976 observer,
1977 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001978 return;
1979 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001980
Steve Anton80dd7b52018-02-16 17:08:42 -08001981 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1982 if (!error.ok()) {
1983 std::string error_message = GetSetDescriptionErrorMessage(
1984 cricket::CS_LOCAL, desc->GetType(), error);
1985 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001986 PostSetSessionDescriptionFailure(
1987 observer,
1988 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001989 return;
1990 }
1991
1992 // Grab the description type before moving ownership to ApplyLocalDescription,
1993 // which may destroy it before returning.
1994 const SdpType type = desc->GetType();
1995
1996 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001997 // |desc| may be destroyed at this point.
1998
1999 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002000 // If ApplyLocalDescription fails, the PeerConnection could be in an
2001 // inconsistent state, so act conservatively here and set the session error
2002 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2003 SetSessionError(SessionError::kContent, error.message());
2004 std::string error_message =
2005 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2006 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002007 PostSetSessionDescriptionFailure(
2008 observer,
2009 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002010 return;
2011 }
Steve Anton8a006912017-12-04 15:25:56 -08002012 RTC_DCHECK(local_description());
2013
2014 PostSetSessionDescriptionSuccess(observer);
2015
Steve Antonad182762018-09-05 20:22:40 +00002016 // MaybeStartGathering needs to be called after posting
2017 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2018 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002019 transport_controller_->MaybeStartGathering();
2020
Steve Antona3a92c22017-12-07 10:27:41 -08002021 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002022 // TODO(deadbeef): We already had to hop to the network thread for
2023 // MaybeStartGathering...
2024 network_thread()->Invoke<void>(
2025 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2026 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002027 // Make UMA notes about what was agreed to.
2028 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002029 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002030 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002031}
2032
2033RTCError PeerConnection::ApplyLocalDescription(
2034 std::unique_ptr<SessionDescriptionInterface> desc) {
2035 RTC_DCHECK_RUN_ON(signaling_thread());
2036 RTC_DCHECK(desc);
2037
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002038 // Update stats here so that we have the most recent stats for tracks and
2039 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002040 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002041
Steve Antondcc3c022017-12-22 16:02:54 -08002042 // Take a reference to the old local description since it's used below to
2043 // compare against the new local description. When setting the new local
2044 // description, grab ownership of the replaced session description in case it
2045 // is the same as |old_local_description|, to keep it alive for the duration
2046 // of the method.
2047 const SessionDescriptionInterface* old_local_description =
2048 local_description();
2049 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002050 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002051 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002052 replaced_local_description = pending_local_description_
2053 ? std::move(pending_local_description_)
2054 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002055 current_local_description_ = std::move(desc);
2056 pending_local_description_ = nullptr;
2057 current_remote_description_ = std::move(pending_remote_description_);
2058 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002059 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002060 pending_local_description_ = std::move(desc);
2061 }
2062 // The session description to apply now must be accessed by
2063 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002064 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002065
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002066 if (!is_caller_) {
2067 if (remote_description()) {
2068 // Remote description was applied first, so this PC is the callee.
2069 is_caller_ = false;
2070 } else {
2071 // Local description is applied first, so this PC is the caller.
2072 is_caller_ = true;
2073 }
2074 }
2075
Zhi Huange830e682018-03-30 10:48:35 -07002076 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2077 if (!error.ok()) {
2078 return error;
2079 }
2080
Steve Antondcc3c022017-12-22 16:02:54 -08002081 if (IsUnifiedPlan()) {
2082 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002083 cricket::CS_LOCAL, *local_description(), old_local_description,
2084 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002085 if (!error.ok()) {
2086 return error;
2087 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002088 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2089 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002090 for (auto transceiver : transceivers_) {
2091 const ContentInfo* content =
2092 FindMediaSectionForTransceiver(transceiver, local_description());
2093 if (!content) {
2094 continue;
2095 }
2096 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002097 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2098 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002099 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002100 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2101 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2102 // "recvonly", process the removal of a remote track for the media
2103 // description, given transceiver, removeList, and muteTracks.
2104 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2105 (transceiver->internal()->fired_direction() &&
2106 RtpTransceiverDirectionHasRecv(
2107 *transceiver->internal()->fired_direction()))) {
2108 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2109 &removed_streams);
2110 }
2111 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2112 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002113 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002114 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002115 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002116 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002117 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002118 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002119 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002120 }
2121 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002122 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002123 }
2124 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002125 // Media channels will be created only when offer is set. These may use new
2126 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002127 if (type == SdpType::kOffer) {
2128 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2129 // description is applied. Restore back to old description.
2130 RTCError error = CreateChannels(*local_description()->description());
2131 if (!error.ok()) {
2132 return error;
2133 }
2134 }
Steve Antondcc3c022017-12-22 16:02:54 -08002135 // Remove unused channels if MediaContentDescription is rejected.
2136 RemoveUnusedChannels(local_description()->description());
2137 }
Steve Anton8a006912017-12-04 15:25:56 -08002138
Zhi Huange830e682018-03-30 10:48:35 -07002139 error = UpdateSessionState(type, cricket::CS_LOCAL,
2140 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002141 if (!error.ok()) {
2142 return error;
2143 }
Steve Antondcc3c022017-12-22 16:02:54 -08002144
Steve Anton8a006912017-12-04 15:25:56 -08002145 if (remote_description()) {
2146 // Now that we have a local description, we can push down remote candidates.
2147 UseCandidatesInSessionDescription(remote_description());
2148 }
2149
2150 pending_ice_restarts_.clear();
2151 if (session_error() != SessionError::kNone) {
2152 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2153 }
2154
deadbeefab9b2d12015-10-14 11:33:11 -07002155 // If setting the description decided our SSL role, allocate any necessary
2156 // SCTP sids.
2157 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002158 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002159 AllocateSctpSids(role);
2160 }
2161
Steve Antond3679212018-01-17 17:41:02 -08002162 if (IsUnifiedPlan()) {
2163 for (auto transceiver : transceivers_) {
2164 const ContentInfo* content =
2165 FindMediaSectionForTransceiver(transceiver, local_description());
2166 if (!content) {
2167 continue;
2168 }
Steve Anton74255ff2018-01-24 18:32:57 -08002169 const auto& streams = content->media_description()->streams();
2170 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002171 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002172 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002173 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002174 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002175 } else {
2176 // 0 is a special value meaning "this sender has no associated send
2177 // stream". Need to call this so the sender won't attempt to configure
2178 // a no longer existing stream and run into DCHECKs in the lower
2179 // layers.
2180 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002181 }
2182 }
2183 } else {
2184 // Plan B semantics.
2185
Steve Antondcc3c022017-12-22 16:02:54 -08002186 // Update state and SSRC of local MediaStreams and DataChannels based on the
2187 // local session description.
2188 const cricket::ContentInfo* audio_content =
2189 GetFirstAudioContent(local_description()->description());
2190 if (audio_content) {
2191 if (audio_content->rejected) {
2192 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2193 } else {
2194 const cricket::AudioContentDescription* audio_desc =
2195 audio_content->media_description()->as_audio();
2196 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2197 }
deadbeeffaac4972015-11-12 15:33:07 -08002198 }
deadbeefab9b2d12015-10-14 11:33:11 -07002199
Steve Antondcc3c022017-12-22 16:02:54 -08002200 const cricket::ContentInfo* video_content =
2201 GetFirstVideoContent(local_description()->description());
2202 if (video_content) {
2203 if (video_content->rejected) {
2204 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2205 } else {
2206 const cricket::VideoContentDescription* video_desc =
2207 video_content->media_description()->as_video();
2208 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2209 }
deadbeeffaac4972015-11-12 15:33:07 -08002210 }
deadbeefab9b2d12015-10-14 11:33:11 -07002211 }
2212
2213 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002214 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002215 if (data_content) {
2216 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002217 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002218 if (rtc::starts_with(data_desc->protocol().data(),
2219 cricket::kMediaProtocolRtpPrefix)) {
2220 UpdateLocalRtpDataChannels(data_desc->streams());
2221 }
2222 }
2223
Steve Anton8a006912017-12-04 15:25:56 -08002224 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002225}
2226
2227void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002228 SetSessionDescriptionObserver* observer,
2229 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002230 SetRemoteDescription(
2231 std::unique_ptr<SessionDescriptionInterface>(desc),
2232 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2233 new SetRemoteDescriptionObserverAdapter(this, observer)));
2234}
2235
2236void PeerConnection::SetRemoteDescription(
2237 std::unique_ptr<SessionDescriptionInterface> desc,
2238 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002239 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002240
nisse7ce109a2017-01-31 00:57:56 -08002241 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002242 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002243 return;
2244 }
Steve Anton8a006912017-12-04 15:25:56 -08002245
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002247 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002248 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002249 return;
2250 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002251
Steve Anton80dd7b52018-02-16 17:08:42 -08002252 // If a session error has occurred the PeerConnection is in a possibly
2253 // inconsistent state so fail right away.
2254 if (session_error() != SessionError::kNone) {
2255 std::string error_message = GetSessionErrorMsg();
2256 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2257 observer->OnSetRemoteDescriptionComplete(
2258 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2259 return;
2260 }
Steve Anton71439a62018-02-15 11:53:06 -08002261
Steve Antonba42e992018-04-09 14:10:01 -07002262 if (desc->GetType() == SdpType::kOffer) {
2263 // Report to UMA the format of the received offer.
2264 ReportSdpFormatReceived(*desc);
2265 }
2266
Steve Anton80dd7b52018-02-16 17:08:42 -08002267 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002268 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002269 std::string error_message = GetSetDescriptionErrorMessage(
2270 cricket::CS_REMOTE, desc->GetType(), error);
2271 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002272 observer->OnSetRemoteDescriptionComplete(
2273 RTCError(error.type(), std::move(error_message)));
2274 return;
2275 }
Steve Anton71439a62018-02-15 11:53:06 -08002276
Steve Anton80dd7b52018-02-16 17:08:42 -08002277 // Grab the description type before moving ownership to
2278 // ApplyRemoteDescription, which may destroy it before returning.
2279 const SdpType type = desc->GetType();
2280
2281 error = ApplyRemoteDescription(std::move(desc));
2282 // |desc| may be destroyed at this point.
2283
2284 if (!error.ok()) {
2285 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2286 // inconsistent state, so act conservatively here and set the session error
2287 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2288 SetSessionError(SessionError::kContent, error.message());
2289 std::string error_message =
2290 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2291 RTC_LOG(LS_ERROR) << error_message;
2292 observer->OnSetRemoteDescriptionComplete(
2293 RTCError(error.type(), std::move(error_message)));
2294 return;
2295 }
2296 RTC_DCHECK(remote_description());
2297
2298 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002299 // TODO(deadbeef): We already had to hop to the network thread for
2300 // MaybeStartGathering...
2301 network_thread()->Invoke<void>(
2302 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2303 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002304 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002305 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002306 }
2307
2308 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002309 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002310}
2311
2312RTCError PeerConnection::ApplyRemoteDescription(
2313 std::unique_ptr<SessionDescriptionInterface> desc) {
2314 RTC_DCHECK_RUN_ON(signaling_thread());
2315 RTC_DCHECK(desc);
2316
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002317 // Update stats here so that we have the most recent stats for tracks and
2318 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002319 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002320
Steve Antondcc3c022017-12-22 16:02:54 -08002321 // Take a reference to the old remote description since it's used below to
2322 // compare against the new remote description. When setting the new remote
2323 // description, grab ownership of the replaced session description in case it
2324 // is the same as |old_remote_description|, to keep it alive for the duration
2325 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002326 const SessionDescriptionInterface* old_remote_description =
2327 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002328 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002329 SdpType type = desc->GetType();
2330 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002331 replaced_remote_description = pending_remote_description_
2332 ? std::move(pending_remote_description_)
2333 : std::move(current_remote_description_);
2334 current_remote_description_ = std::move(desc);
2335 pending_remote_description_ = nullptr;
2336 current_local_description_ = std::move(pending_local_description_);
2337 } else {
2338 replaced_remote_description = std::move(pending_remote_description_);
2339 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002340 }
Steve Anton8a006912017-12-04 15:25:56 -08002341 // The session description to apply now must be accessed by
2342 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002343 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002344
Zhi Huange830e682018-03-30 10:48:35 -07002345 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2346 if (!error.ok()) {
2347 return error;
2348 }
Steve Anton8a006912017-12-04 15:25:56 -08002349 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002350 if (IsUnifiedPlan()) {
2351 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002352 cricket::CS_REMOTE, *remote_description(), local_description(),
2353 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002354 if (!error.ok()) {
2355 return error;
2356 }
Steve Antondcc3c022017-12-22 16:02:54 -08002357 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002358 // Media channels will be created only when offer is set. These may use new
2359 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002360 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002361 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002362 // description is applied. Restore back to old description.
2363 RTCError error = CreateChannels(*remote_description()->description());
2364 if (!error.ok()) {
2365 return error;
2366 }
2367 }
Steve Antondcc3c022017-12-22 16:02:54 -08002368 // Remove unused channels if MediaContentDescription is rejected.
2369 RemoveUnusedChannels(remote_description()->description());
2370 }
Steve Anton8a006912017-12-04 15:25:56 -08002371
Zhi Huange830e682018-03-30 10:48:35 -07002372 // NOTE: Candidates allocation will be initiated only when
2373 // SetLocalDescription is called.
2374 error = UpdateSessionState(type, cricket::CS_REMOTE,
2375 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002376 if (!error.ok()) {
2377 return error;
2378 }
2379
2380 if (local_description() &&
2381 !UseCandidatesInSessionDescription(remote_description())) {
2382 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2383 }
2384
2385 if (old_remote_description) {
2386 for (const cricket::ContentInfo& content :
2387 old_remote_description->description()->contents()) {
2388 // Check if this new SessionDescription contains new ICE ufrag and
2389 // password that indicates the remote peer requests an ICE restart.
2390 // TODO(deadbeef): When we start storing both the current and pending
2391 // remote description, this should reset pending_ice_restarts and compare
2392 // against the current description.
2393 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2394 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002395 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002396 pending_ice_restarts_.insert(content.name);
2397 }
2398 } else {
2399 // We retain all received candidates only if ICE is not restarted.
2400 // When ICE is restarted, all previous candidates belong to an old
2401 // generation and should not be kept.
2402 // TODO(deadbeef): This goes against the W3C spec which says the remote
2403 // description should only contain candidates from the last set remote
2404 // description plus any candidates added since then. We should remove
2405 // this once we're sure it won't break anything.
2406 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2407 old_remote_description, content.name, mutable_remote_description());
2408 }
2409 }
2410 }
2411
2412 if (session_error() != SessionError::kNone) {
2413 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2414 }
2415
2416 // Set the the ICE connection state to connecting since the connection may
2417 // become writable with peer reflexive candidates before any remote candidate
2418 // is signaled.
2419 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2420 // is to have a new signal the indicates a change in checking state from the
2421 // transport and expose a new checking() member from transport that can be
2422 // read to determine the current checking state. The existing SignalConnecting
2423 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002424 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002425 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002426 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2427 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2428 }
2429
deadbeefab9b2d12015-10-14 11:33:11 -07002430 // If setting the description decided our SSL role, allocate any necessary
2431 // SCTP sids.
2432 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002433 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002434 AllocateSctpSids(role);
2435 }
2436
Steve Antondcc3c022017-12-22 16:02:54 -08002437 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002438 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002439 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002440 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002441 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002442 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002443 for (auto transceiver : transceivers_) {
2444 const ContentInfo* content =
2445 FindMediaSectionForTransceiver(transceiver, remote_description());
2446 if (!content) {
2447 continue;
2448 }
2449 const MediaContentDescription* media_desc = content->media_description();
2450 RtpTransceiverDirection local_direction =
2451 RtpTransceiverDirectionReversed(media_desc->direction());
2452 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2453 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2454 // transceiver's current direction is neither sendrecv nor recvonly,
2455 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002456 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002457 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002458 // The remote description has signaled the stream IDs.
2459 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002460 }
Steve Antondcc3c022017-12-22 16:02:54 -08002461 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002462 (!transceiver->fired_direction() ||
2463 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002464 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002465 << content->name << " (added to "
2466 << GetStreamIdsString(stream_ids) << ").";
2467
2468 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2469 for (const std::string& stream_id : stream_ids) {
2470 rtc::scoped_refptr<MediaStreamInterface> stream =
2471 remote_streams_->find(stream_id);
2472 if (!stream) {
2473 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2474 MediaStream::Create(stream_id));
2475 remote_streams_->AddStream(stream);
2476 added_streams.push_back(stream);
2477 }
2478 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002479 }
Henrik Boström5b147782018-12-04 11:25:05 +01002480 // Special case: "a=msid" missing, use random stream ID.
2481 if (media_streams.empty() &&
2482 !(remote_description()->description()->msid_signaling() &
2483 cricket::kMsidSignalingMediaSection)) {
2484 if (!missing_msid_default_stream_) {
2485 missing_msid_default_stream_ = MediaStreamProxy::Create(
2486 rtc::Thread::Current(),
2487 MediaStream::Create(rtc::CreateRandomUuid()));
2488 added_streams.push_back(missing_msid_default_stream_);
2489 }
2490 media_streams.push_back(missing_msid_default_stream_);
2491 }
Steve Anton3172c032018-05-03 15:30:18 -07002492 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002493 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2494 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002495 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002496 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002497 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002498 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2499 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2500 // removal of a remote track for the media description, given transceiver,
2501 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002502 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002503 (transceiver->fired_direction() &&
2504 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2505 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2506 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002507 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002508 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2509 transceiver->internal()->set_fired_direction(local_direction);
2510 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2511 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002512 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002513 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2514 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002515 transceiver->internal()->set_current_direction(local_direction);
2516 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002517 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2518 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002519 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002520 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2521 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002522 transceiver->Stop();
2523 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002524 if (!content->rejected &&
2525 RtpTransceiverDirectionHasRecv(local_direction)) {
2526 // Set ssrc to 0 in the case of an unsignalled ssrc.
2527 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002528 if (!media_desc->streams().empty() &&
2529 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002530 ssrc = media_desc->streams()[0].first_ssrc();
2531 }
2532 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002533 }
Steve Antondcc3c022017-12-22 16:02:54 -08002534 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002535 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002536 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002537 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002538 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002539 observer->OnTrack(transceiver);
2540 observer->OnAddTrack(transceiver->receiver(),
2541 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002542 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002543 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002544 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002545 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002546 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002547 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002548 }
2549 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002550 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002551 }
Steve Antondcc3c022017-12-22 16:02:54 -08002552 }
2553
Henrik Boströmfdb92012017-11-09 19:55:44 +01002554 const cricket::ContentInfo* audio_content =
2555 GetFirstAudioContent(remote_description()->description());
2556 const cricket::ContentInfo* video_content =
2557 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002558 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002559 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002560 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002561 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002562 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002563 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002564
2565 // Check if the descriptions include streams, just in case the peer supports
2566 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002567 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002568 (audio_desc && !audio_desc->streams().empty()) ||
2569 (video_desc && !video_desc->streams().empty())) {
2570 remote_peer_supports_msid_ = true;
2571 }
deadbeefab9b2d12015-10-14 11:33:11 -07002572
2573 // We wait to signal new streams until we finish processing the description,
2574 // since only at that point will new streams have all their tracks.
2575 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2576
Steve Antondcc3c022017-12-22 16:02:54 -08002577 if (!IsUnifiedPlan()) {
2578 // TODO(steveanton): When removing RTP senders/receivers in response to a
2579 // rejected media section, there is some cleanup logic that expects the
2580 // voice/ video channel to still be set. But in this method the voice/video
2581 // channel would have been destroyed by the SetRemoteDescription caller
2582 // above so the cleanup that relies on them fails to run. The RemoveSenders
2583 // calls should be moved to right before the DestroyChannel calls to fix
2584 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002585
Steve Antondcc3c022017-12-22 16:02:54 -08002586 // Find all audio rtp streams and create corresponding remote AudioTracks
2587 // and MediaStreams.
2588 if (audio_content) {
2589 if (audio_content->rejected) {
2590 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2591 } else {
2592 bool default_audio_track_needed =
2593 !remote_peer_supports_msid_ &&
2594 RtpTransceiverDirectionHasSend(audio_desc->direction());
2595 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2596 default_audio_track_needed, audio_desc->type(),
2597 new_streams);
2598 }
deadbeeffaac4972015-11-12 15:33:07 -08002599 }
deadbeefab9b2d12015-10-14 11:33:11 -07002600
Steve Antondcc3c022017-12-22 16:02:54 -08002601 // Find all video rtp streams and create corresponding remote VideoTracks
2602 // and MediaStreams.
2603 if (video_content) {
2604 if (video_content->rejected) {
2605 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2606 } else {
2607 bool default_video_track_needed =
2608 !remote_peer_supports_msid_ &&
2609 RtpTransceiverDirectionHasSend(video_desc->direction());
2610 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2611 default_video_track_needed, video_desc->type(),
2612 new_streams);
2613 }
deadbeeffaac4972015-11-12 15:33:07 -08002614 }
deadbeefab9b2d12015-10-14 11:33:11 -07002615
Steve Antondcc3c022017-12-22 16:02:54 -08002616 // Update the DataChannels with the information from the remote peer.
2617 if (data_desc) {
2618 if (rtc::starts_with(data_desc->protocol().data(),
2619 cricket::kMediaProtocolRtpPrefix)) {
2620 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2621 }
deadbeefab9b2d12015-10-14 11:33:11 -07002622 }
deadbeefab9b2d12015-10-14 11:33:11 -07002623
Steve Antondcc3c022017-12-22 16:02:54 -08002624 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002625 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002626 for (size_t i = 0; i < new_streams->count(); ++i) {
2627 MediaStreamInterface* new_stream = new_streams->at(i);
2628 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002629 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002630 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2631 }
deadbeefab9b2d12015-10-14 11:33:11 -07002632
Steve Antondcc3c022017-12-22 16:02:54 -08002633 UpdateEndedRemoteMediaStreams();
2634 }
deadbeefab9b2d12015-10-14 11:33:11 -07002635
Steve Anton8a006912017-12-04 15:25:56 -08002636 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002637}
2638
Steve Anton0f5400a2018-07-17 14:25:36 -07002639void PeerConnection::ProcessRemovalOfRemoteTrack(
2640 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2641 transceiver,
2642 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2643 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2644 RTC_DCHECK(transceiver->mid());
2645 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2646 << *transceiver->mid();
2647 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2648 transceiver->internal()->receiver_internal()->streams();
2649 // This will remove the remote track from the streams.
2650 transceiver->internal()->receiver_internal()->set_stream_ids({});
2651 remove_list->push_back(transceiver);
2652 // Remove any streams that no longer have tracks.
2653 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2654 // of streams, see if the stream was removed by checking if this was the
2655 // last receiver with that stream ID.
2656 for (auto stream : media_streams) {
2657 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2658 remote_streams_->RemoveStream(stream);
2659 removed_streams->push_back(stream);
2660 }
2661 }
2662}
2663
Steve Antondcc3c022017-12-22 16:02:54 -08002664RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2665 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002666 const SessionDescriptionInterface& new_session,
2667 const SessionDescriptionInterface* old_local_description,
2668 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002669 RTC_DCHECK(IsUnifiedPlan());
2670
Steve Anton7464fca2018-01-19 11:10:37 -08002671 const cricket::ContentGroup* bundle_group = nullptr;
2672 if (new_session.GetType() == SdpType::kOffer) {
2673 auto bundle_group_or_error =
2674 GetEarlyBundleGroup(*new_session.description());
2675 if (!bundle_group_or_error.ok()) {
2676 return bundle_group_or_error.MoveError();
2677 }
2678 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002679 }
Steve Antondcc3c022017-12-22 16:02:54 -08002680
Steve Antondcc3c022017-12-22 16:02:54 -08002681 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002682 for (size_t i = 0; i < new_contents.size(); ++i) {
2683 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002684 cricket::MediaType media_type = new_content.media_description()->type();
2685 seen_mids_.insert(new_content.name);
2686 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2687 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002688 const cricket::ContentInfo* old_local_content = nullptr;
2689 if (old_local_description &&
2690 i < old_local_description->description()->contents().size()) {
2691 old_local_content =
2692 &old_local_description->description()->contents()[i];
2693 }
2694 const cricket::ContentInfo* old_remote_content = nullptr;
2695 if (old_remote_description &&
2696 i < old_remote_description->description()->contents().size()) {
2697 old_remote_content =
2698 &old_remote_description->description()->contents()[i];
2699 }
Steve Antondcc3c022017-12-22 16:02:54 -08002700 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002701 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2702 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002703 if (!transceiver_or_error.ok()) {
2704 return transceiver_or_error.MoveError();
2705 }
2706 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002707 RTCError error =
2708 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2709 if (!error.ok()) {
2710 return error;
2711 }
2712 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002713 if (GetDataMid() && new_content.name != *GetDataMid()) {
2714 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002715 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2716 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002717 continue;
2718 }
2719 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2720 if (!error.ok()) {
2721 return error;
2722 }
Steve Antondcc3c022017-12-22 16:02:54 -08002723 } else {
2724 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2725 "Unknown section type.");
2726 }
2727 }
2728
2729 return RTCError::OK();
2730}
2731
2732RTCError PeerConnection::UpdateTransceiverChannel(
2733 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2734 transceiver,
2735 const cricket::ContentInfo& content,
2736 const cricket::ContentGroup* bundle_group) {
2737 RTC_DCHECK(IsUnifiedPlan());
2738 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002739 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002740 if (content.rejected) {
2741 if (channel) {
2742 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002743 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002744 }
2745 } else {
2746 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002747 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002748 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002749 } else {
Steve Anton69470252018-02-09 11:43:08 -08002750 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002751 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002752 }
2753 if (!channel) {
2754 LOG_AND_RETURN_ERROR(
2755 RTCErrorType::INTERNAL_ERROR,
2756 "Failed to create channel for mid=" + content.name);
2757 }
2758 transceiver->internal()->SetChannel(channel);
2759 }
2760 }
2761 return RTCError::OK();
2762}
2763
Steve Antonfa2260d2017-12-28 16:38:23 -08002764RTCError PeerConnection::UpdateDataChannel(
2765 cricket::ContentSource source,
2766 const cricket::ContentInfo& content,
2767 const cricket::ContentGroup* bundle_group) {
2768 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002769 // If data channels are disabled, ignore this media section. CreateAnswer
2770 // will take care of rejecting it.
2771 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002772 }
2773 if (content.rejected) {
2774 DestroyDataChannel();
2775 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002776 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002777 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002778 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2779 "Failed to create data channel.");
2780 }
2781 }
2782 if (source == cricket::CS_REMOTE) {
2783 const MediaContentDescription* data_desc = content.media_description();
2784 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2785 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2786 }
2787 }
2788 }
2789 return RTCError::OK();
2790}
2791
Steve Antondcc3c022017-12-22 16:02:54 -08002792RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2793PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002794 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002795 size_t mline_index,
2796 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002797 const ContentInfo* old_local_content,
2798 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002799 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002800 // If this is an offer then the m= section might be recycled. If the m=
2801 // section is being recycled (defined as: rejected in the current local or
2802 // remote description and not rejected in new description), dissociate the
2803 // currently associated RtpTransceiver by setting its mid property to null,
2804 // and discard the mapping between the transceiver and its m= section index.
2805 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2806 old_remote_content)) {
2807 // We want to dissociate the transceiver that has the rejected mid.
2808 const std::string& old_mid =
2809 (old_local_content && old_local_content->rejected)
2810 ? old_local_content->name
2811 : old_remote_content->name;
2812 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002813 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002814 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2815 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002816 old_transceiver->internal()->set_mid(absl::nullopt);
2817 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002818 }
2819 }
2820 const MediaContentDescription* media_desc = content.media_description();
2821 auto transceiver = GetAssociatedTransceiver(content.name);
2822 if (source == cricket::CS_LOCAL) {
2823 // Find the RtpTransceiver that corresponds to this m= section, using the
2824 // mapping between transceivers and m= section indices established when
2825 // creating the offer.
2826 if (!transceiver) {
2827 transceiver = GetTransceiverByMLineIndex(mline_index);
2828 }
2829 if (!transceiver) {
2830 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2831 "Unknown transceiver");
2832 }
2833 } else {
2834 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2835 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2836 // of the same type...
2837 if (!transceiver &&
2838 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2839 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2840 }
2841 // If no RtpTransceiver was found in the previous step, create one with a
2842 // recvonly direction.
2843 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002844 RTC_LOG(LS_INFO) << "Adding "
2845 << cricket::MediaTypeToString(media_desc->type())
2846 << " transceiver for MID=" << content.name
2847 << " at i=" << mline_index
2848 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002849 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002850 auto sender =
2851 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002852 std::string receiver_id;
2853 if (!media_desc->streams().empty()) {
2854 receiver_id = media_desc->streams()[0].id;
2855 } else {
2856 receiver_id = rtc::CreateRandomUuid();
2857 }
2858 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002859 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002860 transceiver->internal()->set_direction(
2861 RtpTransceiverDirection::kRecvOnly);
2862 }
2863 }
2864 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002865 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002866 LOG_AND_RETURN_ERROR(
2867 RTCErrorType::INVALID_PARAMETER,
2868 "Transceiver type does not match media description type.");
2869 }
2870 // Associate the found or created RtpTransceiver with the m= section by
2871 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2872 // section, and establish a mapping between the transceiver and the index of
2873 // the m= section.
2874 transceiver->internal()->set_mid(content.name);
2875 transceiver->internal()->set_mline_index(mline_index);
2876 return std::move(transceiver);
2877}
2878
2879rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2880PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2881 RTC_DCHECK(IsUnifiedPlan());
2882 for (auto transceiver : transceivers_) {
2883 if (transceiver->mid() == mid) {
2884 return transceiver;
2885 }
2886 }
2887 return nullptr;
2888}
2889
2890rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2891PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2892 RTC_DCHECK(IsUnifiedPlan());
2893 for (auto transceiver : transceivers_) {
2894 if (transceiver->internal()->mline_index() == mline_index) {
2895 return transceiver;
2896 }
2897 }
2898 return nullptr;
2899}
2900
2901rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2902PeerConnection::FindAvailableTransceiverToReceive(
2903 cricket::MediaType media_type) const {
2904 RTC_DCHECK(IsUnifiedPlan());
2905 // From JSEP section 5.10 (Applying a Remote Description):
2906 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2907 // the same type that were added to the PeerConnection by addTrack and are not
2908 // associated with any m= section and are not stopped, find the first such
2909 // RtpTransceiver.
2910 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002911 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002912 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2913 !transceiver->stopped()) {
2914 return transceiver;
2915 }
2916 }
2917 return nullptr;
2918}
2919
Steve Antoned10bd92017-12-05 10:52:59 -08002920const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2921 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2922 transceiver,
2923 const SessionDescriptionInterface* sdesc) const {
2924 RTC_DCHECK(transceiver);
2925 RTC_DCHECK(sdesc);
2926 if (IsUnifiedPlan()) {
2927 if (!transceiver->internal()->mid()) {
2928 // This transceiver is not associated with a media section yet.
2929 return nullptr;
2930 }
2931 return sdesc->description()->GetContentByName(
2932 *transceiver->internal()->mid());
2933 } else {
2934 // Plan B only allows at most one audio and one video section, so use the
2935 // first media section of that type.
2936 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002937 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002938 }
2939}
2940
deadbeef46c73892016-11-16 19:42:04 -08002941PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2942 return configuration_;
2943}
2944
deadbeef293e9262017-01-11 12:28:30 -08002945bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2946 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002947 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002948 if (IsClosed()) {
2949 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2950 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2951 }
2952
Qingsi Wanga2d60672018-04-11 16:57:45 -07002953 // According to JSEP, after setLocalDescription, changing the candidate pool
2954 // size is not allowed, and changing the set of ICE servers will not result
2955 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002956 if (local_description() && configuration.ice_candidate_pool_size !=
2957 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002958 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2959 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002960 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002961 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002962
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002963 if (local_description() &&
2964 configuration.use_media_transport != configuration_.use_media_transport) {
2965 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2966 "SetLocalDescription.";
2967 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2968 }
2969
2970 if (remote_description() &&
2971 configuration.use_media_transport != configuration_.use_media_transport) {
2972 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2973 "SetRemoteDescription.";
2974 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2975 }
2976
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002977 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002978 configuration.use_media_transport_for_data_channels !=
2979 configuration_.use_media_transport_for_data_channels) {
2980 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2981 "after calling SetLocalDescription.";
2982 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2983 }
2984
2985 if (remote_description() &&
2986 configuration.use_media_transport_for_data_channels !=
2987 configuration_.use_media_transport_for_data_channels) {
2988 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2989 "after calling SetRemoteDescription.";
2990 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2991 }
2992
2993 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002994 configuration.crypto_options != configuration_.crypto_options) {
2995 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2996 "SetLocalDescription.";
2997 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2998 }
2999
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003000 if (configuration.use_media_transport_for_data_channels ||
3001 configuration.use_media_transport) {
3002 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3003 << "Media transport requires MaxBundle policy.";
3004 }
3005
deadbeef293e9262017-01-11 12:28:30 -08003006 // The simplest (and most future-compatible) way to tell if the config was
3007 // modified in an invalid way is to copy each property we do support
3008 // modifying, then use operator==. There are far more properties we don't
3009 // support modifying than those we do, and more could be added.
3010 RTCConfiguration modified_config = configuration_;
3011 modified_config.servers = configuration.servers;
3012 modified_config.type = configuration.type;
3013 modified_config.ice_candidate_pool_size =
3014 configuration.ice_candidate_pool_size;
3015 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003016 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003017 modified_config.ice_check_interval_strong_connectivity =
3018 configuration.ice_check_interval_strong_connectivity;
3019 modified_config.ice_check_interval_weak_connectivity =
3020 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003021 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3022 modified_config.ice_unwritable_min_checks =
3023 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003024 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003025 modified_config.stun_candidate_keepalive_interval =
3026 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003027 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003028 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003029 modified_config.active_reset_srtp_params =
3030 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003031 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003032 modified_config.use_media_transport_for_data_channels =
3033 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003034 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003035 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003036 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3037 }
3038
Steve Anton038834f2017-07-14 15:59:59 -07003039 // Validate the modified configuration.
3040 RTCError validate_error = ValidateConfiguration(modified_config);
3041 if (!validate_error.ok()) {
3042 return SafeSetError(std::move(validate_error), error);
3043 }
3044
deadbeef293e9262017-01-11 12:28:30 -08003045 // Note that this isn't possible through chromium, since it's an unsigned
3046 // short in WebIDL.
3047 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003048 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003049 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3050 }
3051
3052 // Parse ICE servers before hopping to network thread.
3053 cricket::ServerAddresses stun_servers;
3054 std::vector<cricket::RelayServerConfig> turn_servers;
3055 RTCErrorType parse_error =
3056 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3057 if (parse_error != RTCErrorType::NONE) {
3058 return SafeSetError(parse_error, error);
3059 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003060 // Note if STUN or TURN servers were supplied.
3061 if (!stun_servers.empty()) {
3062 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3063 }
3064 if (!turn_servers.empty()) {
3065 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3066 }
deadbeef293e9262017-01-11 12:28:30 -08003067
3068 // In theory this shouldn't fail.
3069 if (!network_thread()->Invoke<bool>(
3070 RTC_FROM_HERE,
3071 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3072 stun_servers, turn_servers, modified_config.type,
3073 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003074 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003075 modified_config.turn_customizer,
3076 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003077 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003078 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3079 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003080
deadbeefd1a38b52016-12-10 13:15:33 -08003081 // As described in JSEP, calling setConfiguration with new ICE servers or
3082 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3083 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003084 if (modified_config.servers != configuration_.servers ||
3085 modified_config.type != configuration_.type ||
3086 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003087 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003088 }
skvladd1f5fda2017-02-03 16:54:05 -08003089
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003090 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003091 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003092 modified_config.use_media_transport ||
3093 modified_config.use_media_transport_for_data_channels
3094 ? factory_->media_transport_factory()
3095 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003096
Zhi Huangb57e1692018-06-12 11:41:11 -07003097 if (configuration_.active_reset_srtp_params !=
3098 modified_config.active_reset_srtp_params) {
3099 transport_controller_->SetActiveResetSrtpParams(
3100 modified_config.active_reset_srtp_params);
3101 }
3102
deadbeef293e9262017-01-11 12:28:30 -08003103 configuration_ = modified_config;
3104 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003105}
3106
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003107bool PeerConnection::AddIceCandidate(
3108 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003109 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003110 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003111 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003112 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003113 return false;
3114 }
Steve Antond25da372017-11-06 14:50:29 -08003115
3116 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003117 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003118 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003119 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003120 return false;
3121 }
3122
3123 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003124 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003125 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003126 return false;
3127 }
3128
3129 bool valid = false;
3130 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3131 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003132 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003133 return false;
3134 }
3135
3136 // Add this candidate to the remote session description.
3137 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003138 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003139 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003140 return false;
3141 }
3142
3143 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003144 bool result = UseCandidate(ice_candidate);
3145 if (result) {
3146 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3147 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3148 } else {
3149 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3150 }
3151 return result;
Steve Antond25da372017-11-06 14:50:29 -08003152 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003153 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003154 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003155 return true;
3156 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003157}
3158
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003159bool PeerConnection::RemoveIceCandidates(
3160 const std::vector<cricket::Candidate>& candidates) {
3161 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003162 if (IsClosed()) {
3163 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3164 return false;
3165 }
3166
Steve Antond25da372017-11-06 14:50:29 -08003167 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003168 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3169 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003170 return false;
3171 }
3172
3173 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003174 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003175 return false;
3176 }
3177
3178 size_t number_removed =
3179 mutable_remote_description()->RemoveCandidates(candidates);
3180 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003181 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003182 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003183 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003184 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003185 }
3186
3187 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003188 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3189 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003190 RTC_LOG(LS_ERROR)
3191 << "RemoveIceCandidates: Error when removing remote candidates: "
3192 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003193 }
3194 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003195}
3196
Niels Möller0c4f7be2018-05-07 14:01:37 +02003197RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003198 if (!worker_thread()->IsCurrent()) {
3199 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003200 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003201 }
3202
Niels Möller0c4f7be2018-05-07 14:01:37 +02003203 const bool has_min = bitrate.min_bitrate_bps.has_value();
3204 const bool has_start = bitrate.start_bitrate_bps.has_value();
3205 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003206 if (has_min && *bitrate.min_bitrate_bps < 0) {
3207 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3208 "min_bitrate_bps <= 0");
3209 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003210 if (has_start) {
3211 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_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 "start_bitrate_bps < min_bitrate_bps");
3214 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3216 "curent_bitrate_bps < 0");
3217 }
3218 }
3219 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003220 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003221 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003222 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003223 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3224 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3225 "max_bitrate_bps < min_bitrate_bps");
3226 } else if (*bitrate.max_bitrate_bps < 0) {
3227 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3228 "max_bitrate_bps < 0");
3229 }
3230 }
3231
zstein4b979802017-06-02 14:37:37 -07003232 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003233 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003234
3235 return RTCError::OK();
3236}
3237
Alex Narest78609d52017-10-20 10:37:47 +02003238void PeerConnection::SetBitrateAllocationStrategy(
3239 std::unique_ptr<rtc::BitrateAllocationStrategy>
3240 bitrate_allocation_strategy) {
3241 rtc::Thread* worker_thread = factory_->worker_thread();
3242 if (!worker_thread->IsCurrent()) {
3243 rtc::BitrateAllocationStrategy* strategy_raw =
3244 bitrate_allocation_strategy.release();
3245 auto functor = [this, strategy_raw]() {
3246 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003247 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003248 };
3249 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3250 return;
3251 }
3252 RTC_DCHECK(call_.get());
3253 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3254}
3255
henrika5f6bf242017-11-01 11:06:56 +01003256void PeerConnection::SetAudioPlayout(bool playout) {
3257 if (!worker_thread()->IsCurrent()) {
3258 worker_thread()->Invoke<void>(
3259 RTC_FROM_HERE,
3260 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3261 return;
3262 }
3263 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003264 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003265 audio_state->SetPlayout(playout);
3266}
3267
3268void PeerConnection::SetAudioRecording(bool recording) {
3269 if (!worker_thread()->IsCurrent()) {
3270 worker_thread()->Invoke<void>(
3271 RTC_FROM_HERE,
3272 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3273 return;
3274 }
3275 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003276 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003277 audio_state->SetRecording(recording);
3278}
3279
Steve Anton8c0f7a72017-10-03 10:03:10 -07003280std::unique_ptr<rtc::SSLCertificate>
3281PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003282 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3283 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003284 return nullptr;
3285 }
Steve Antonf25303e2018-10-16 15:23:31 -07003286 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003287}
3288
Zhi Huang70b820f2018-01-27 14:16:15 -08003289std::unique_ptr<rtc::SSLCertChain>
3290PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003291 auto audio_transceiver = GetFirstAudioTransceiver();
3292 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003293 return nullptr;
3294 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003295 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003296 audio_transceiver->internal()->channel()->transport_name());
3297}
3298
3299rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3300PeerConnection::GetFirstAudioTransceiver() const {
3301 for (auto transceiver : transceivers_) {
3302 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3303 return transceiver;
3304 }
3305 }
3306 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003307}
3308
ivoc14d5dbe2016-07-04 07:06:55 -07003309bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3310 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003311 // TODO(eladalon): It would be better to not allow negative values into PC.
3312 const size_t max_size = (max_size_bytes < 0)
3313 ? RtcEventLog::kUnlimitedOutput
3314 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003315 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3316 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3317 output_period_ms = 5000;
3318 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003319 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003320 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003321 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003322}
3323
Bjorn Tereliusde939432017-11-20 17:38:14 +01003324bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3325 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003326 // TODO(eladalon): In C++14, this can be done with a lambda.
3327 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003328 bool operator()() {
3329 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3330 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003331 PeerConnection* const pc;
3332 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003333 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003334 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003335 return worker_thread()->Invoke<bool>(
3336 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003337}
3338
3339void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003340 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003341 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3342}
3343
Harald Alvestrandad88c882018-11-28 16:47:46 +01003344rtc::scoped_refptr<DtlsTransportInterface>
3345PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3346 return transport_controller_->LookupDtlsTransportByMid(mid);
3347}
3348
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003349const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003350 return pending_local_description_ ? pending_local_description_.get()
3351 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003352}
3353
3354const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003355 return pending_remote_description_ ? pending_remote_description_.get()
3356 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
deadbeeffe4a8a42016-12-20 17:56:17 -08003359const SessionDescriptionInterface* PeerConnection::current_local_description()
3360 const {
Steve Anton75737c02017-11-06 10:37:17 -08003361 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003362}
3363
3364const SessionDescriptionInterface* PeerConnection::current_remote_description()
3365 const {
Steve Anton75737c02017-11-06 10:37:17 -08003366 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003367}
3368
3369const SessionDescriptionInterface* PeerConnection::pending_local_description()
3370 const {
Steve Anton75737c02017-11-06 10:37:17 -08003371 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003372}
3373
3374const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3375 const {
Steve Anton75737c02017-11-06 10:37:17 -08003376 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003377}
3378
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003379void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003380 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003381 // Update stats here so that we have the most recent stats for tracks and
3382 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003383 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003384
Steve Anton75737c02017-11-06 10:37:17 -08003385 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003386 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003387
Steve Anton8af21862017-12-15 11:20:13 -08003388 for (auto transceiver : transceivers_) {
3389 transceiver->Stop();
3390 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003391
3392 // Ensure that all asynchronous stats requests are completed before destroying
3393 // the transport controller below.
3394 if (stats_collector_) {
3395 stats_collector_->WaitForPendingRequest();
3396 }
3397
3398 // Don't destroy BaseChannels until after stats has been cleaned up so that
3399 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003400 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003401
Qingsi Wang93a84392018-01-30 17:13:09 -08003402 // The event log is used in the transport controller, which must be outlived
3403 // by the former. CreateOffer by the peer connection is implemented
3404 // asynchronously and if the peer connection is closed without resetting the
3405 // WebRTC session description factory, the session description factory would
3406 // call the transport controller.
3407 webrtc_session_desc_factory_.reset();
3408 transport_controller_.reset();
3409
deadbeef42a42632017-03-10 15:18:00 -08003410 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003411 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3412 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003413
Steve Anton978b8762017-09-29 12:15:02 -07003414 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003415 call_.reset();
3416 // The event log must outlive call (and any other object that uses it).
3417 event_log_.reset();
3418 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003419 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003420 // The .h file says that observer can be discarded after close() returns.
3421 // Make sure this is true.
3422 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003423}
3424
Steve Antonad182762018-09-05 20:22:40 +00003425void PeerConnection::OnMessage(rtc::Message* msg) {
3426 switch (msg->message_id) {
3427 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3428 SetSessionDescriptionMsg* param =
3429 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3430 param->observer->OnSuccess();
3431 delete param;
3432 break;
3433 }
3434 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3435 SetSessionDescriptionMsg* param =
3436 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3437 param->observer->OnFailure(std::move(param->error));
3438 delete param;
3439 break;
3440 }
3441 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3442 CreateSessionDescriptionMsg* param =
3443 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3444 param->observer->OnFailure(std::move(param->error));
3445 delete param;
3446 break;
3447 }
3448 case MSG_GETSTATS: {
3449 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3450 StatsReports reports;
3451 stats_->GetStats(param->track, &reports);
3452 param->observer->OnComplete(reports);
3453 delete param;
3454 break;
3455 }
3456 case MSG_FREE_DATACHANNELS: {
3457 sctp_data_channels_to_free_.clear();
3458 break;
3459 }
3460 case MSG_REPORT_USAGE_PATTERN: {
3461 ReportUsagePattern();
3462 break;
3463 }
3464 default:
3465 RTC_NOTREACHED() << "Not implemented";
3466 break;
3467 }
3468}
3469
Steve Antonafb0bb72018-02-20 11:35:37 -08003470cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3471 RTC_DCHECK(!IsUnifiedPlan());
3472 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3473 GetAudioTransceiver()->internal()->channel());
3474 if (voice_channel) {
3475 return voice_channel->media_channel();
3476 } else {
3477 return nullptr;
3478 }
3479}
3480
3481cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3482 RTC_DCHECK(!IsUnifiedPlan());
3483 auto* video_channel = static_cast<cricket::VideoChannel*>(
3484 GetVideoTransceiver()->internal()->channel());
3485 if (video_channel) {
3486 return video_channel->media_channel();
3487 } else {
3488 return nullptr;
3489 }
3490}
3491
Steve Anton4171afb2017-11-20 10:20:22 -08003492void PeerConnection::CreateAudioReceiver(
3493 MediaStreamInterface* stream,
3494 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003495 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3496 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003497 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3498 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003499 auto* audio_receiver = new AudioRtpReceiver(
3500 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003501 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003502 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3503 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3504 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003505 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003506 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003507 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508}
3509
Steve Anton4171afb2017-11-20 10:20:22 -08003510void PeerConnection::CreateVideoReceiver(
3511 MediaStreamInterface* stream,
3512 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003513 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3514 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003515 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3516 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003517 auto* video_receiver = new VideoRtpReceiver(
3518 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003519 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003520 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3521 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3522 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003523 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003524 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003525 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003526}
3527
deadbeef70ab1a12015-09-28 16:53:55 -07003528// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3529// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003530rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003531 const RtpSenderInfo& remote_sender_info) {
3532 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3533 if (!receiver) {
3534 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3535 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003536 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003537 }
Steve Anton4171afb2017-11-20 10:20:22 -08003538 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3539 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3540 } else {
3541 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3542 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003543 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003544}
3545
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003546void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3547 MediaStreamInterface* stream) {
3548 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003549 RTC_DCHECK(track);
3550 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003551 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003552 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003553 // We already have a sender for this track, so just change the stream_id
3554 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003555 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003556 return;
3557 }
3558
3559 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003560 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003561 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003562 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003563 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003564 // If the sender has already been configured in SDP, we call SetSsrc,
3565 // which will connect the sender to the underlying transport. This can
3566 // occur if a local session description that contains the ID of the sender
3567 // is set before AddStream is called. It can also occur if the local
3568 // session description is not changed and RemoveStream is called, and
3569 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003570 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003571 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003572 if (sender_info) {
3573 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003574 }
3575}
3576
3577// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3578// indefinitely, when we have unified plan SDP.
3579void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3580 MediaStreamInterface* stream) {
3581 RTC_DCHECK(!IsClosed());
3582 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003583 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003584 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3585 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003586 return;
3587 }
Steve Anton4171afb2017-11-20 10:20:22 -08003588 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003589}
3590
3591void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3592 MediaStreamInterface* stream) {
3593 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003594 RTC_DCHECK(track);
3595 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003596 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003597 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003598 // We already have a sender for this track, so just change the stream_id
3599 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003600 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003601 return;
3602 }
3603
3604 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003605 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003606 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003607 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003608 GetVideoTransceiver()->internal()->AddSender(new_sender);
3609 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003610 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003611 if (sender_info) {
3612 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003613 }
3614}
3615
3616void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3617 MediaStreamInterface* stream) {
3618 RTC_DCHECK(!IsClosed());
3619 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003620 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003621 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3622 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003623 return;
3624 }
Steve Anton4171afb2017-11-20 10:20:22 -08003625 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003626}
3627
Steve Antonba818672017-11-06 10:21:57 -08003628void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003629 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003630 if (ice_connection_state_ == new_state) {
3631 return;
3632 }
3633
deadbeefcbecd352015-09-23 11:50:27 -07003634 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003635 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003636 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003637 return;
3638 }
Steve Antonba818672017-11-06 10:21:57 -08003639
Mirko Bonadei675513b2017-11-09 11:09:25 +01003640 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3641 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003642 RTC_DCHECK(ice_connection_state_ !=
3643 PeerConnectionInterface::kIceConnectionClosed);
3644
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003645 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003646 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003647}
3648
Alex Loiko9289eda2018-11-23 16:18:59 +00003649void PeerConnection::SetStandardizedIceConnectionState(
3650 PeerConnectionInterface::IceConnectionState new_state) {
3651 RTC_DCHECK(signaling_thread()->IsCurrent());
3652 if (standardized_ice_connection_state_ == new_state)
3653 return;
3654 if (IsClosed())
3655 return;
3656 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003657 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003658}
3659
Jonas Olsson635474e2018-10-18 15:58:17 +02003660void PeerConnection::SetConnectionState(
3661 PeerConnectionInterface::PeerConnectionState new_state) {
3662 RTC_DCHECK(signaling_thread()->IsCurrent());
3663 if (connection_state_ == new_state)
3664 return;
3665 if (IsClosed())
3666 return;
3667 connection_state_ = new_state;
3668 Observer()->OnConnectionChange(new_state);
3669}
3670
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003671void PeerConnection::OnIceGatheringChange(
3672 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003673 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003674 if (IsClosed()) {
3675 return;
3676 }
3677 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003678 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003679}
3680
jbauch81bf7b02017-03-25 08:31:12 -07003681void PeerConnection::OnIceCandidate(
3682 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003683 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003684 if (IsClosed()) {
3685 return;
3686 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003687 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003688 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3689 candidate->candidate().address().IsPrivateIP()) {
3690 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3691 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003692 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003693}
3694
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003695void PeerConnection::OnIceCandidatesRemoved(
3696 const std::vector<cricket::Candidate>& candidates) {
3697 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003698 if (IsClosed()) {
3699 return;
3700 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003701 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003702}
3703
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003704void PeerConnection::ChangeSignalingState(
3705 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003706 RTC_DCHECK(signaling_thread()->IsCurrent());
3707 if (signaling_state_ == signaling_state) {
3708 return;
3709 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003710 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3711 << GetSignalingStateString(signaling_state_)
3712 << " New state: "
3713 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003714 signaling_state_ = signaling_state;
3715 if (signaling_state == kClosed) {
3716 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003717 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003718 standardized_ice_connection_state_ =
3719 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003720 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3721 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003722 if (ice_gathering_state_ != kIceGatheringComplete) {
3723 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003724 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003725 }
3726 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003727 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003728}
3729
deadbeefeb459812015-12-15 19:24:43 -08003730void PeerConnection::OnAudioTrackAdded(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 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003736 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003737}
3738
deadbeefeb459812015-12-15 19:24:43 -08003739void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3740 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003741 if (IsClosed()) {
3742 return;
3743 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003744 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003745 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003746}
3747
3748void PeerConnection::OnVideoTrackAdded(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 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003754 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003755}
3756
3757void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3758 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003759 if (IsClosed()) {
3760 return;
3761 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003762 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003763 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003764}
3765
Henrik Boström31638672017-11-23 17:48:32 +01003766void PeerConnection::PostSetSessionDescriptionSuccess(
3767 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003768 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3769 signaling_thread()->Post(RTC_FROM_HERE, this,
3770 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003771}
3772
deadbeefab9b2d12015-10-14 11:33:11 -07003773void PeerConnection::PostSetSessionDescriptionFailure(
3774 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003775 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003776 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003777 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3778 msg->error = std::move(error);
3779 signaling_thread()->Post(RTC_FROM_HERE, this,
3780 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003781}
3782
3783void PeerConnection::PostCreateSessionDescriptionFailure(
3784 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003785 RTCError error) {
3786 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003787 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3788 msg->error = std::move(error);
3789 signaling_thread()->Post(RTC_FROM_HERE, this,
3790 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003791}
3792
zhihuang1c378ed2017-08-17 14:10:50 -07003793void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003794 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003795 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003796 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003797
Steve Antondcc3c022017-12-22 16:02:54 -08003798 if (IsUnifiedPlan()) {
3799 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3800 } else {
3801 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3802 }
3803
Steve Antonfa2260d2017-12-28 16:38:23 -08003804 // Intentionally unset the data channel type for RTP data channel with the
3805 // second condition. Otherwise the RTP data channels would be successfully
3806 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3807 // when building with chromium. We want to leave RTP data channels broken, so
3808 // people won't try to use them.
3809 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3810 session_options->data_channel_type = data_channel_type();
3811 }
3812
Steve Antondcc3c022017-12-22 16:02:54 -08003813 // Apply ICE restart flag and renomination flag.
3814 for (auto& options : session_options->media_description_options) {
3815 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3816 options.transport_options.enable_ice_renomination =
3817 configuration_.enable_ice_renomination;
3818 }
3819
3820 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003821 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003822 session_options->pooled_ice_credentials =
3823 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3824 RTC_FROM_HERE,
3825 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3826 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003827 session_options->offer_extmap_allow_mixed =
3828 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003829}
3830
3831void PeerConnection::GetOptionsForPlanBOffer(
3832 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3833 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003834 // Figure out transceiver directional preferences.
3835 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3836 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3837
3838 // By default, generate sendrecv/recvonly m= sections.
3839 bool recv_audio = true;
3840 bool recv_video = true;
3841
3842 // By default, only offer a new m= section if we have media to send with it.
3843 bool offer_new_audio_description = send_audio;
3844 bool offer_new_video_description = send_video;
3845 bool offer_new_data_description = HasDataChannels();
3846
3847 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003848 if (offer_answer_options.offer_to_receive_audio !=
3849 RTCOfferAnswerOptions::kUndefined) {
3850 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003851 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003852 offer_new_audio_description ||
3853 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003854 }
Steve Antondcc3c022017-12-22 16:02:54 -08003855 if (offer_answer_options.offer_to_receive_video !=
3856 RTCOfferAnswerOptions::kUndefined) {
3857 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003858 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003859 offer_new_video_description ||
3860 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003861 }
3862
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003863 absl::optional<size_t> audio_index;
3864 absl::optional<size_t> video_index;
3865 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003866 // If a current description exists, generate m= sections in the same order,
3867 // using the first audio/video/data section that appears and rejecting
3868 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003869 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003870 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003871 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003872 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3873 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3874 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003875 }
3876
zhihuang1c378ed2017-08-17 14:10:50 -07003877 // Add audio/video/data m= sections to the end if needed.
3878 if (!audio_index && offer_new_audio_description) {
3879 session_options->media_description_options.push_back(
3880 cricket::MediaDescriptionOptions(
3881 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003882 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3883 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003884 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003885 }
zhihuang1c378ed2017-08-17 14:10:50 -07003886 if (!video_index && offer_new_video_description) {
3887 session_options->media_description_options.push_back(
3888 cricket::MediaDescriptionOptions(
3889 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003890 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3891 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003892 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003893 }
zhihuang1c378ed2017-08-17 14:10:50 -07003894 if (!data_index && offer_new_data_description) {
3895 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003896 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003897 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003898 }
3899
3900 cricket::MediaDescriptionOptions* audio_media_description_options =
3901 !audio_index ? nullptr
3902 : &session_options->media_description_options[*audio_index];
3903 cricket::MediaDescriptionOptions* video_media_description_options =
3904 !video_index ? nullptr
3905 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003906
Steve Anton4171afb2017-11-20 10:20:22 -08003907 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003908 video_media_description_options,
3909 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003910}
3911
3912// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3913// and return a reference to it.
3914// Generated MIDs should be no more than 3 bytes long to take up less space in
3915// the RTP packet.
3916static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3917 RTC_DCHECK(used_mids);
3918 // We're boring: just generate MIDs 0, 1, 2, ...
3919 size_t i = 0;
3920 std::set<std::string>::iterator it;
3921 bool inserted;
3922 do {
3923 std::string mid = rtc::ToString(i++);
3924 auto insert_result = used_mids->insert(mid);
3925 it = insert_result.first;
3926 inserted = insert_result.second;
3927 } while (!inserted);
3928 return *it;
3929}
3930
3931static cricket::MediaDescriptionOptions
3932GetMediaDescriptionOptionsForTransceiver(
3933 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3934 transceiver,
3935 const std::string& mid) {
3936 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003937 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003938 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003939 // This behavior is specified in JSEP. The gist is that:
3940 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3941 // sendrecv.
3942 // 2. If the MSID is included, then it must be included in any subsequent
3943 // offer/answer exactly the same until the RtpTransceiver is stopped.
3944 if (!transceiver->stopped() &&
3945 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3946 transceiver->internal()->has_ever_been_used_to_send())) {
3947 cricket::SenderOptions sender_options;
3948 sender_options.track_id = transceiver->sender()->id();
3949 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003950 int num_send_encoding_layers =
3951 transceiver->sender()->init_send_encodings().size();
3952 sender_options.num_sim_layers =
3953 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003954 media_description_options.sender_options.push_back(sender_options);
3955 }
Steve Antondcc3c022017-12-22 16:02:54 -08003956 return media_description_options;
3957}
3958
Steve Anton5c72e712018-12-10 14:25:30 -08003959// Returns the ContentInfo at mline index |i|, or null if none exists.
3960static const ContentInfo* GetContentByIndex(
3961 const SessionDescriptionInterface* sdesc,
3962 size_t i) {
3963 if (!sdesc) {
3964 return nullptr;
3965 }
3966 const ContentInfos& contents = sdesc->description()->contents();
3967 return (i < contents.size() ? &contents[i] : nullptr);
3968}
3969
Steve Antondcc3c022017-12-22 16:02:54 -08003970void PeerConnection::GetOptionsForUnifiedPlanOffer(
3971 const RTCOfferAnswerOptions& offer_answer_options,
3972 cricket::MediaSessionOptions* session_options) {
3973 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3974 // Offers) and 5.2.2 (Subsequent Offers).
3975 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3976 const ContentInfos& local_contents =
3977 (local_description() ? local_description()->description()->contents()
3978 : ContentInfos());
3979 const ContentInfos& remote_contents =
3980 (remote_description() ? remote_description()->description()->contents()
3981 : ContentInfos());
3982 // The mline indices that can be recycled. New transceivers should reuse these
3983 // slots first.
3984 std::queue<size_t> recycleable_mline_indices;
3985 // Track the MIDs used in previous offer/answer exchanges and the current
3986 // offer so that new, unique MIDs are generated.
3987 std::set<std::string> used_mids = seen_mids_;
3988 // First, go through each media section that exists in either the local or
3989 // remote description and generate a media section in this offer for the
3990 // associated transceiver. If a media section can be recycled, generate a
3991 // default, rejected media section here that can be later overwritten.
3992 for (size_t i = 0;
3993 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3994 // Either |local_content| or |remote_content| is non-null.
3995 const ContentInfo* local_content =
3996 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08003997 const ContentInfo* current_local_content =
3998 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08003999 const ContentInfo* remote_content =
4000 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004001 const ContentInfo* current_remote_content =
4002 GetContentByIndex(current_remote_description(), i);
4003 bool had_been_rejected =
4004 (current_local_content && current_local_content->rejected) ||
4005 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004006 const std::string& mid =
4007 (local_content ? local_content->name : remote_content->name);
4008 cricket::MediaType media_type =
4009 (local_content ? local_content->media_description()->type()
4010 : remote_content->media_description()->type());
4011 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4012 media_type == cricket::MEDIA_TYPE_VIDEO) {
4013 auto transceiver = GetAssociatedTransceiver(mid);
4014 RTC_CHECK(transceiver);
4015 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004016 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004017 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004018 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004019 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4020 RtpTransceiverDirection::kInactive,
4021 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004022 recycleable_mline_indices.push(i);
4023 } else {
4024 session_options->media_description_options.push_back(
4025 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4026 // CreateOffer shouldn't really cause any state changes in
4027 // PeerConnection, but we need a way to match new transceivers to new
4028 // media sections in SetLocalDescription and JSEP specifies this is done
4029 // by recording the index of the media section generated for the
4030 // transceiver in the offer.
4031 transceiver->internal()->set_mline_index(i);
4032 }
4033 } else {
4034 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004035 RTC_CHECK(GetDataMid());
4036 if (had_been_rejected || mid != *GetDataMid()) {
4037 session_options->media_description_options.push_back(
4038 GetMediaDescriptionOptionsForRejectedData(mid));
4039 } else {
4040 session_options->media_description_options.push_back(
4041 GetMediaDescriptionOptionsForActiveData(mid));
4042 }
Steve Antondcc3c022017-12-22 16:02:54 -08004043 }
4044 }
4045 // Next, look for transceivers that are newly added (that is, are not stopped
4046 // and not associated). Reuse media sections marked as recyclable first,
4047 // otherwise append to the end of the offer. New media sections should be
4048 // added in the order they were added to the PeerConnection.
4049 for (auto transceiver : transceivers_) {
4050 if (transceiver->mid() || transceiver->stopped()) {
4051 continue;
4052 }
4053 size_t mline_index;
4054 if (!recycleable_mline_indices.empty()) {
4055 mline_index = recycleable_mline_indices.front();
4056 recycleable_mline_indices.pop();
4057 session_options->media_description_options[mline_index] =
4058 GetMediaDescriptionOptionsForTransceiver(transceiver,
4059 AllocateMid(&used_mids));
4060 } else {
4061 mline_index = session_options->media_description_options.size();
4062 session_options->media_description_options.push_back(
4063 GetMediaDescriptionOptionsForTransceiver(transceiver,
4064 AllocateMid(&used_mids)));
4065 }
4066 // See comment above for why CreateOffer changes the transceiver's state.
4067 transceiver->internal()->set_mline_index(mline_index);
4068 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004069 // Lastly, add a m-section if we have local data channels and an m section
4070 // does not already exist.
4071 if (!GetDataMid() && HasDataChannels()) {
4072 session_options->media_description_options.push_back(
4073 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4074 }
Steve Antondcc3c022017-12-22 16:02:54 -08004075}
4076
4077void PeerConnection::GetOptionsForAnswer(
4078 const RTCOfferAnswerOptions& offer_answer_options,
4079 cricket::MediaSessionOptions* session_options) {
4080 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4081
4082 if (IsUnifiedPlan()) {
4083 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4084 } else {
4085 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4086 }
4087
Steve Antonfa2260d2017-12-28 16:38:23 -08004088 // Intentionally unset the data channel type for RTP data channel. Otherwise
4089 // the RTP data channels would be successfully negotiated by default and the
4090 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4091 // We want to leave RTP data channels broken, so people won't try to use them.
4092 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4093 session_options->data_channel_type = data_channel_type();
4094 }
4095
Steve Antondcc3c022017-12-22 16:02:54 -08004096 // Apply ICE renomination flag.
4097 for (auto& options : session_options->media_description_options) {
4098 options.transport_options.enable_ice_renomination =
4099 configuration_.enable_ice_renomination;
4100 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004101
4102 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004103 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004104 session_options->pooled_ice_credentials =
4105 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4106 RTC_FROM_HERE,
4107 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4108 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004109}
4110
Steve Antondcc3c022017-12-22 16:02:54 -08004111void PeerConnection::GetOptionsForPlanBAnswer(
4112 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004113 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004114 // Figure out transceiver directional preferences.
4115 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4116 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4117
4118 // By default, generate sendrecv/recvonly m= sections. The direction is also
4119 // restricted by the direction in the offer.
4120 bool recv_audio = true;
4121 bool recv_video = true;
4122
4123 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004124 if (offer_answer_options.offer_to_receive_audio !=
4125 RTCOfferAnswerOptions::kUndefined) {
4126 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004127 }
Steve Antondcc3c022017-12-22 16:02:54 -08004128 if (offer_answer_options.offer_to_receive_video !=
4129 RTCOfferAnswerOptions::kUndefined) {
4130 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004131 }
4132
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004133 absl::optional<size_t> audio_index;
4134 absl::optional<size_t> video_index;
4135 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004136
4137 // Generate m= sections that match those in the offer.
4138 // Note that mediasession.cc will handle intersection our preferred
4139 // direction with the offered direction.
4140 GenerateMediaDescriptionOptions(
4141 remote_description(),
4142 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4143 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4144 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004145
4146 cricket::MediaDescriptionOptions* audio_media_description_options =
4147 !audio_index ? nullptr
4148 : &session_options->media_description_options[*audio_index];
4149 cricket::MediaDescriptionOptions* video_media_description_options =
4150 !video_index ? nullptr
4151 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004152
Steve Anton4171afb2017-11-20 10:20:22 -08004153 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004154 video_media_description_options,
4155 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004156}
zhihuangaf388472016-11-02 16:49:48 -07004157
Steve Antondcc3c022017-12-22 16:02:54 -08004158void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4159 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4160 cricket::MediaSessionOptions* session_options) {
4161 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4162 // Answers) and 5.3.2 (Subsequent Answers).
4163 RTC_DCHECK(remote_description());
4164 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4165 for (const ContentInfo& content :
4166 remote_description()->description()->contents()) {
4167 cricket::MediaType media_type = content.media_description()->type();
4168 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4169 media_type == cricket::MEDIA_TYPE_VIDEO) {
4170 auto transceiver = GetAssociatedTransceiver(content.name);
4171 RTC_CHECK(transceiver);
4172 session_options->media_description_options.push_back(
4173 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4174 } else {
4175 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004176 // Reject all data sections if data channels are disabled.
4177 // Reject a data section if it has already been rejected.
4178 // Reject all data sections except for the first one.
4179 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4180 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004181 session_options->media_description_options.push_back(
4182 GetMediaDescriptionOptionsForRejectedData(content.name));
4183 } else {
4184 session_options->media_description_options.push_back(
4185 GetMediaDescriptionOptionsForActiveData(content.name));
4186 }
Steve Antondcc3c022017-12-22 16:02:54 -08004187 }
4188 }
htaa2a49d92016-03-04 02:51:39 -08004189}
4190
zhihuang1c378ed2017-08-17 14:10:50 -07004191void PeerConnection::GenerateMediaDescriptionOptions(
4192 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004193 RtpTransceiverDirection audio_direction,
4194 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004195 absl::optional<size_t>* audio_index,
4196 absl::optional<size_t>* video_index,
4197 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004198 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004199 for (const cricket::ContentInfo& content :
4200 session_desc->description()->contents()) {
4201 if (IsAudioContent(&content)) {
4202 // If we already have an audio m= section, reject this extra one.
4203 if (*audio_index) {
4204 session_options->media_description_options.push_back(
4205 cricket::MediaDescriptionOptions(
4206 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004207 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004208 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004209 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004210 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004211 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4212 content.name, audio_direction,
4213 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004214 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004215 }
4216 } else if (IsVideoContent(&content)) {
4217 // If we already have an video m= section, reject this extra one.
4218 if (*video_index) {
4219 session_options->media_description_options.push_back(
4220 cricket::MediaDescriptionOptions(
4221 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004222 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004223 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004224 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004225 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004226 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4227 content.name, video_direction,
4228 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004229 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004230 }
4231 } else {
4232 RTC_DCHECK(IsDataContent(&content));
4233 // If we already have an data m= section, reject this extra one.
4234 if (*data_index) {
4235 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004236 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004237 } else {
4238 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004239 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004240 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004241 }
4242 }
htaa2a49d92016-03-04 02:51:39 -08004243 }
deadbeefab9b2d12015-10-14 11:33:11 -07004244}
4245
Steve Antonfa2260d2017-12-28 16:38:23 -08004246cricket::MediaDescriptionOptions
4247PeerConnection::GetMediaDescriptionOptionsForActiveData(
4248 const std::string& mid) const {
4249 // Direction for data sections is meaningless, but legacy endpoints might
4250 // expect sendrecv.
4251 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4252 RtpTransceiverDirection::kSendRecv,
4253 /*stopped=*/false);
4254 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4255 return options;
4256}
4257
4258cricket::MediaDescriptionOptions
4259PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4260 const std::string& mid) const {
4261 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4262 RtpTransceiverDirection::kInactive,
4263 /*stopped=*/true);
4264 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4265 return options;
4266}
4267
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004268absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004269 switch (data_channel_type_) {
4270 case cricket::DCT_RTP:
4271 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004272 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004273 }
4274 return rtp_data_channel_->content_name();
4275 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004276 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004277 case cricket::DCT_MEDIA_TRANSPORT:
4278 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004279 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004280 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004281 }
4282}
4283
Steve Anton4171afb2017-11-20 10:20:22 -08004284void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4285 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4286 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004287 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004288}
4289
Steve Anton4171afb2017-11-20 10:20:22 -08004290void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004291 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004292 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004293 cricket::MediaType media_type,
4294 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004295 RTC_DCHECK(!IsUnifiedPlan());
4296
Steve Anton4171afb2017-11-20 10:20:22 -08004297 std::vector<RtpSenderInfo>* current_senders =
4298 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004299
Steve Anton4171afb2017-11-20 10:20:22 -08004300 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004301 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004302 for (auto sender_it = current_senders->begin();
4303 sender_it != current_senders->end();
4304 /* incremented manually */) {
4305 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004306 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004307 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004308 std::string params_stream_id;
4309 if (params) {
4310 params_stream_id =
4311 (!params->first_stream_id().empty() ? params->first_stream_id()
4312 : kDefaultStreamId);
4313 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004314 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004315 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004316 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004317 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004318 sender_exists) {
4319 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004320 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004321 OnRemoteSenderRemoved(info, media_type);
4322 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004323 }
4324 }
4325
Steve Anton4171afb2017-11-20 10:20:22 -08004326 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004327 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004328 if (!params.has_ssrcs()) {
4329 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4330 // sender, this means it is coming from a Unified Plan endpoint,so we just
4331 // create a default.
4332 default_sender_needed = true;
4333 break;
4334 }
4335
Seth Hampson845e8782018-03-02 11:34:10 -08004336 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004337 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004338 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4339 // not supported in Plan B, we just take the first here and create the
4340 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004341 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004342 (!params.first_stream_id().empty() ? params.first_stream_id()
4343 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004344 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004345 uint32_t ssrc = params.first_ssrc();
4346
4347 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004348 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004349 if (!stream) {
4350 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004351 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004352 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004353 remote_streams_->AddStream(stream);
4354 new_streams->AddStream(stream);
4355 }
4356
Steve Anton4171afb2017-11-20 10:20:22 -08004357 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004358 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004359 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004360 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004361 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004362 }
4363 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004364
Steve Anton4171afb2017-11-20 10:20:22 -08004365 // Add default sender if necessary.
4366 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004367 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004368 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004369 if (!default_stream) {
4370 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004371 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004372 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004373 remote_streams_->AddStream(default_stream);
4374 new_streams->AddStream(default_stream);
4375 }
Steve Anton4171afb2017-11-20 10:20:22 -08004376 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4377 ? kDefaultAudioSenderId
4378 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004379 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004380 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004381 if (!default_sender_info) {
4382 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004383 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004384 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004385 }
4386 }
deadbeefab9b2d12015-10-14 11:33:11 -07004387}
4388
Steve Anton4171afb2017-11-20 10:20:22 -08004389void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4390 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004391 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4392 << " receiver for track_id=" << sender_info.sender_id
4393 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004394
Steve Anton3d954a62018-04-02 11:27:23 -07004395 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004396 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004397 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004398 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004399 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004400 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004401 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004402 }
4403}
4404
Steve Anton4171afb2017-11-20 10:20:22 -08004405void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4406 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004407 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4408 << " receiver for track_id=" << sender_info.sender_id
4409 << " and stream_id=" << sender_info.stream_id;
4410
Seth Hampson845e8782018-03-02 11:34:10 -08004411 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004412
Henrik Boström933d8b02017-10-10 10:05:16 -07004413 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004414 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004415 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4416 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004417 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004418 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004419 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004420 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004421 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004422 }
4423 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004424 // Stopping or destroying a VideoRtpReceiver will end the
4425 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004426 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004427 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004428 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004429 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004430 // There's no guarantee the track is still available, e.g. the track may
4431 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004432 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004433 }
4434 } else {
nisseede5da42017-01-12 05:15:36 -08004435 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004436 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004437 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004438 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004439 }
deadbeefab9b2d12015-10-14 11:33:11 -07004440}
4441
4442void PeerConnection::UpdateEndedRemoteMediaStreams() {
4443 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4444 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4445 MediaStreamInterface* stream = remote_streams_->at(i);
4446 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4447 streams_to_remove.push_back(stream);
4448 }
4449 }
4450
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004451 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004452 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004453 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004454 }
4455}
4456
Steve Anton4171afb2017-11-20 10:20:22 -08004457void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004458 const std::vector<cricket::StreamParams>& streams,
4459 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004460 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004461
Seth Hampson845e8782018-03-02 11:34:10 -08004462 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004463 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004464 for (auto sender_it = current_senders->begin();
4465 sender_it != current_senders->end();
4466 /* incremented manually */) {
4467 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004468 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004469 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4470 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004471 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004472 OnLocalSenderRemoved(info, media_type);
4473 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004474 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004475 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004476 }
4477 }
4478
Steve Anton4171afb2017-11-20 10:20:22 -08004479 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004480 for (const cricket::StreamParams& params : streams) {
4481 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004482 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004483 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004484 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004485 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004486 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004487 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004488 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004489 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004490 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004491 }
4492 }
4493}
4494
Steve Anton4171afb2017-11-20 10:20:22 -08004495void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4496 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004497 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004498 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004499 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004500 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4501 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004502 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004503 return;
4504 }
4505
deadbeeffac06552015-11-25 11:26:01 -08004506 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004507 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004508 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004509 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004510 }
deadbeeffac06552015-11-25 11:26:01 -08004511
Seth Hampson5b4f0752018-04-02 16:31:36 -07004512 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004513 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004514}
4515
Steve Anton4171afb2017-11-20 10:20:22 -08004516void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4517 cricket::MediaType media_type) {
4518 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004519 if (!sender) {
4520 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004521 // SessionDescriptions has been renegotiated.
4522 return;
4523 }
deadbeeffac06552015-11-25 11:26:01 -08004524
4525 // A sender has been removed from the SessionDescription but it's still
4526 // associated with the PeerConnection. This only occurs if the SDP doesn't
4527 // match with the calls to CreateSender, AddStream and RemoveStream.
4528 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004529 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004530 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004531 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004532 }
deadbeeffac06552015-11-25 11:26:01 -08004533
Steve Anton4171afb2017-11-20 10:20:22 -08004534 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004535}
4536
4537void PeerConnection::UpdateLocalRtpDataChannels(
4538 const cricket::StreamParamsVec& streams) {
4539 std::vector<std::string> existing_channels;
4540
4541 // Find new and active data channels.
4542 for (const cricket::StreamParams& params : streams) {
4543 // |it->sync_label| is actually the data channel label. The reason is that
4544 // we use the same naming of data channels as we do for
4545 // MediaStreams and Tracks.
4546 // For MediaStreams, the sync_label is the MediaStream label and the
4547 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004548 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004549 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004550 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004551 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004552 continue;
4553 }
4554 // Set the SSRC the data channel should use for sending.
4555 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4556 existing_channels.push_back(data_channel_it->first);
4557 }
4558
4559 UpdateClosingRtpDataChannels(existing_channels, true);
4560}
4561
4562void PeerConnection::UpdateRemoteRtpDataChannels(
4563 const cricket::StreamParamsVec& streams) {
4564 std::vector<std::string> existing_channels;
4565
4566 // Find new and active data channels.
4567 for (const cricket::StreamParams& params : streams) {
4568 // The data channel label is either the mslabel or the SSRC if the mslabel
4569 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004570 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004571 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004572 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004573 auto data_channel_it = rtp_data_channels_.find(label);
4574 if (data_channel_it == rtp_data_channels_.end()) {
4575 // This is a new data channel.
4576 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4577 } else {
4578 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4579 }
4580 existing_channels.push_back(label);
4581 }
4582
4583 UpdateClosingRtpDataChannels(existing_channels, false);
4584}
4585
4586void PeerConnection::UpdateClosingRtpDataChannels(
4587 const std::vector<std::string>& active_channels,
4588 bool is_local_update) {
4589 auto it = rtp_data_channels_.begin();
4590 while (it != rtp_data_channels_.end()) {
4591 DataChannel* data_channel = it->second;
4592 if (std::find(active_channels.begin(), active_channels.end(),
4593 data_channel->label()) != active_channels.end()) {
4594 ++it;
4595 continue;
4596 }
4597
4598 if (is_local_update) {
4599 data_channel->SetSendSsrc(0);
4600 } else {
4601 data_channel->RemotePeerRequestClose();
4602 }
4603
4604 if (data_channel->state() == DataChannel::kClosed) {
4605 rtp_data_channels_.erase(it);
4606 it = rtp_data_channels_.begin();
4607 } else {
4608 ++it;
4609 }
4610 }
4611}
4612
4613void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4614 uint32_t remote_ssrc) {
4615 rtc::scoped_refptr<DataChannel> channel(
4616 InternalCreateDataChannel(label, nullptr));
4617 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004618 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004619 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004620 return;
4621 }
4622 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004623 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4624 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004625 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004626}
4627
4628rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4629 const std::string& label,
4630 const InternalDataChannelInit* config) {
4631 if (IsClosed()) {
4632 return nullptr;
4633 }
Steve Anton75737c02017-11-06 10:37:17 -08004634 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004635 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004636 << "InternalCreateDataChannel: Data is not supported in this call.";
4637 return nullptr;
4638 }
4639 InternalDataChannelInit new_config =
4640 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004641 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004642 if (new_config.id < 0) {
4643 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004644 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004645 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004646 RTC_LOG(LS_ERROR)
4647 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004648 return nullptr;
4649 }
4650 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004651 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004652 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004653 return nullptr;
4654 }
4655 }
4656
Steve Anton75737c02017-11-06 10:37:17 -08004657 rtc::scoped_refptr<DataChannel> channel(
4658 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004659 if (!channel) {
4660 sid_allocator_.ReleaseSid(new_config.id);
4661 return nullptr;
4662 }
4663
4664 if (channel->data_channel_type() == cricket::DCT_RTP) {
4665 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004666 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4667 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004668 return nullptr;
4669 }
4670 rtp_data_channels_[channel->label()] = channel;
4671 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004672 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004673 sctp_data_channels_.push_back(channel);
4674 channel->SignalClosed.connect(this,
4675 &PeerConnection::OnSctpDataChannelClosed);
4676 }
4677
Steve Anton2d8609c2018-01-23 16:38:46 -08004678 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004679 return channel;
4680}
4681
4682bool PeerConnection::HasDataChannels() const {
4683 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4684}
4685
4686void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4687 for (const auto& channel : sctp_data_channels_) {
4688 if (channel->id() < 0) {
4689 int sid;
4690 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004691 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004692 continue;
4693 }
4694 channel->SetSctpSid(sid);
4695 }
4696 }
4697}
4698
4699void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004700 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004701 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4702 ++it) {
4703 if (it->get() == channel) {
4704 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004705 // After the closing procedure is done, it's safe to use this ID for
4706 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004707 sid_allocator_.ReleaseSid(channel->id());
4708 }
deadbeefbd292462015-12-14 18:15:29 -08004709 // Since this method is triggered by a signal from the DataChannel,
4710 // we can't free it directly here; we need to free it asynchronously.
4711 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004712 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004713 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4714 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004715 return;
4716 }
4717 }
4718}
4719
deadbeefab9b2d12015-10-14 11:33:11 -07004720void PeerConnection::OnDataChannelDestroyed() {
4721 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4722 // DataChannel may callback to us and try to modify the list.
4723 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4724 temp_rtp_dcs.swap(rtp_data_channels_);
4725 for (const auto& kv : temp_rtp_dcs) {
4726 kv.second->OnTransportChannelDestroyed();
4727 }
4728
4729 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4730 temp_sctp_dcs.swap(sctp_data_channels_);
4731 for (const auto& channel : temp_sctp_dcs) {
4732 channel->OnTransportChannelDestroyed();
4733 }
4734}
4735
4736void PeerConnection::OnDataChannelOpenMessage(
4737 const std::string& label,
4738 const InternalDataChannelInit& config) {
4739 rtc::scoped_refptr<DataChannel> channel(
4740 InternalCreateDataChannel(label, &config));
4741 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004742 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004743 return;
4744 }
4745
deadbeefa601f5c2016-06-06 14:27:39 -07004746 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4747 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004748 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004749 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004750}
4751
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004752bool PeerConnection::HandleOpenMessage_s(
4753 const cricket::ReceiveDataParams& params,
4754 const rtc::CopyOnWriteBuffer& buffer) {
4755 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4756 // Received OPEN message; parse and signal that a new data channel should
4757 // be created.
4758 std::string label;
4759 InternalDataChannelInit config;
4760 config.id = params.ssrc;
4761 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4762 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4763 << params.ssrc;
4764 return true;
4765 }
4766 config.open_handshake_role = InternalDataChannelInit::kAcker;
4767 OnDataChannelOpenMessage(label, config);
4768 return true;
4769 }
4770 return false;
4771}
4772
Steve Anton4171afb2017-11-20 10:20:22 -08004773rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4774PeerConnection::GetAudioTransceiver() const {
4775 // This method only works with Plan B SDP, where there is a single
4776 // audio/video transceiver.
4777 RTC_DCHECK(!IsUnifiedPlan());
4778 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004779 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004780 return transceiver;
4781 }
4782 }
4783 RTC_NOTREACHED();
4784 return nullptr;
4785}
4786
4787rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4788PeerConnection::GetVideoTransceiver() const {
4789 // This method only works with Plan B SDP, where there is a single
4790 // audio/video transceiver.
4791 RTC_DCHECK(!IsUnifiedPlan());
4792 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004793 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004794 return transceiver;
4795 }
4796 }
4797 RTC_NOTREACHED();
4798 return nullptr;
4799}
4800
4801// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4802// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004803bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004804 switch (type) {
4805 case cricket::MEDIA_TYPE_AUDIO:
4806 return !GetAudioTransceiver()->internal()->senders().empty();
4807 case cricket::MEDIA_TYPE_VIDEO:
4808 return !GetVideoTransceiver()->internal()->senders().empty();
4809 case cricket::MEDIA_TYPE_DATA:
4810 return false;
4811 }
4812 RTC_NOTREACHED();
4813 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004814}
4815
Steve Anton4171afb2017-11-20 10:20:22 -08004816rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4817PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4818 for (auto transceiver : transceivers_) {
4819 for (auto sender : transceiver->internal()->senders()) {
4820 if (sender->track() == track) {
4821 return sender;
4822 }
4823 }
4824 }
4825 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004826}
4827
Steve Anton4171afb2017-11-20 10:20:22 -08004828rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4829PeerConnection::FindSenderById(const std::string& sender_id) const {
4830 for (auto transceiver : transceivers_) {
4831 for (auto sender : transceiver->internal()->senders()) {
4832 if (sender->id() == sender_id) {
4833 return sender;
4834 }
4835 }
4836 }
4837 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004838}
4839
Steve Anton4171afb2017-11-20 10:20:22 -08004840rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4841PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4842 for (auto transceiver : transceivers_) {
4843 for (auto receiver : transceiver->internal()->receivers()) {
4844 if (receiver->id() == receiver_id) {
4845 return receiver;
4846 }
4847 }
4848 }
4849 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004850}
4851
Steve Anton4171afb2017-11-20 10:20:22 -08004852std::vector<PeerConnection::RtpSenderInfo>*
4853PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4854 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4855 media_type == cricket::MEDIA_TYPE_VIDEO);
4856 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4857 ? &remote_audio_sender_infos_
4858 : &remote_video_sender_infos_;
4859}
4860
4861std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004862 cricket::MediaType media_type) {
4863 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4864 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004865 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4866 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004867}
4868
Steve Anton4171afb2017-11-20 10:20:22 -08004869const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4870 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004871 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004872 const std::string sender_id) const {
4873 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004874 if (sender_info.stream_id == stream_id &&
4875 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004876 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004877 }
4878 }
4879 return nullptr;
4880}
4881
4882DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4883 for (const auto& channel : sctp_data_channels_) {
4884 if (channel->id() == sid) {
4885 return channel;
4886 }
4887 }
4888 return nullptr;
4889}
4890
deadbeef91dd5672016-05-18 16:55:30 -07004891bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004892 const cricket::ServerAddresses& stun_servers,
4893 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004894 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004895 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004896 // To handle both internal and externally created port allocator, we will
4897 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004898 port_allocator_flags_ = port_allocator_->flags();
4899 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4900 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4901 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004902 // If the disable-IPv6 flag was specified, we'll not override it
4903 // by experiment.
4904 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004905 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004906 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4907 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004908 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004909 }
4910
zhihuangb09b3f92017-03-07 14:40:51 -08004911 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004912 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004913 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004914 }
4915
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004916 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004917 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004918 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004919 }
4920
honghaiz60347052016-05-31 18:29:12 -07004921 if (configuration.candidate_network_policy ==
4922 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004923 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004924 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004925 }
4926
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004927 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004928 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004929 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4930 }
4931
Qingsi Wanga2d60672018-04-11 16:57:45 -07004932 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004933 // No step delay is used while allocating ports.
4934 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4935 port_allocator_->set_candidate_filter(
4936 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004937 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004938
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004939 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004940 for (auto& turn_server : turn_servers_copy) {
4941 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004942 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004943 // Call this last since it may create pooled allocator sessions using the
4944 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004945 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004946 stun_servers, std::move(turn_servers_copy),
4947 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4948 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004949 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004950 return true;
4951}
4952
deadbeef91dd5672016-05-18 16:55:30 -07004953bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004954 const cricket::ServerAddresses& stun_servers,
4955 const std::vector<cricket::RelayServerConfig>& turn_servers,
4956 IceTransportsType type,
4957 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004958 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004959 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004960 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004961 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004962 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004963 // According to JSEP, after setLocalDescription, changing the candidate pool
4964 // size is not allowed, and changing the set of ICE servers will not result
4965 // in new candidates being gathered.
4966 if (local_description()) {
4967 port_allocator_->FreezeCandidatePool();
4968 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004969 // Add the custom tls turn servers if they exist.
4970 auto turn_servers_copy = turn_servers;
4971 for (auto& turn_server : turn_servers_copy) {
4972 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4973 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004974 // Call this last since it may create pooled allocator sessions using the
4975 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004976 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004977 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4978 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004979}
4980
Steve Antonba818672017-11-06 10:21:57 -08004981cricket::ChannelManager* PeerConnection::channel_manager() const {
4982 return factory_->channel_manager();
4983}
4984
Elad Alon99c3fe52017-10-13 16:29:40 +02004985bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004986 std::unique_ptr<RtcEventLogOutput> output,
4987 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004988 if (!event_log_) {
4989 return false;
4990 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004991 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004992}
4993
4994void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004995 if (event_log_) {
4996 event_log_->StopLogging();
4997 }
ivoc14d5dbe2016-07-04 07:06:55 -07004998}
nisseeaabdf62017-05-05 02:23:02 -07004999
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005000cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005001 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005002 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005003 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005004 if (channel && channel->content_name() == content_name) {
5005 return channel;
5006 }
Steve Anton75737c02017-11-06 10:37:17 -08005007 }
5008 if (rtp_data_channel() &&
5009 rtp_data_channel()->content_name() == content_name) {
5010 return rtp_data_channel();
5011 }
5012 return nullptr;
5013}
5014
5015bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005016 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005017 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005018 RTC_LOG(LS_INFO)
5019 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005020 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005021 return false;
5022 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005023 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005024 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005025 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005026 return false;
5027 }
5028
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005029 absl::optional<rtc::SSLRole> dtls_role;
5030 if (sctp_mid_) {
5031 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5032 } else if (is_caller_) {
5033 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5034 }
Zhi Huange830e682018-03-30 10:48:35 -07005035 if (dtls_role) {
5036 *role = *dtls_role;
5037 return true;
5038 }
5039 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005040}
5041
5042bool PeerConnection::GetSslRole(const std::string& content_name,
5043 rtc::SSLRole* role) {
5044 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005045 RTC_LOG(LS_INFO)
5046 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005047 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005048 return false;
5049 }
5050
Zhi Huange830e682018-03-30 10:48:35 -07005051 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5052 if (dtls_role) {
5053 *role = *dtls_role;
5054 return true;
5055 }
5056 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005057}
5058
Steve Antonf8470812017-12-04 10:46:21 -08005059void PeerConnection::SetSessionError(SessionError error,
5060 const std::string& error_desc) {
5061 RTC_DCHECK_RUN_ON(signaling_thread());
5062 if (error != session_error_) {
5063 session_error_ = error;
5064 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005065 }
5066}
5067
Zhi Huange830e682018-03-30 10:48:35 -07005068RTCError PeerConnection::UpdateSessionState(
5069 SdpType type,
5070 cricket::ContentSource source,
5071 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005072 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005073
5074 // If there's already a pending error then no state transition should happen.
5075 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005076 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005077
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005078 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005079 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005080 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005081 }
5082
5083 // Update the signaling state according to the specified state machine (see
5084 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005085 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005086 ChangeSignalingState(source == cricket::CS_LOCAL
5087 ? PeerConnectionInterface::kHaveLocalOffer
5088 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005089 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005090 ChangeSignalingState(source == cricket::CS_LOCAL
5091 ? PeerConnectionInterface::kHaveLocalPrAnswer
5092 : PeerConnectionInterface::kHaveRemotePrAnswer);
5093 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005094 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005095 ChangeSignalingState(PeerConnectionInterface::kStable);
5096 }
5097
5098 // Update internal objects according to the session description's media
5099 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005100 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005101 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005102 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005103 }
5104
Steve Anton8a006912017-12-04 15:25:56 -08005105 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005106}
5107
Steve Anton8a006912017-12-04 15:25:56 -08005108RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005109 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005110 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005111 const SessionDescriptionInterface* sdesc =
5112 (source == cricket::CS_LOCAL ? local_description()
5113 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005114 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005115
5116 // Push down the new SDP media section for each audio/video transceiver.
5117 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005118 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005119 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005120 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005121 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005122 continue;
5123 }
5124 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005125 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005126 if (!content_desc) {
5127 continue;
5128 }
5129 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005130 bool success = (source == cricket::CS_LOCAL)
5131 ? channel->SetLocalContent(content_desc, type, &error)
5132 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005133 if (!success) {
5134 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5135 }
5136 }
5137
5138 // If using the RtpDataChannel, push down the new SDP section for it too.
5139 if (rtp_data_channel_) {
5140 const ContentInfo* data_content =
5141 cricket::GetFirstDataContent(sdesc->description());
5142 if (data_content && !data_content->rejected) {
5143 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005144 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005145 if (data_desc) {
5146 std::string error;
5147 bool success =
5148 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005149 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005150 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005151 if (!success) {
5152 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5153 std::move(error));
5154 }
Steve Anton75737c02017-11-06 10:37:17 -08005155 }
5156 }
5157 }
Steve Antoned10bd92017-12-05 10:52:59 -08005158
Steve Anton75737c02017-11-06 10:37:17 -08005159 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5160 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5161 if (sctp_transport_ && local_description() && remote_description() &&
5162 cricket::GetFirstDataContent(local_description()->description()) &&
5163 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005164 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005165 RTC_FROM_HERE,
5166 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005167 if (!success) {
5168 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5169 "Failed to push down SCTP parameters.");
5170 }
Steve Anton75737c02017-11-06 10:37:17 -08005171 }
Steve Antoned10bd92017-12-05 10:52:59 -08005172
Steve Anton8a006912017-12-04 15:25:56 -08005173 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005174}
5175
5176bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5177 RTC_DCHECK(network_thread()->IsCurrent());
5178 RTC_DCHECK(local_description());
5179 RTC_DCHECK(remote_description());
5180 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5181 // When we support "max-message-size", that would also be pushed down here.
5182 return sctp_transport_->Start(
5183 GetSctpPort(local_description()->description()),
5184 GetSctpPort(remote_description()->description()));
5185}
5186
Steve Anton8a006912017-12-04 15:25:56 -08005187RTCError PeerConnection::PushdownTransportDescription(
5188 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005189 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005190 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005191
Zhi Huange830e682018-03-30 10:48:35 -07005192 if (source == cricket::CS_LOCAL) {
5193 const SessionDescriptionInterface* sdesc = local_description();
5194 RTC_DCHECK(sdesc);
5195 return transport_controller_->SetLocalDescription(type,
5196 sdesc->description());
5197 } else {
5198 const SessionDescriptionInterface* sdesc = remote_description();
5199 RTC_DCHECK(sdesc);
5200 return transport_controller_->SetRemoteDescription(type,
5201 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005202 }
Steve Anton75737c02017-11-06 10:37:17 -08005203}
5204
5205bool PeerConnection::GetTransportDescription(
5206 const SessionDescription* description,
5207 const std::string& content_name,
5208 cricket::TransportDescription* tdesc) {
5209 if (!description || !tdesc) {
5210 return false;
5211 }
5212 const TransportInfo* transport_info =
5213 description->GetTransportInfoByName(content_name);
5214 if (!transport_info) {
5215 return false;
5216 }
5217 *tdesc = transport_info->description;
5218 return true;
5219}
5220
Steve Anton75737c02017-11-06 10:37:17 -08005221cricket::IceConfig PeerConnection::ParseIceConfig(
5222 const PeerConnectionInterface::RTCConfiguration& config) const {
5223 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005224 switch (config.continual_gathering_policy) {
5225 case PeerConnectionInterface::GATHER_ONCE:
5226 gathering_policy = cricket::GATHER_ONCE;
5227 break;
5228 case PeerConnectionInterface::GATHER_CONTINUALLY:
5229 gathering_policy = cricket::GATHER_CONTINUALLY;
5230 break;
5231 default:
5232 RTC_NOTREACHED();
5233 gathering_policy = cricket::GATHER_ONCE;
5234 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005235
Steve Anton75737c02017-11-06 10:37:17 -08005236 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005237 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5238 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005239 ice_config.prioritize_most_likely_candidate_pairs =
5240 config.prioritize_most_likely_ice_candidate_pairs;
5241 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005242 RTCConfigurationToIceConfigOptionalInt(
5243 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005244 ice_config.continual_gathering_policy = gathering_policy;
5245 ice_config.presume_writable_when_fully_relayed =
5246 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005247 ice_config.ice_check_interval_strong_connectivity =
5248 config.ice_check_interval_strong_connectivity;
5249 ice_config.ice_check_interval_weak_connectivity =
5250 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005251 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005252 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5253 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005254 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005255 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005256 ice_config.regather_all_networks_interval_range =
5257 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005258 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005259 return ice_config;
5260}
5261
Steve Antona41959e2018-11-28 11:15:33 -08005262static absl::string_view GetTrackIdBySsrc(
5263 const SessionDescriptionInterface* session_description,
5264 uint32_t ssrc) {
5265 if (!session_description) {
5266 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005267 }
Steve Antona41959e2018-11-28 11:15:33 -08005268 for (const cricket::ContentInfo& content :
5269 session_description->description()->contents()) {
5270 const cricket::MediaContentDescription& media =
5271 *content.media_description();
5272 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5273 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5274 const cricket::StreamParams* stream_params =
5275 cricket::GetStreamBySsrc(media.streams(), ssrc);
5276 if (stream_params) {
5277 return stream_params->id;
5278 }
5279 }
5280 }
5281 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005282}
5283
Steve Antona41959e2018-11-28 11:15:33 -08005284absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5285 return GetTrackIdBySsrc(local_description(), ssrc);
5286}
5287
5288absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5289 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005290}
5291
5292bool PeerConnection::SendData(const cricket::SendDataParams& params,
5293 const rtc::CopyOnWriteBuffer& payload,
5294 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005295 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5296 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5297 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005298 return false;
5299 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005300 if (media_transport_) {
5301 SendDataParams send_params;
5302 send_params.type = ToWebrtcDataMessageType(params.type);
5303 send_params.ordered = params.ordered;
5304 if (params.max_rtx_count >= 0) {
5305 send_params.max_rtx_count = params.max_rtx_count;
5306 } else if (params.max_rtx_ms >= 0) {
5307 send_params.max_rtx_ms = params.max_rtx_ms;
5308 }
5309 return media_transport_->SendData(params.sid, send_params, payload).ok();
5310 }
Steve Anton75737c02017-11-06 10:37:17 -08005311 return rtp_data_channel_
5312 ? rtp_data_channel_->SendData(params, payload, result)
5313 : network_thread()->Invoke<bool>(
5314 RTC_FROM_HERE,
5315 Bind(&cricket::SctpTransportInternal::SendData,
5316 sctp_transport_.get(), params, payload, result));
5317}
5318
5319bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005320 RTC_DCHECK_RUN_ON(signaling_thread());
5321 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005322 // Don't log an error here, because DataChannels are expected to call
5323 // ConnectDataChannel in this state. It's the only way to initially tell
5324 // whether or not the underlying transport is ready.
5325 return false;
5326 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005327 if (media_transport_) {
5328 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5329 &DataChannel::OnChannelReady);
5330 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5331 &DataChannel::OnDataReceived);
5332 SignalMediaTransportChannelClosing_s.connect(
5333 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5334 SignalMediaTransportChannelClosed_s.connect(
5335 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5336 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005337 rtp_data_channel_->SignalReadyToSendData.connect(
5338 webrtc_data_channel, &DataChannel::OnChannelReady);
5339 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5340 &DataChannel::OnDataReceived);
5341 } else {
5342 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5343 &DataChannel::OnChannelReady);
5344 SignalSctpDataReceived.connect(webrtc_data_channel,
5345 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005346 SignalSctpClosingProcedureStartedRemotely.connect(
5347 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5348 SignalSctpClosingProcedureComplete.connect(
5349 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005350 }
5351 return true;
5352}
5353
5354void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005355 RTC_DCHECK_RUN_ON(signaling_thread());
5356 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005357 RTC_LOG(LS_ERROR)
5358 << "DisconnectDataChannel called when rtp_data_channel_ and "
5359 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005360 return;
5361 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005362 if (media_transport_) {
5363 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5364 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5365 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5366 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5367 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005368 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5369 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5370 } else {
5371 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5372 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005373 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5374 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005375 }
5376}
5377
5378void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005379 if (media_transport_) {
5380 // No-op. Media transport does not need to add streams.
5381 return;
5382 }
Steve Anton75737c02017-11-06 10:37:17 -08005383 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005384 RTC_LOG(LS_ERROR)
5385 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005386 return;
5387 }
5388 network_thread()->Invoke<void>(
5389 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5390 sctp_transport_.get(), sid));
5391}
5392
5393void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005394 if (media_transport_) {
5395 media_transport_->CloseChannel(sid);
5396 return;
5397 }
Steve Anton75737c02017-11-06 10:37:17 -08005398 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005399 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005400 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005401 return;
5402 }
5403 network_thread()->Invoke<void>(
5404 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5405 sctp_transport_.get(), sid));
5406}
5407
5408bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005409 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005410 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005411 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005412 sctp_ready_to_send_data_;
5413}
5414
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005415void PeerConnection::OnDataReceived(int channel_id,
5416 DataMessageType type,
5417 const rtc::CopyOnWriteBuffer& buffer) {
5418 cricket::ReceiveDataParams params;
5419 params.sid = channel_id;
5420 params.type = ToCricketDataMessageType(type);
5421 media_transport_invoker_->AsyncInvoke<void>(
5422 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5423 RTC_DCHECK_RUN_ON(signaling_thread());
5424 if (!HandleOpenMessage_s(params, buffer)) {
5425 SignalMediaTransportReceivedData_s(params, buffer);
5426 }
5427 });
5428}
5429
5430void PeerConnection::OnChannelClosing(int channel_id) {
5431 media_transport_invoker_->AsyncInvoke<void>(
5432 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5433 RTC_DCHECK_RUN_ON(signaling_thread());
5434 SignalMediaTransportChannelClosing_s(channel_id);
5435 });
5436}
5437
5438void PeerConnection::OnChannelClosed(int channel_id) {
5439 media_transport_invoker_->AsyncInvoke<void>(
5440 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5441 RTC_DCHECK_RUN_ON(signaling_thread());
5442 SignalMediaTransportChannelClosed_s(channel_id);
5443 });
5444}
5445
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005446absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005447 if (sctp_mid_ && transport_controller_) {
5448 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5449 if (dtls_transport) {
5450 return dtls_transport->transport_name();
5451 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005452 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005453 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005454 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005455}
5456
Qingsi Wang72a43a12018-02-20 16:03:18 -08005457cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5458 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005459 network_thread()->Invoke<void>(
5460 RTC_FROM_HERE,
5461 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5462 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005463 return candidate_states_list;
5464}
5465
Steve Anton5dfde182018-02-06 10:34:40 -08005466std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5467 const {
5468 std::map<std::string, std::string> transport_names_by_mid;
5469 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005470 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005471 if (channel) {
5472 transport_names_by_mid[channel->content_name()] =
5473 channel->transport_name();
5474 }
Steve Anton75737c02017-11-06 10:37:17 -08005475 }
Steve Anton5dfde182018-02-06 10:34:40 -08005476 if (rtp_data_channel_) {
5477 transport_names_by_mid[rtp_data_channel_->content_name()] =
5478 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005479 }
5480 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005481 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005482 RTC_DCHECK(transport_name);
5483 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005484 }
Steve Anton5dfde182018-02-06 10:34:40 -08005485 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005486}
5487
Steve Anton5dfde182018-02-06 10:34:40 -08005488std::map<std::string, cricket::TransportStats>
5489PeerConnection::GetTransportStatsByNames(
5490 const std::set<std::string>& transport_names) {
5491 if (!network_thread()->IsCurrent()) {
5492 return network_thread()
5493 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5494 RTC_FROM_HERE,
5495 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005496 }
Steve Anton5dfde182018-02-06 10:34:40 -08005497 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5498 for (const std::string& transport_name : transport_names) {
5499 cricket::TransportStats transport_stats;
5500 bool success =
5501 transport_controller_->GetStats(transport_name, &transport_stats);
5502 if (success) {
5503 transport_stats_by_name[transport_name] = std::move(transport_stats);
5504 } else {
5505 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5506 << transport_name;
5507 }
5508 }
5509 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005510}
5511
5512bool PeerConnection::GetLocalCertificate(
5513 const std::string& transport_name,
5514 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005515 if (!certificate) {
5516 return false;
5517 }
5518 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5519 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005520}
5521
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005522std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005523 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005524 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005525}
5526
5527cricket::DataChannelType PeerConnection::data_channel_type() const {
5528 return data_channel_type_;
5529}
5530
5531bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5532 return pending_ice_restarts_.find(content_name) !=
5533 pending_ice_restarts_.end();
5534}
5535
Steve Anton75737c02017-11-06 10:37:17 -08005536bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5537 return transport_controller_->NeedsIceRestart(content_name);
5538}
5539
5540void PeerConnection::OnCertificateReady(
5541 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5542 transport_controller_->SetLocalCertificate(certificate);
5543}
5544
5545void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005546 SetSessionError(SessionError::kTransport,
5547 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005548}
5549
Alex Loiko9289eda2018-11-23 16:18:59 +00005550void PeerConnection::OnTransportControllerConnectionState(
5551 cricket::IceConnectionState state) {
5552 switch (state) {
5553 case cricket::kIceConnectionConnecting:
5554 // If the current state is Connected or Completed, then there were
5555 // writable channels but now there are not, so the next state must
5556 // be Disconnected.
5557 // kIceConnectionConnecting is currently used as the default,
5558 // un-connected state by the TransportController, so its only use is
5559 // detecting disconnections.
5560 if (ice_connection_state_ ==
5561 PeerConnectionInterface::kIceConnectionConnected ||
5562 ice_connection_state_ ==
5563 PeerConnectionInterface::kIceConnectionCompleted) {
5564 SetIceConnectionState(
5565 PeerConnectionInterface::kIceConnectionDisconnected);
5566 }
5567 break;
5568 case cricket::kIceConnectionFailed:
5569 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5570 break;
5571 case cricket::kIceConnectionConnected:
5572 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5573 "all transports are writable.";
5574 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5575 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5576 break;
5577 case cricket::kIceConnectionCompleted:
5578 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5579 "all transports are complete.";
5580 if (ice_connection_state_ !=
5581 PeerConnectionInterface::kIceConnectionConnected) {
5582 // If jumping directly from "checking" to "connected",
5583 // signal "connected" first.
5584 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5585 }
5586 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5587 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5588 ReportTransportStats();
5589 break;
5590 default:
5591 RTC_NOTREACHED();
5592 }
5593}
5594
Steve Anton75737c02017-11-06 10:37:17 -08005595void PeerConnection::OnTransportControllerCandidatesGathered(
5596 const std::string& transport_name,
5597 const cricket::Candidates& candidates) {
5598 RTC_DCHECK(signaling_thread()->IsCurrent());
5599 int sdp_mline_index;
5600 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005601 RTC_LOG(LS_ERROR)
5602 << "OnTransportControllerCandidatesGathered: content name "
5603 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005604 return;
5605 }
5606
5607 for (cricket::Candidates::const_iterator citer = candidates.begin();
5608 citer != candidates.end(); ++citer) {
5609 // Use transport_name as the candidate media id.
5610 std::unique_ptr<JsepIceCandidate> candidate(
5611 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5612 if (local_description()) {
5613 mutable_local_description()->AddCandidate(candidate.get());
5614 }
5615 OnIceCandidate(std::move(candidate));
5616 }
5617}
5618
5619void PeerConnection::OnTransportControllerCandidatesRemoved(
5620 const std::vector<cricket::Candidate>& candidates) {
5621 RTC_DCHECK(signaling_thread()->IsCurrent());
5622 // Sanity check.
5623 for (const cricket::Candidate& candidate : candidates) {
5624 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005625 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005626 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005627 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005628 return;
5629 }
5630 }
5631
5632 if (local_description()) {
5633 mutable_local_description()->RemoveCandidates(candidates);
5634 }
5635 OnIceCandidatesRemoved(candidates);
5636}
5637
5638void PeerConnection::OnTransportControllerDtlsHandshakeError(
5639 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005640 RTC_HISTOGRAM_ENUMERATION(
5641 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5642 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005643}
5644
Steve Antoned10bd92017-12-05 10:52:59 -08005645void PeerConnection::EnableSending() {
5646 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005647 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005648 if (channel && !channel->enabled()) {
5649 channel->Enable(true);
5650 }
Steve Anton75737c02017-11-06 10:37:17 -08005651 }
5652
Steve Anton4171afb2017-11-20 10:20:22 -08005653 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005654 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005655 }
Steve Anton75737c02017-11-06 10:37:17 -08005656}
5657
5658// Returns the media index for a local ice candidate given the content name.
5659bool PeerConnection::GetLocalCandidateMediaIndex(
5660 const std::string& content_name,
5661 int* sdp_mline_index) {
5662 if (!local_description() || !sdp_mline_index) {
5663 return false;
5664 }
5665
5666 bool content_found = false;
5667 const ContentInfos& contents = local_description()->description()->contents();
5668 for (size_t index = 0; index < contents.size(); ++index) {
5669 if (contents[index].name == content_name) {
5670 *sdp_mline_index = static_cast<int>(index);
5671 content_found = true;
5672 break;
5673 }
5674 }
5675 return content_found;
5676}
5677
5678bool PeerConnection::UseCandidatesInSessionDescription(
5679 const SessionDescriptionInterface* remote_desc) {
5680 if (!remote_desc) {
5681 return true;
5682 }
5683 bool ret = true;
5684
5685 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5686 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5687 for (size_t n = 0; n < candidates->count(); ++n) {
5688 const IceCandidateInterface* candidate = candidates->at(n);
5689 bool valid = false;
5690 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5691 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005692 RTC_LOG(LS_INFO)
5693 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005694 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005695 }
5696 continue;
5697 }
5698 ret = UseCandidate(candidate);
5699 if (!ret) {
5700 break;
5701 }
5702 }
5703 }
5704 return ret;
5705}
5706
5707bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5708 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5709 size_t remote_content_size =
5710 remote_description()->description()->contents().size();
5711 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005712 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005713 return false;
5714 }
5715
5716 cricket::ContentInfo content =
5717 remote_description()->description()->contents()[mediacontent_index];
5718 std::vector<cricket::Candidate> candidates;
5719 candidates.push_back(candidate->candidate());
5720 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005721 RTCError error =
5722 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005723 if (error.ok()) {
5724 // Candidates successfully submitted for checking.
5725 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5726 ice_connection_state_ ==
5727 PeerConnectionInterface::kIceConnectionDisconnected) {
5728 // If state is New, then the session has just gotten its first remote ICE
5729 // candidates, so go to Checking.
5730 // If state is Disconnected, the session is re-using old candidates or
5731 // receiving additional ones, so go to Checking.
5732 // If state is Connected, stay Connected.
5733 // TODO(bemasc): If state is Connected, and the new candidates are for a
5734 // newly added transport, then the state actually _should_ move to
5735 // checking. Add a way to distinguish that case.
5736 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5737 }
5738 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005739 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005740 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005741 }
5742 return true;
5743}
5744
5745void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005746 // Destroy video channel first since it may have a pointer to the
5747 // voice channel.
5748 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005749 if (!video_info || video_info->rejected) {
5750 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005751 }
5752
Steve Anton6fec8802017-12-04 10:37:29 -08005753 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5754 if (!audio_info || audio_info->rejected) {
5755 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005756 }
5757
5758 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5759 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005760 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005761 }
5762}
5763
Steve Antondcc3c022017-12-22 16:02:54 -08005764RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5765 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005766 const cricket::ContentGroup* bundle_group = nullptr;
5767 if (configuration_.bundle_policy ==
5768 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005769 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005770 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005771 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5772 "max-bundle configured but session description "
5773 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005774 }
5775 }
Steve Antondcc3c022017-12-22 16:02:54 -08005776 return std::move(bundle_group);
5777}
5778
5779RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005780 // Creating the media channels. Transports should already have been created
5781 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005782 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005783 if (voice && !voice->rejected &&
5784 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005785 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005786 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005787 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5788 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005789 }
5790 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5791 }
5792
Steve Antondcc3c022017-12-22 16:02:54 -08005793 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005794 if (video && !video->rejected &&
5795 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005796 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005797 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005798 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5799 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005800 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005801 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005802 }
5803
Steve Antondcc3c022017-12-22 16:02:54 -08005804 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005805 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005806 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005807 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005808 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5809 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005810 }
5811 }
5812
Steve Anton8a006912017-12-04 15:25:56 -08005813 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005814}
5815
Steve Anton4171afb2017-11-20 10:20:22 -08005816// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005817cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005818 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005819 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005820 MediaTransportInterface* media_transport = nullptr;
5821 if (configuration_.use_media_transport) {
5822 media_transport = GetMediaTransport(mid);
5823 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005824
Steve Anton75737c02017-11-06 10:37:17 -08005825 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005826 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005827 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5828 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005829 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005830 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005831 }
Steve Anton75737c02017-11-06 10:37:17 -08005832 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5833 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005834 voice_channel->SignalSentPacket.connect(this,
5835 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005836 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005837
Steve Antoneda6ccd2017-12-04 10:21:55 -08005838 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005839}
5840
Steve Anton4171afb2017-11-20 10:20:22 -08005841// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005842cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005843 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005844 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5845
5846 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005847 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005848 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005849 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5850 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005851 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005852 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005853 }
Steve Anton75737c02017-11-06 10:37:17 -08005854 video_channel->SignalDtlsSrtpSetupFailure.connect(
5855 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005856 video_channel->SignalSentPacket.connect(this,
5857 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005858 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005859
Steve Antoneda6ccd2017-12-04 10:21:55 -08005860 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005861}
5862
Zhi Huange830e682018-03-30 10:48:35 -07005863bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005864 switch (data_channel_type_) {
5865 case cricket::DCT_MEDIA_TRANSPORT:
5866 if (network_thread()->Invoke<bool>(
5867 RTC_FROM_HERE,
5868 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5869 this, mid))) {
5870 for (const auto& channel : sctp_data_channels_) {
5871 channel->OnTransportChannelCreated();
5872 }
5873 return true;
5874 }
Steve Anton75737c02017-11-06 10:37:17 -08005875 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005876 case cricket::DCT_SCTP:
5877 if (!sctp_factory_) {
5878 RTC_LOG(LS_ERROR)
5879 << "Trying to create SCTP transport, but didn't compile with "
5880 "SCTP support (HAVE_SCTP)";
5881 return false;
5882 }
5883 if (!network_thread()->Invoke<bool>(
5884 RTC_FROM_HERE,
5885 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5886 return false;
5887 }
5888 for (const auto& channel : sctp_data_channels_) {
5889 channel->OnTransportChannelCreated();
5890 }
5891 return true;
5892 case cricket::DCT_RTP:
5893 default:
5894 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5895 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5896 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5897 SrtpRequired(), GetCryptoOptions());
5898 if (!rtp_data_channel_) {
5899 return false;
5900 }
5901 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5902 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5903 rtp_data_channel_->SignalSentPacket.connect(
5904 this, &PeerConnection::OnSentPacket_w);
5905 rtp_data_channel_->SetRtpTransport(rtp_transport);
5906 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005907 }
5908
Steve Anton75737c02017-11-06 10:37:17 -08005909 return true;
5910}
5911
5912Call::Stats PeerConnection::GetCallStats() {
5913 if (!worker_thread()->IsCurrent()) {
5914 return worker_thread()->Invoke<Call::Stats>(
5915 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5916 }
5917 if (call_) {
5918 return call_->GetStats();
5919 } else {
5920 return Call::Stats();
5921 }
5922}
5923
Zhi Huange830e682018-03-30 10:48:35 -07005924bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005925 RTC_DCHECK(network_thread()->IsCurrent());
5926 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005927 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005928 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005929 RTC_DCHECK(dtls_transport);
5930 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005931 RTC_DCHECK(sctp_transport_);
5932 sctp_invoker_.reset(new rtc::AsyncInvoker());
5933 sctp_transport_->SignalReadyToSendData.connect(
5934 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5935 sctp_transport_->SignalDataReceived.connect(
5936 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005937 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5938 // another thread. Would be nice if there was a helper class similar to
5939 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5940 // code.
5941 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5942 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5943 sctp_transport_->SignalClosingProcedureComplete.connect(
5944 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005945 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005946 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005947 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005948}
5949
5950void PeerConnection::DestroySctpTransport_n() {
5951 RTC_DCHECK(network_thread()->IsCurrent());
5952 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005953 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005954 sctp_invoker_.reset(nullptr);
5955 sctp_ready_to_send_data_ = false;
5956}
5957
5958void PeerConnection::OnSctpTransportReadyToSendData_n() {
5959 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5960 RTC_DCHECK(network_thread()->IsCurrent());
5961 // Note: Cannot use rtc::Bind here because it will grab a reference to
5962 // PeerConnection and potentially cause PeerConnection to live longer than
5963 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5964 // be destroyed before PeerConnection is destroyed, and at that point all
5965 // pending tasks will be cleared.
5966 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5967 OnSctpTransportReadyToSendData_s(true);
5968 });
5969}
5970
5971void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5972 RTC_DCHECK(signaling_thread()->IsCurrent());
5973 sctp_ready_to_send_data_ = ready;
5974 SignalSctpReadyToSendData(ready);
5975}
5976
5977void PeerConnection::OnSctpTransportDataReceived_n(
5978 const cricket::ReceiveDataParams& params,
5979 const rtc::CopyOnWriteBuffer& payload) {
5980 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5981 RTC_DCHECK(network_thread()->IsCurrent());
5982 // Note: Cannot use rtc::Bind here because it will grab a reference to
5983 // PeerConnection and potentially cause PeerConnection to live longer than
5984 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5985 // be destroyed before PeerConnection is destroyed, and at that point all
5986 // pending tasks will be cleared.
5987 sctp_invoker_->AsyncInvoke<void>(
5988 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5989 OnSctpTransportDataReceived_s(params, payload);
5990 });
5991}
5992
5993void PeerConnection::OnSctpTransportDataReceived_s(
5994 const cricket::ReceiveDataParams& params,
5995 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005996 RTC_DCHECK_RUN_ON(signaling_thread());
5997 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005998 SignalSctpDataReceived(params, payload);
5999 }
6000}
6001
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006002void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006003 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6004 RTC_DCHECK(network_thread()->IsCurrent());
6005 sctp_invoker_->AsyncInvoke<void>(
6006 RTC_FROM_HERE, signaling_thread(),
6007 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006008 &SignalSctpClosingProcedureStartedRemotely, sid));
6009}
6010
6011void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6012 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6013 RTC_DCHECK(network_thread()->IsCurrent());
6014 sctp_invoker_->AsyncInvoke<void>(
6015 RTC_FROM_HERE, signaling_thread(),
6016 rtc::Bind(&sigslot::signal1<int>::operator(),
6017 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006018}
6019
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006020bool PeerConnection::SetupMediaTransportForDataChannels_n(
6021 const std::string& mid) {
6022 media_transport_ = transport_controller_->GetMediaTransport(mid);
6023 if (!media_transport_) {
6024 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6025 return false;
6026 }
6027
6028 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6029 media_transport_->SetDataSink(this);
6030 media_transport_data_mid_ = mid;
6031 transport_controller_->SignalMediaTransportStateChanged.connect(
6032 this, &PeerConnection::OnMediaTransportStateChanged_n);
6033 // Check the initial state right away, in case transport is already writable.
6034 OnMediaTransportStateChanged_n();
6035 return true;
6036}
6037
6038void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6039 if (!media_transport_) {
6040 return;
6041 }
6042 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6043 media_transport_data_mid_.reset();
6044 media_transport_->SetDataSink(nullptr);
6045 media_transport_invoker_ = nullptr;
6046 media_transport_ = nullptr;
6047}
6048
6049void PeerConnection::OnMediaTransportStateChanged_n() {
6050 if (!media_transport_data_mid_ ||
6051 transport_controller_->GetMediaTransportState(
6052 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6053 return;
6054 }
6055 media_transport_invoker_->AsyncInvoke<void>(
6056 RTC_FROM_HERE, signaling_thread(), [this] {
6057 RTC_DCHECK_RUN_ON(signaling_thread());
6058 media_transport_ready_to_send_data_ = true;
6059 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6060 });
6061}
6062
Steve Anton75737c02017-11-06 10:37:17 -08006063// Returns false if bundle is enabled and rtcp_mux is disabled.
6064bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6065 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6066 if (!bundle_enabled)
6067 return true;
6068
6069 const cricket::ContentGroup* bundle_group =
6070 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6071 RTC_DCHECK(bundle_group != NULL);
6072
6073 const cricket::ContentInfos& contents = desc->contents();
6074 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6075 citer != contents.end(); ++citer) {
6076 const cricket::ContentInfo* content = (&*citer);
6077 RTC_DCHECK(content != NULL);
6078 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006079 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006080 if (!HasRtcpMuxEnabled(content))
6081 return false;
6082 }
6083 }
6084 // RTCP-MUX is enabled in all the contents.
6085 return true;
6086}
6087
6088bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006089 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006090}
6091
Steve Anton8a006912017-12-04 15:25:56 -08006092RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006093 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006094 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006095 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006096 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006097 }
6098
6099 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006100 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006101 }
6102
Steve Anton3828c062017-12-06 10:34:51 -08006103 SdpType type = sdesc->GetType();
6104 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6105 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006106 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006107 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006108 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006109 }
6110
6111 // Verify crypto settings.
6112 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006113 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6114 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006115 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006116 if (!crypto_error.ok()) {
6117 return crypto_error;
6118 }
Steve Anton75737c02017-11-06 10:37:17 -08006119 }
6120
6121 // Verify ice-ufrag and ice-pwd.
6122 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006123 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6124 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006125 }
6126
6127 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006128 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6129 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006130 }
6131
6132 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6133 // m-lines that do not rtcp-mux enabled.
6134
6135 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006136 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006137 // With an answer we want to compare the new answer session description with
6138 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006139 const cricket::SessionDescription* offer_desc =
6140 (source == cricket::CS_LOCAL) ? remote_description()->description()
6141 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006142 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6143 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6144 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006145 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6146 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006147 }
6148 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006149 // The re-offers should respect the order of m= sections in current
6150 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006151 // With a re-offer, either the current local or current remote descriptions
6152 // could be the most up to date, so we would like to check against both of
6153 // them if they exist. It could be the case that one of them has a 0 port
6154 // for a media section, but the other does not. This is important to check
6155 // against in the case that we are recycling an m= section.
6156 const cricket::SessionDescription* current_desc = nullptr;
6157 const cricket::SessionDescription* secondary_current_desc = nullptr;
6158 if (local_description()) {
6159 current_desc = local_description()->description();
6160 if (remote_description()) {
6161 secondary_current_desc = remote_description()->description();
6162 }
6163 } else if (remote_description()) {
6164 current_desc = remote_description()->description();
6165 }
Steve Anton75737c02017-11-06 10:37:17 -08006166 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006167 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6168 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006169 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6170 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006171 }
6172 }
6173
Steve Antonba42e992018-04-09 14:10:01 -07006174 if (IsUnifiedPlan()) {
6175 // Ensure that each audio and video media section has at most one
6176 // "StreamParams". This will return an error if receiving a session
6177 // description from a "Plan B" endpoint which adds multiple tracks of the
6178 // same type. With Unified Plan, there can only be at most one track per
6179 // media section.
6180 for (const ContentInfo& content : sdesc->description()->contents()) {
6181 const MediaContentDescription& desc = *content.description;
6182 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6183 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6184 desc.streams().size() > 1u) {
6185 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6186 "Media section has more than one track specified "
6187 "with a=ssrc lines which is not supported with "
6188 "Unified Plan.");
6189 }
6190 }
6191 }
6192
Steve Anton8a006912017-12-04 15:25:56 -08006193 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006194}
6195
Steve Anton3828c062017-12-06 10:34:51 -08006196bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006197 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006198 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006199 return (state == PeerConnectionInterface::kStable) ||
6200 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006201 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006202 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006203 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6204 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6205 }
6206}
6207
Steve Anton3828c062017-12-06 10:34:51 -08006208bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006209 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006210 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006211 return (state == PeerConnectionInterface::kStable) ||
6212 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006213 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006214 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006215 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6216 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6217 }
6218}
6219
Steve Antonf8470812017-12-04 10:46:21 -08006220const char* PeerConnection::SessionErrorToString(SessionError error) const {
6221 switch (error) {
6222 case SessionError::kNone:
6223 return "ERROR_NONE";
6224 case SessionError::kContent:
6225 return "ERROR_CONTENT";
6226 case SessionError::kTransport:
6227 return "ERROR_TRANSPORT";
6228 }
6229 RTC_NOTREACHED();
6230 return "";
6231}
6232
Steve Anton75737c02017-11-06 10:37:17 -08006233std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006234 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006235 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6236 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006237 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006238}
6239
Steve Anton8e20f172018-03-06 10:55:04 -08006240void PeerConnection::ReportSdpFormatReceived(
6241 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006242 int num_audio_mlines = 0;
6243 int num_video_mlines = 0;
6244 int num_audio_tracks = 0;
6245 int num_video_tracks = 0;
6246 for (const ContentInfo& content : remote_offer.description()->contents()) {
6247 cricket::MediaType media_type = content.media_description()->type();
6248 int num_tracks = std::max(
6249 1, static_cast<int>(content.media_description()->streams().size()));
6250 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6251 num_audio_mlines += 1;
6252 num_audio_tracks += num_tracks;
6253 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6254 num_video_mlines += 1;
6255 num_video_tracks += num_tracks;
6256 }
6257 }
6258 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6259 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6260 format = kSdpFormatReceivedComplexUnifiedPlan;
6261 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6262 format = kSdpFormatReceivedComplexPlanB;
6263 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6264 format = kSdpFormatReceivedSimple;
6265 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006266 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6267 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006268}
6269
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006270void PeerConnection::NoteUsageEvent(UsageEvent event) {
6271 RTC_DCHECK_RUN_ON(signaling_thread());
6272 usage_event_accumulator_ |= static_cast<int>(event);
6273}
6274
6275void PeerConnection::ReportUsagePattern() const {
6276 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006277 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6278 usage_event_accumulator_,
6279 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006280 const int bad_bits =
6281 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6282 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6283 const int good_bits =
6284 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6285 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6286 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6287 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6288 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006289 // If called after close(), we can't report, because observer may have
6290 // been deallocated, and therefore pointer is null. Write to log instead.
6291 if (observer_) {
6292 Observer()->OnInterestingUsage(usage_event_accumulator_);
6293 } else {
6294 RTC_LOG(LS_INFO) << "Interesting usage signature "
6295 << usage_event_accumulator_
6296 << " observed after observer shutdown";
6297 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006298 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006299}
6300
Steve Anton0ffaaa22018-02-23 10:31:30 -08006301void PeerConnection::ReportNegotiatedSdpSemantics(
6302 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006303 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006304 switch (answer.description()->msid_signaling()) {
6305 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006306 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006307 break;
6308 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006309 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006310 break;
6311 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006312 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006313 break;
6314 case cricket::kMsidSignalingMediaSection |
6315 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006316 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006317 break;
6318 default:
6319 RTC_NOTREACHED();
6320 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006321 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6322 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006323}
6324
Steve Anton75737c02017-11-06 10:37:17 -08006325// We need to check the local/remote description for the Transport instead of
6326// the session, because a new Transport added during renegotiation may have
6327// them unset while the session has them set from the previous negotiation.
6328// Not doing so may trigger the auto generation of transport description and
6329// mess up DTLS identity information, ICE credential, etc.
6330bool PeerConnection::ReadyToUseRemoteCandidate(
6331 const IceCandidateInterface* candidate,
6332 const SessionDescriptionInterface* remote_desc,
6333 bool* valid) {
6334 *valid = true;
6335
6336 const SessionDescriptionInterface* current_remote_desc =
6337 remote_desc ? remote_desc : remote_description();
6338
6339 if (!current_remote_desc) {
6340 return false;
6341 }
6342
6343 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6344 size_t remote_content_size =
6345 current_remote_desc->description()->contents().size();
6346 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006347 RTC_LOG(LS_ERROR)
6348 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6349 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006350
6351 *valid = false;
6352 return false;
6353 }
6354
6355 cricket::ContentInfo content =
6356 current_remote_desc->description()->contents()[mediacontent_index];
6357
6358 const std::string transport_name = GetTransportName(content.name);
6359 if (transport_name.empty()) {
6360 return false;
6361 }
Zhi Huange830e682018-03-30 10:48:35 -07006362 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006363}
6364
6365bool PeerConnection::SrtpRequired() const {
6366 return dtls_enabled_ ||
6367 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6368}
6369
6370void PeerConnection::OnTransportControllerGatheringState(
6371 cricket::IceGatheringState state) {
6372 RTC_DCHECK(signaling_thread()->IsCurrent());
6373 if (state == cricket::kIceGatheringGathering) {
6374 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6375 } else if (state == cricket::kIceGatheringComplete) {
6376 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6377 }
6378}
6379
6380void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006381 std::map<std::string, std::set<cricket::MediaType>>
6382 media_types_by_transport_name;
6383 for (auto transceiver : transceivers_) {
6384 if (transceiver->internal()->channel()) {
6385 const std::string& transport_name =
6386 transceiver->internal()->channel()->transport_name();
6387 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006388 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006389 }
Steve Anton75737c02017-11-06 10:37:17 -08006390 }
6391 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006392 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6393 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006394 }
Zhi Huange830e682018-03-30 10:48:35 -07006395
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006396 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006397 if (transport_name) {
6398 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006399 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006400 }
Zhi Huange830e682018-03-30 10:48:35 -07006401
Steve Antonc7b964c2018-02-01 14:39:45 -08006402 for (const auto& entry : media_types_by_transport_name) {
6403 const std::string& transport_name = entry.first;
6404 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006405 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006406 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006407 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006408 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006409 }
6410 }
6411}
6412// Walk through the ConnectionInfos to gather best connection usage
6413// for IPv4 and IPv6.
6414void PeerConnection::ReportBestConnectionState(
6415 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006416 for (const cricket::TransportChannelStats& channel_stats :
6417 stats.channel_stats) {
6418 for (const cricket::ConnectionInfo& connection_info :
6419 channel_stats.connection_infos) {
6420 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006421 continue;
6422 }
6423
Steve Antonc7b964c2018-02-01 14:39:45 -08006424 const cricket::Candidate& local = connection_info.local_candidate;
6425 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006426
6427 // Increment the counter for IceCandidatePairType.
6428 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6429 (local.type() == RELAY_PORT_TYPE &&
6430 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006431 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6432 GetIceCandidatePairCounter(local, remote),
6433 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006434 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006435 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6436 GetIceCandidatePairCounter(local, remote),
6437 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006438 } else {
6439 RTC_CHECK(0);
6440 }
Steve Anton75737c02017-11-06 10:37:17 -08006441
6442 // Increment the counter for IP type.
6443 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6445 kBestConnections_IPv4,
6446 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006447 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006448 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6449 kBestConnections_IPv6,
6450 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006451 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006452 RTC_CHECK(!local.address().hostname().empty() &&
6453 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006454 }
6455
6456 return;
6457 }
6458 }
6459}
6460
6461void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006462 const cricket::TransportStats& stats,
6463 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006464 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6465 return;
6466 }
6467
6468 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6469 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6470 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6471 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6472 return;
6473 }
6474
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006475 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6476 for (cricket::MediaType media_type : media_types) {
6477 switch (media_type) {
6478 case cricket::MEDIA_TYPE_AUDIO:
6479 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6480 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6481 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6482 break;
6483 case cricket::MEDIA_TYPE_VIDEO:
6484 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6485 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6486 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6487 break;
6488 case cricket::MEDIA_TYPE_DATA:
6489 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6490 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6491 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6492 break;
6493 default:
6494 RTC_NOTREACHED();
6495 continue;
6496 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006497 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006498 }
6499
6500 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6501 for (cricket::MediaType media_type : media_types) {
6502 switch (media_type) {
6503 case cricket::MEDIA_TYPE_AUDIO:
6504 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6505 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6506 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6507 break;
6508 case cricket::MEDIA_TYPE_VIDEO:
6509 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6510 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6511 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6512 break;
6513 case cricket::MEDIA_TYPE_DATA:
6514 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6515 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6516 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6517 break;
6518 default:
6519 RTC_NOTREACHED();
6520 continue;
6521 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006522 }
Steve Anton75737c02017-11-06 10:37:17 -08006523 }
6524}
6525
6526void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6527 RTC_DCHECK(worker_thread()->IsCurrent());
6528 RTC_DCHECK(call_);
6529 call_->OnSentPacket(sent_packet);
6530}
6531
6532const std::string PeerConnection::GetTransportName(
6533 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006534 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006535 if (channel) {
6536 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006537 }
Steve Anton6fec8802017-12-04 10:37:29 -08006538 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006539 RTC_DCHECK(sctp_mid_);
6540 if (content_name == *sctp_mid_) {
6541 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006542 }
6543 }
6544 // Return an empty string if failed to retrieve the transport name.
6545 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006546}
6547
Steve Anton6fec8802017-12-04 10:37:29 -08006548void PeerConnection::DestroyTransceiverChannel(
6549 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6550 transceiver) {
6551 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006552
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006553 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006554 if (channel) {
6555 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006556 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006557 }
6558}
6559
6560void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006561 if (rtp_data_channel_) {
6562 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006563 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006564 rtp_data_channel_ = nullptr;
6565 }
6566
6567 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6568 // grab a reference to this PeerConnection. If this is called from the
6569 // PeerConnection destructor, the RefCountedObject vtable will have already
6570 // been destroyed (since it is a subclass of PeerConnection) and using
6571 // rtc::Bind will cause "Pure virtual function called" error to appear.
6572
6573 if (sctp_transport_) {
6574 OnDataChannelDestroyed();
6575 network_thread()->Invoke<void>(RTC_FROM_HERE,
6576 [this] { DestroySctpTransport_n(); });
6577 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006578
6579 if (media_transport_) {
6580 OnDataChannelDestroyed();
6581 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6582 RTC_DCHECK_RUN_ON(network_thread());
6583 TeardownMediaTransportForDataChannels_n();
6584 });
6585 }
Steve Anton6fec8802017-12-04 10:37:29 -08006586}
6587
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006588void PeerConnection::DestroyChannelInterface(
6589 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006590 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006591 switch (channel->media_type()) {
6592 case cricket::MEDIA_TYPE_AUDIO:
6593 channel_manager()->DestroyVoiceChannel(
6594 static_cast<cricket::VoiceChannel*>(channel));
6595 break;
6596 case cricket::MEDIA_TYPE_VIDEO:
6597 channel_manager()->DestroyVideoChannel(
6598 static_cast<cricket::VideoChannel*>(channel));
6599 break;
6600 case cricket::MEDIA_TYPE_DATA:
6601 channel_manager()->DestroyRtpDataChannel(
6602 static_cast<cricket::RtpDataChannel*>(channel));
6603 break;
6604 default:
6605 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6606 break;
6607 }
Zhi Huange830e682018-03-30 10:48:35 -07006608}
Steve Anton6fec8802017-12-04 10:37:29 -08006609
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006610bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006611 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006612 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006613 cricket::DtlsTransportInternal* dtls_transport,
6614 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006615 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006616 auto base_channel = GetChannel(mid);
6617 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006618 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006619 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006620 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006621 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006622 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006623
6624 call_->MediaTransportChange(media_transport);
6625
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006626 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006627}
6628
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006629PeerConnectionObserver* PeerConnection::Observer() const {
6630 // In earlier production code, the pointer was not cleared on close,
6631 // which might have led to undefined behavior if the observer was not
6632 // deallocated, or strange crashes if it was.
6633 // We use CHECK in order to catch such behavior if it exists.
6634 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6635 RTC_CHECK(observer_);
6636 return observer_;
6637}
6638
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006639CryptoOptions PeerConnection::GetCryptoOptions() {
6640 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6641 // after it has been removed.
6642 return configuration_.crypto_options.has_value()
6643 ? *configuration_.crypto_options
6644 : factory_->options().crypto_options;
6645}
6646
Harald Alvestrand89061872018-01-02 14:08:34 +01006647void PeerConnection::ClearStatsCache() {
6648 if (stats_collector_) {
6649 stats_collector_->ClearCachedStatsReport();
6650 }
6651}
6652
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006653void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006654 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6655 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006656}
6657
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006658} // namespace webrtc