blob: 3c5a025f22aacf060705da50ab5d664e09ddc70a [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 10:37:17 -0800342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800389}
390
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100417
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100424 }
425}
426
Harald Alvestrand76829d72018-07-18 23:24:36 +0200427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 10:37:17 -0800432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800443 continue;
444 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800479 }
480 }
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 continue;
494 }
Steve Anton8a006912017-12-04 15:25:56 -0800495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800515 return false;
516 }
517 }
518 return true;
519}
520
521bool GetTrackIdBySsrc(const SessionDescription* session_description,
522 uint32_t ssrc,
523 std::string* track_id) {
524 RTC_DCHECK(track_id != NULL);
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::AudioContentDescription* audio_desc =
527 cricket::GetFirstAudioContentDescription(session_description);
528 if (audio_desc) {
529 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535
Steve Antonb1c1de12017-12-21 15:14:30 -0800536 const cricket::VideoContentDescription* video_desc =
537 cricket::GetFirstVideoContentDescription(session_description);
538 if (video_desc) {
539 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800540 if (found) {
541 *track_id = found->id;
542 return true;
543 }
544 }
545 return false;
546}
547
548// Get the SCTP port out of a SessionDescription.
549// Return -1 if not found.
550int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800551 const cricket::DataContentDescription* data_desc =
552 GetFirstDataContentDescription(session_description);
553 RTC_DCHECK(data_desc);
554 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800555 return -1;
556 }
Steve Anton75737c02017-11-06 10:37:17 -0800557 std::string value;
558 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
559 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800560 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800561 if (!codec.Matches(match_pattern)) {
562 continue;
563 }
564 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
565 return rtc::FromString<int>(value);
566 }
567 }
568 return -1;
569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Steve Anton75737c02017-11-06 10:37:17 -0800634} // namespace
635
Henrik Boström31638672017-11-23 17:48:32 +0100636// Upon completion, posts a task to execute the callback of the
637// SetSessionDescriptionObserver asynchronously on the same thread. At this
638// point, the state of the peer connection might no longer reflect the effects
639// of the SetRemoteDescription operation, as the peer connection could have been
640// modified during the post.
641// TODO(hbos): Remove this class once we remove the version of
642// PeerConnectionInterface::SetRemoteDescription() that takes a
643// SetSessionDescriptionObserver as an argument.
644class PeerConnection::SetRemoteDescriptionObserverAdapter
645 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
646 public:
647 SetRemoteDescriptionObserverAdapter(
648 rtc::scoped_refptr<PeerConnection> pc,
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
650 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
651
652 // SetRemoteDescriptionObserverInterface implementation.
653 void OnSetRemoteDescriptionComplete(RTCError error) override {
654 if (error.ok())
655 pc_->PostSetSessionDescriptionSuccess(wrapper_);
656 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100657 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100658 }
659
660 private:
661 rtc::scoped_refptr<PeerConnection> pc_;
662 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
663};
664
deadbeef293e9262017-01-11 12:28:30 -0800665bool PeerConnectionInterface::RTCConfiguration::operator==(
666 const PeerConnectionInterface::RTCConfiguration& o) const {
667 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700668 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800669 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000670 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700671 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800672 BundlePolicy bundle_policy;
673 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700674 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
675 int ice_candidate_pool_size;
676 bool disable_ipv6;
677 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700678 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100679 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700680 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200681 absl::optional<int> screencast_min_bitrate;
682 absl::optional<bool> combined_audio_video_bwe;
683 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800684 TcpCandidatePolicy tcp_candidate_policy;
685 CandidateNetworkPolicy candidate_network_policy;
686 int audio_jitter_buffer_max_packets;
687 bool audio_jitter_buffer_fast_accelerate;
688 int ice_connection_receiving_timeout;
689 int ice_backup_candidate_pair_ping_interval;
690 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800691 bool prioritize_most_likely_ice_candidate_pairs;
692 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800693 bool prune_turn_ports;
694 bool presume_writable_when_fully_relayed;
695 bool enable_ice_renomination;
696 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200697 absl::optional<int> ice_check_interval_strong_connectivity;
698 absl::optional<int> ice_check_interval_weak_connectivity;
699 absl::optional<int> ice_check_min_interval;
700 absl::optional<int> ice_unwritable_timeout;
701 absl::optional<int> ice_unwritable_min_checks;
702 absl::optional<int> stun_candidate_keepalive_interval;
703 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200704 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800705 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200706 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700707 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700708 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700709 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700710 absl::optional<CryptoOptions> crypto_options;
deadbeef293e9262017-01-11 12:28:30 -0800711 };
712 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
713 "Did you add something to RTCConfiguration and forget to "
714 "update operator==?");
715 return type == o.type && servers == o.servers &&
716 bundle_policy == o.bundle_policy &&
717 rtcp_mux_policy == o.rtcp_mux_policy &&
718 tcp_candidate_policy == o.tcp_candidate_policy &&
719 candidate_network_policy == o.candidate_network_policy &&
720 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
721 audio_jitter_buffer_fast_accelerate ==
722 o.audio_jitter_buffer_fast_accelerate &&
723 ice_connection_receiving_timeout ==
724 o.ice_connection_receiving_timeout &&
725 ice_backup_candidate_pair_ping_interval ==
726 o.ice_backup_candidate_pair_ping_interval &&
727 continual_gathering_policy == o.continual_gathering_policy &&
728 certificates == o.certificates &&
729 prioritize_most_likely_ice_candidate_pairs ==
730 o.prioritize_most_likely_ice_candidate_pairs &&
731 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800732 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700733 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100734 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800735 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800736 screencast_min_bitrate == o.screencast_min_bitrate &&
737 combined_audio_video_bwe == o.combined_audio_video_bwe &&
738 enable_dtls_srtp == o.enable_dtls_srtp &&
739 ice_candidate_pool_size == o.ice_candidate_pool_size &&
740 prune_turn_ports == o.prune_turn_ports &&
741 presume_writable_when_fully_relayed ==
742 o.presume_writable_when_fully_relayed &&
743 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800744 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800745 ice_check_interval_strong_connectivity ==
746 o.ice_check_interval_strong_connectivity &&
747 ice_check_interval_weak_connectivity ==
748 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700749 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700750 ice_unwritable_timeout == o.ice_unwritable_timeout &&
751 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800752 stun_candidate_keepalive_interval ==
753 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200754 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800755 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800756 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700757 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700758 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700759 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700760 use_media_transport_for_data_channels ==
761 o.use_media_transport_for_data_channels &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700762 crypto_options == o.crypto_options;
deadbeef293e9262017-01-11 12:28:30 -0800763}
764
765bool PeerConnectionInterface::RTCConfiguration::operator!=(
766 const PeerConnectionInterface::RTCConfiguration& o) const {
767 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800768}
769
zhihuang8f65cdf2016-05-06 18:40:30 -0700770// Generate a RTCP CNAME when a PeerConnection is created.
771std::string GenerateRtcpCname() {
772 std::string cname;
773 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100774 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800775 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700776 }
777 return cname;
778}
779
zhihuang1c378ed2017-08-17 14:10:50 -0700780bool ValidateOfferAnswerOptions(
781 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
782 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
783 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700784}
785
zhihuang1c378ed2017-08-17 14:10:50 -0700786// From |rtc_options|, fill parts of |session_options| shared by all generated
787// m= sections (in other words, nothing that involves a map/array).
788void ExtractSharedMediaSessionOptions(
789 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
790 cricket::MediaSessionOptions* session_options) {
791 session_options->vad_enabled = rtc_options.voice_activity_detection;
792 session_options->bundle_enabled = rtc_options.use_rtp_mux;
793}
zhihuanga77e6bb2017-08-14 18:17:48 -0700794
zhihuang38ede132017-06-15 12:52:32 -0700795PeerConnection::PeerConnection(PeerConnectionFactory* factory,
796 std::unique_ptr<RtcEventLog> event_log,
797 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000798 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700799 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700800 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700801 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700802 remote_streams_(StreamCollection::Create()),
803 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000804
805PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100806 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800807 RTC_DCHECK_RUN_ON(signaling_thread());
808
Steve Anton8af21862017-12-15 11:20:13 -0800809 // Need to stop transceivers before destroying the stats collector because
810 // AudioRtpSender has a reference to the StatsCollector it will update when
811 // stopping.
812 for (auto transceiver : transceivers_) {
813 transceiver->Stop();
814 }
Steve Anton4171afb2017-11-20 10:20:22 -0800815
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700816 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800817 if (stats_collector_) {
818 stats_collector_->WaitForPendingRequest();
819 stats_collector_ = nullptr;
820 }
Steve Anton75737c02017-11-06 10:37:17 -0800821
Steve Anton8af21862017-12-15 11:20:13 -0800822 // Don't destroy BaseChannels until after stats has been cleaned up so that
823 // the last stats request can still read from the channels.
824 DestroyAllChannels();
825
Mirko Bonadei675513b2017-11-09 11:09:25 +0100826 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800827
828 webrtc_session_desc_factory_.reset();
829 sctp_invoker_.reset();
830 sctp_factory_.reset();
831 transport_controller_.reset();
832
deadbeef91dd5672016-05-18 16:55:30 -0700833 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700834 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700835 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700836 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700837 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700838 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800839 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700840 event_log_.reset();
841 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842}
843
Steve Anton8af21862017-12-15 11:20:13 -0800844void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800845 // Destroy video channels first since they may have a pointer to a voice
846 // channel.
847 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800848 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800849 DestroyTransceiverChannel(transceiver);
850 }
851 }
852 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800853 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800854 DestroyTransceiverChannel(transceiver);
855 }
856 }
857 DestroyDataChannel();
858}
859
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000861 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700862 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100863 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700864
865 RTCError config_error = ValidateConfiguration(configuration);
866 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100867 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700868 return false;
869 }
870
Benjamin Wrightcab58882018-05-02 15:12:47 -0700871 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100872 RTC_LOG(LS_ERROR)
873 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100874 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800875 return false;
876 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200877
Benjamin Wrightcab58882018-05-02 15:12:47 -0700878 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800879 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100880 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100881 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800882 return false;
883 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700884
Benjamin Wrightcab58882018-05-02 15:12:47 -0700885 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700886 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700887 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700888 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800889
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200890 cricket::ServerAddresses stun_servers;
891 std::vector<cricket::RelayServerConfig> turn_servers;
892
893 RTCErrorType parse_error =
894 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
895 if (parse_error != RTCErrorType::NONE) {
896 return false;
897 }
898
deadbeef91dd5672016-05-18 16:55:30 -0700899 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700900 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700901 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200902 RTC_FROM_HERE,
903 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
904 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905 return false;
906 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200907 // If initialization was successful, note if STUN or TURN servers
908 // were supplied.
909 if (!stun_servers.empty()) {
910 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
911 }
912 if (!turn_servers.empty()) {
913 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
914 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700916 // Send information about IPv4/IPv6 status.
917 PeerConnectionAddressFamilyCounter address_family;
918 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
919 address_family = kPeerConnection_IPv6;
920 } else {
921 address_family = kPeerConnection_IPv4;
922 }
923 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
924 kPeerConnectionAddressFamilyCounter_Max);
925
Zhi Huange830e682018-03-30 10:48:35 -0700926 const PeerConnectionFactoryInterface::Options& options = factory_->options();
927
Steve Anton75737c02017-11-06 10:37:17 -0800928 // RFC 3264: The numeric value of the session id and version in the
929 // o line MUST be representable with a "64 bit signed integer".
930 // Due to this constraint session id |session_id_| is max limited to
931 // LLONG_MAX.
932 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700933 JsepTransportController::Config config;
934 config.redetermine_role_on_ice_restart =
935 configuration.redetermine_role_on_ice_restart;
936 config.ssl_max_version = factory_->options().ssl_max_version;
937 config.disable_encryption = options.disable_encryption;
938 config.bundle_policy = configuration.bundle_policy;
939 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700940 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
941 // stub.
942 config.crypto_options = configuration.crypto_options.has_value()
943 ? *configuration.crypto_options
944 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700945 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700946 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700947#if defined(ENABLE_EXTERNAL_AUTH)
948 config.enable_external_auth = true;
949#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700950 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700951
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700952 if (configuration.use_media_transport ||
953 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700954 if (!factory_->media_transport_factory()) {
955 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700956 << "PeerConnecton is initialized with use_media_transport = true or "
957 << "use_media_transport_for_data_channels = true "
958 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700959 return false;
960 }
961
962 config.media_transport_factory = factory_->media_transport_factory();
963 }
964
Zhi Huange830e682018-03-30 10:48:35 -0700965 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700966 signaling_thread(), network_thread(), port_allocator_.get(),
967 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700968 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800969 this, &PeerConnection::OnTransportControllerConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +0200970 transport_controller_->SignalStandardizedIceConnectionState.connect(
971 this, &PeerConnection::SetStandardizedIceConnectionState);
972 transport_controller_->SignalConnectionState.connect(
973 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700974 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800975 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700976 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800977 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700978 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800979 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
980 transport_controller_->SignalDtlsHandshakeError.connect(
981 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
982
983 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700984
deadbeefab9b2d12015-10-14 11:33:11 -0700985 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700986 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000987
Steve Antonba818672017-11-06 10:21:57 -0800988 configuration_ = configuration;
989
Steve Anton75737c02017-11-06 10:37:17 -0800990 // Obtain a certificate from RTCConfiguration if any were provided (optional).
991 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
992 if (!configuration.certificates.empty()) {
993 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
994 // just picking the first one. The decision should be made based on the DTLS
995 // handshake. The DTLS negotiations need to know about all certificates.
996 certificate = configuration.certificates[0];
997 }
998
Steve Antond25da372017-11-06 14:50:29 -0800999 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001000
1001 if (options.disable_encryption) {
1002 dtls_enabled_ = false;
1003 } else {
1004 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001005 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001006 // |configuration| can override the default |dtls_enabled_| value.
1007 if (configuration.enable_dtls_srtp) {
1008 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1009 }
1010 }
1011
1012 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
1013 // It takes precendence over the disable_sctp_data_channels
1014 // PeerConnectionFactoryInterface::Options.
1015 if (configuration.enable_rtp_data_channel) {
1016 data_channel_type_ = cricket::DCT_RTP;
1017 } else {
1018 // DTLS has to be enabled to use SCTP.
1019 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1020 data_channel_type_ = cricket::DCT_SCTP;
1021 }
1022 }
1023
1024 video_options_.screencast_min_bitrate_kbps =
1025 configuration.screencast_min_bitrate;
1026 audio_options_.combined_audio_video_bwe =
1027 configuration.combined_audio_video_bwe;
1028
1029 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001030 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001031
1032 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001033 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001034
1035 // Whether the certificate generator/certificate is null or not determines
1036 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1037 // the right instructions by clearing the variables if needed.
1038 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001039 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001040 certificate = nullptr;
1041 } else if (certificate) {
1042 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001043 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001044 }
1045
1046 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1047 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001048 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001049 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1050 this, &PeerConnection::OnCertificateReady);
1051
1052 if (options.disable_encryption) {
1053 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1054 }
1055
1056 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001057 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001058
Steve Anton4171afb2017-11-20 10:20:22 -08001059 // Add default audio/video transceivers for Plan B SDP.
1060 if (!IsUnifiedPlan()) {
1061 transceivers_.push_back(
1062 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1063 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1064 transceivers_.push_back(
1065 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1066 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1067 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001068 int delay_ms =
1069 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001070 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1071 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001072 return true;
1073}
1074
Steve Anton038834f2017-07-14 15:59:59 -07001075RTCError PeerConnection::ValidateConfiguration(
1076 const RTCConfiguration& config) const {
1077 if (config.ice_regather_interval_range &&
1078 config.continual_gathering_policy == GATHER_ONCE) {
1079 return RTCError(RTCErrorType::INVALID_PARAMETER,
1080 "ice_regather_interval_range specified but continual "
1081 "gathering policy is GATHER_ONCE");
1082 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001083 auto result =
1084 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1085 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001086}
1087
Yves Gerey665174f2018-06-19 15:03:05 +02001088rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001089 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1090 "Plan SdpSemantics. Please use GetSenders "
1091 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001092 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001093}
1094
Yves Gerey665174f2018-06-19 15:03:05 +02001095rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001096 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1097 "Plan SdpSemantics. Please use GetReceivers "
1098 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001099 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100}
1101
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001102bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001103 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1104 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001105 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001106 if (IsClosed()) {
1107 return false;
1108 }
deadbeefab9b2d12015-10-14 11:33:11 -07001109 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 return false;
1111 }
deadbeefab9b2d12015-10-14 11:33:11 -07001112
1113 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001114 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1115 observer->SignalAudioTrackAdded.connect(this,
1116 &PeerConnection::OnAudioTrackAdded);
1117 observer->SignalAudioTrackRemoved.connect(
1118 this, &PeerConnection::OnAudioTrackRemoved);
1119 observer->SignalVideoTrackAdded.connect(this,
1120 &PeerConnection::OnVideoTrackAdded);
1121 observer->SignalVideoTrackRemoved.connect(
1122 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001123 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001124
deadbeefab9b2d12015-10-14 11:33:11 -07001125 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001126 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001127 }
1128 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001129 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001130 }
1131
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001132 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001133 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001134 return true;
1135}
1136
1137void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001138 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1139 "Plan SdpSemantics. Please use RemoveTrack "
1140 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001141 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001142 if (!IsClosed()) {
1143 for (const auto& track : local_stream->GetAudioTracks()) {
1144 RemoveAudioTrack(track.get(), local_stream);
1145 }
1146 for (const auto& track : local_stream->GetVideoTracks()) {
1147 RemoveVideoTrack(track.get(), local_stream);
1148 }
deadbeefab9b2d12015-10-14 11:33:11 -07001149 }
deadbeefab9b2d12015-10-14 11:33:11 -07001150 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001151 stream_observers_.erase(
1152 std::remove_if(
1153 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001154 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001155 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001156 }),
1157 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001158
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001159 if (IsClosed()) {
1160 return;
1161 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001162 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163}
1164
Steve Anton2d6c76a2018-01-05 17:10:52 -08001165RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001166 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001167 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001168 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001169 if (!track) {
1170 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1171 }
1172 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1173 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1174 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1175 "Track has invalid kind: " + track->kind());
1176 }
Steve Antonf9381f02017-12-14 10:23:57 -08001177 if (IsClosed()) {
1178 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1179 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001180 }
Steve Anton4171afb2017-11-20 10:20:22 -08001181 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001182 LOG_AND_RETURN_ERROR(
1183 RTCErrorType::INVALID_PARAMETER,
1184 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001185 }
Steve Antonf9381f02017-12-14 10:23:57 -08001186 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001187 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1188 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001189 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001190 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001191 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001192 }
1193 return sender_or_error;
1194}
deadbeefe1f9d832016-01-14 15:35:42 -08001195
Steve Antonf9381f02017-12-14 10:23:57 -08001196RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1197PeerConnection::AddTrackPlanB(
1198 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001199 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001200 if (stream_ids.size() > 1u) {
1201 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1202 "AddTrack with more than one stream is not "
1203 "supported with Plan B semantics.");
1204 }
1205 std::vector<std::string> adjusted_stream_ids = stream_ids;
1206 if (adjusted_stream_ids.empty()) {
1207 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1208 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001209 cricket::MediaType media_type =
1210 (track->kind() == MediaStreamTrackInterface::kAudioKind
1211 ? cricket::MEDIA_TYPE_AUDIO
1212 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001213 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001214 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001215 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001216 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001217 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001218 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001219 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001220 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001221 if (sender_info) {
1222 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Antonf9381f02017-12-14 10:23:57 -08001224 } else {
1225 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001226 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001227 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001228 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001229 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001230 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001231 if (sender_info) {
1232 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001233 }
deadbeefe1f9d832016-01-14 15:35:42 -08001234 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001235 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001236}
deadbeefe1f9d832016-01-14 15:35:42 -08001237
Steve Antonf9381f02017-12-14 10:23:57 -08001238RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1239PeerConnection::AddTrackUnifiedPlan(
1240 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001241 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001242 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1243 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001244 RTC_LOG(LS_INFO) << "Reusing an existing "
1245 << cricket::MediaTypeToString(transceiver->media_type())
1246 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001247 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001248 transceiver->internal()->set_direction(
1249 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001250 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001251 transceiver->internal()->set_direction(
1252 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001253 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001254 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001255 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001256 } else {
1257 cricket::MediaType media_type =
1258 (track->kind() == MediaStreamTrackInterface::kAudioKind
1259 ? cricket::MEDIA_TYPE_AUDIO
1260 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001261 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1262 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001263 std::string sender_id = track->id();
1264 // Avoid creating a sender with an existing ID by generating a random ID.
1265 // This can happen if this is the second time AddTrack has created a sender
1266 // for this track.
1267 if (FindSenderById(sender_id)) {
1268 sender_id = rtc::CreateRandomUuid();
1269 }
Florent Castelli892acf02018-10-01 22:47:20 +02001270 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001271 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1272 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001273 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001274 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001275 }
Steve Antonf9381f02017-12-14 10:23:57 -08001276 return transceiver->sender();
1277}
1278
1279rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1280PeerConnection::FindFirstTransceiverForAddedTrack(
1281 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1282 RTC_DCHECK(track);
1283 for (auto transceiver : transceivers_) {
1284 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001285 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001286 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001287 !transceiver->internal()->has_ever_been_used_to_send() &&
1288 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001289 return transceiver;
1290 }
1291 }
1292 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001293}
1294
1295bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1296 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001297 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001298}
1299
Steve Anton24db5732018-07-23 10:27:33 -07001300RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001301 rtc::scoped_refptr<RtpSenderInterface> sender) {
1302 if (!sender) {
1303 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1304 }
deadbeefe1f9d832016-01-14 15:35:42 -08001305 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001306 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1307 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001308 }
Steve Antonf9381f02017-12-14 10:23:57 -08001309 if (IsUnifiedPlan()) {
1310 auto transceiver = FindTransceiverBySender(sender);
1311 if (!transceiver || !sender->track()) {
1312 return RTCError::OK();
1313 }
1314 sender->SetTrack(nullptr);
1315 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001316 transceiver->internal()->set_direction(
1317 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001318 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001319 transceiver->internal()->set_direction(
1320 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001321 }
Steve Anton4171afb2017-11-20 10:20:22 -08001322 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001323 bool removed;
1324 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1325 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1326 } else {
1327 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1328 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1329 }
1330 if (!removed) {
1331 LOG_AND_RETURN_ERROR(
1332 RTCErrorType::INVALID_PARAMETER,
1333 "Couldn't find sender " + sender->id() + " to remove.");
1334 }
Steve Anton4171afb2017-11-20 10:20:22 -08001335 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001336 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001337 return RTCError::OK();
1338}
1339
1340rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1341PeerConnection::FindTransceiverBySender(
1342 rtc::scoped_refptr<RtpSenderInterface> sender) {
1343 for (auto transceiver : transceivers_) {
1344 if (transceiver->sender() == sender) {
1345 return transceiver;
1346 }
1347 }
1348 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001349}
1350
Steve Anton9158ef62017-11-27 13:01:52 -08001351RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1352PeerConnection::AddTransceiver(
1353 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1354 return AddTransceiver(track, RtpTransceiverInit());
1355}
1356
1357RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1358PeerConnection::AddTransceiver(
1359 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1360 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001361 RTC_CHECK(IsUnifiedPlan())
1362 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001363 if (!track) {
1364 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1365 }
1366 cricket::MediaType media_type;
1367 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1368 media_type = cricket::MEDIA_TYPE_AUDIO;
1369 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1370 media_type = cricket::MEDIA_TYPE_VIDEO;
1371 } else {
1372 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1373 "Track kind is not audio or video");
1374 }
1375 return AddTransceiver(media_type, track, init);
1376}
1377
1378RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1379PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1380 return AddTransceiver(media_type, RtpTransceiverInit());
1381}
1382
1383RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1384PeerConnection::AddTransceiver(cricket::MediaType media_type,
1385 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001386 RTC_CHECK(IsUnifiedPlan())
1387 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001388 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1389 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1390 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1391 "media type is not audio or video");
1392 }
1393 return AddTransceiver(media_type, nullptr, init);
1394}
1395
1396RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1397PeerConnection::AddTransceiver(
1398 cricket::MediaType media_type,
1399 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001400 const RtpTransceiverInit& init,
1401 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001402 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1403 media_type == cricket::MEDIA_TYPE_VIDEO));
1404 if (track) {
1405 RTC_DCHECK_EQ(media_type,
1406 (track->kind() == MediaStreamTrackInterface::kAudioKind
1407 ? cricket::MEDIA_TYPE_AUDIO
1408 : cricket::MEDIA_TYPE_VIDEO));
1409 }
1410
1411 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001412 if (init.send_encodings.size() > 1) {
1413 LOG_AND_RETURN_ERROR(
1414 RTCErrorType::UNSUPPORTED_PARAMETER,
1415 "Attempted to create an encoder with more than 1 encoding parameter.");
1416 }
1417
1418 for (const auto& encoding : init.send_encodings) {
1419 if (encoding.ssrc.has_value()) {
1420 LOG_AND_RETURN_ERROR(
1421 RTCErrorType::UNSUPPORTED_PARAMETER,
1422 "Attempted to set an unimplemented parameter of RtpParameters.");
1423 }
1424 }
1425
1426 RtpParameters parameters;
1427 parameters.encodings = init.send_encodings;
1428 if (UnimplementedRtpParameterHasValue(parameters)) {
1429 LOG_AND_RETURN_ERROR(
1430 RTCErrorType::UNSUPPORTED_PARAMETER,
1431 "Attempted to set an unimplemented parameter of RtpParameters.");
1432 }
Steve Anton9158ef62017-11-27 13:01:52 -08001433
Steve Anton3d954a62018-04-02 11:27:23 -07001434 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1435 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001436 // Set the sender ID equal to the track ID if the track is specified unless
1437 // that sender ID is already in use.
1438 std::string sender_id =
1439 (track && !FindSenderById(track->id()) ? track->id()
1440 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001441 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1442 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001443 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1444 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1445 transceiver->internal()->set_direction(init.direction);
1446
Steve Anton22da89f2018-01-25 13:58:07 -08001447 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001448 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001449 }
Steve Antonf9381f02017-12-14 10:23:57 -08001450
1451 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1452}
1453
Steve Anton02ee47c2018-01-10 16:26:06 -08001454rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1455PeerConnection::CreateSender(
1456 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001457 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001458 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001459 const std::vector<std::string>& stream_ids,
1460 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001461 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001462 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1463 RTC_DCHECK(!track ||
1464 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1465 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1466 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001467 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001468 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001469 } else {
1470 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1471 RTC_DCHECK(!track ||
1472 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1473 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001474 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001475 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001476 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001477 bool set_track_succeeded = sender->SetTrack(track);
1478 RTC_DCHECK(set_track_succeeded);
1479 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001480 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001481 return sender;
1482}
1483
1484rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1485PeerConnection::CreateReceiver(cricket::MediaType media_type,
1486 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001487 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1488 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001489 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001490 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001491 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1492 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001493 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001494 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001495 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001496 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001497 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1498 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001499 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001500 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001501 return receiver;
1502}
1503
1504rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1505PeerConnection::CreateAndAddTransceiver(
1506 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1507 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1508 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001509 // Ensure that the new sender does not have an ID that is already in use by
1510 // another sender.
1511 // Allow receiver IDs to conflict since those come from remote SDP (which
1512 // could be invalid, but should not cause a crash).
1513 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001514 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1515 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001516 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001517 transceiver->internal()->SignalNegotiationNeeded.connect(
1518 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001519 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001520}
1521
Steve Anton52d86772018-02-20 15:48:12 -08001522void PeerConnection::OnNegotiationNeeded() {
1523 RTC_DCHECK_RUN_ON(signaling_thread());
1524 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001525 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001526}
1527
deadbeeffac06552015-11-25 11:26:01 -08001528rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001529 const std::string& kind,
1530 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001531 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1532 "Plan SdpSemantics. Please use AddTransceiver "
1533 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001534 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001535 if (IsClosed()) {
1536 return nullptr;
1537 }
Steve Anton4171afb2017-11-20 10:20:22 -08001538
Seth Hampson5b4f0752018-04-02 16:31:36 -07001539 // Internally we need to have one stream with Plan B semantics, so we
1540 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001541 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001542 if (stream_id.empty()) {
1543 stream_ids.push_back(rtc::CreateRandomUuid());
1544 RTC_LOG(LS_INFO)
1545 << "No stream_id specified for sender. Generated stream ID: "
1546 << stream_ids[0];
1547 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001548 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001549 }
1550
Steve Anton4171afb2017-11-20 10:20:22 -08001551 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001552 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001553 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001554 auto* audio_sender = new AudioRtpSender(
1555 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001556 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001557 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001558 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001559 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001560 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001561 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001562 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001563 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001564 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001565 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001566 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001567 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001568 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001569 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001570 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001571 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001572
deadbeefe1f9d832016-01-14 15:35:42 -08001573 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001574}
1575
deadbeef70ab1a12015-09-28 16:53:55 -07001576std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1577 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001578 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001579 for (auto sender : GetSendersInternal()) {
1580 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001581 }
1582 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001583}
1584
Steve Anton4171afb2017-11-20 10:20:22 -08001585std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1586PeerConnection::GetSendersInternal() const {
1587 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1588 all_senders;
1589 for (auto transceiver : transceivers_) {
1590 auto senders = transceiver->internal()->senders();
1591 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1592 }
1593 return all_senders;
1594}
1595
deadbeef70ab1a12015-09-28 16:53:55 -07001596std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1597PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001598 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001599 for (const auto& receiver : GetReceiversInternal()) {
1600 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001601 }
1602 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001603}
1604
Steve Anton4171afb2017-11-20 10:20:22 -08001605std::vector<
1606 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1607PeerConnection::GetReceiversInternal() const {
1608 std::vector<
1609 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1610 all_receivers;
1611 for (auto transceiver : transceivers_) {
1612 auto receivers = transceiver->internal()->receivers();
1613 all_receivers.insert(all_receivers.end(), receivers.begin(),
1614 receivers.end());
1615 }
1616 return all_receivers;
1617}
1618
Steve Anton9158ef62017-11-27 13:01:52 -08001619std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1620PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001621 RTC_CHECK(IsUnifiedPlan())
1622 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001623 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1624 for (auto transceiver : transceivers_) {
1625 all_transceivers.push_back(transceiver);
1626 }
1627 return all_transceivers;
1628}
1629
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001631 MediaStreamTrackInterface* track,
1632 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001633 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001634 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001635 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001636 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001637 return false;
1638 }
1639
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001640 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001641 // The StatsCollector is used to tell if a track is valid because it may
1642 // remember tracks that the PeerConnection previously removed.
1643 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001644 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1645 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001646 return false;
1647 }
Steve Antonad182762018-09-05 20:22:40 +00001648 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1649 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001650 return true;
1651}
1652
hbos74e1a4f2016-09-15 23:33:01 -07001653void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001654 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001655 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001656 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001657 stats_collector_->GetStatsReport(callback);
1658}
1659
Henrik Boström1df1bf82018-03-20 13:24:20 +01001660void PeerConnection::GetStats(
1661 rtc::scoped_refptr<RtpSenderInterface> selector,
1662 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1663 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1664 RTC_DCHECK(callback);
1665 RTC_DCHECK(stats_collector_);
1666 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1667 if (selector) {
1668 for (const auto& proxy_transceiver : transceivers_) {
1669 for (const auto& proxy_sender :
1670 proxy_transceiver->internal()->senders()) {
1671 if (proxy_sender == selector) {
1672 internal_sender = proxy_sender->internal();
1673 break;
1674 }
1675 }
1676 if (internal_sender)
1677 break;
1678 }
1679 }
1680 // If there is no |internal_sender| then |selector| is either null or does not
1681 // belong to the PeerConnection (in Plan B, senders can be removed from the
1682 // PeerConnection). This means that "all the stats objects representing the
1683 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1684 // produces an empty stats report.
1685 stats_collector_->GetStatsReport(internal_sender, callback);
1686}
1687
1688void PeerConnection::GetStats(
1689 rtc::scoped_refptr<RtpReceiverInterface> 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<RtpReceiverInternal> internal_receiver;
1695 if (selector) {
1696 for (const auto& proxy_transceiver : transceivers_) {
1697 for (const auto& proxy_receiver :
1698 proxy_transceiver->internal()->receivers()) {
1699 if (proxy_receiver == selector) {
1700 internal_receiver = proxy_receiver->internal();
1701 break;
1702 }
1703 }
1704 if (internal_receiver)
1705 break;
1706 }
1707 }
1708 // If there is no |internal_receiver| then |selector| is either null or does
1709 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1710 // the PeerConnection). This means that "all the stats objects representing
1711 // the selector" is an empty set. Invoking GetStatsReport() with a null
1712 // selector produces an empty stats report.
1713 stats_collector_->GetStatsReport(internal_receiver, callback);
1714}
1715
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1717 return signaling_state_;
1718}
1719
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001720PeerConnectionInterface::IceConnectionState
1721PeerConnection::ice_connection_state() {
1722 return ice_connection_state_;
1723}
1724
Jonas Olsson635474e2018-10-18 15:58:17 +02001725PeerConnectionInterface::IceConnectionState
1726PeerConnection::standardized_ice_connection_state() {
1727 return standardized_ice_connection_state_;
1728}
1729
1730PeerConnectionInterface::PeerConnectionState
1731PeerConnection::peer_connection_state() {
1732 return connection_state_;
1733}
1734
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001735PeerConnectionInterface::IceGatheringState
1736PeerConnection::ice_gathering_state() {
1737 return ice_gathering_state_;
1738}
1739
Yves Gerey665174f2018-06-19 15:03:05 +02001740rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001741 const std::string& label,
1742 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001743 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001744
deadbeefab9b2d12015-10-14 11:33:11 -07001745 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001746
kwibergd1fe2812016-04-27 06:47:29 -07001747 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001748 if (config) {
1749 internal_config.reset(new InternalDataChannelInit(*config));
1750 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001751 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001752 InternalCreateDataChannel(label, internal_config.get()));
1753 if (!channel.get()) {
1754 return nullptr;
1755 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001756
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001757 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1758 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001759 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001760 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001761 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001762 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001763 return DataChannelProxy::Create(signaling_thread(), channel.get());
1764}
1765
1766void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001767 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001768 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001769
nisse7ce109a2017-01-31 00:57:56 -08001770 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001771 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001772 return;
1773 }
deadbeefab9b2d12015-10-14 11:33:11 -07001774
Steve Anton8d3444d2017-10-20 15:30:51 -07001775 if (IsClosed()) {
1776 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001777 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001778 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001779 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001780 return;
1781 }
1782
zhihuang1c378ed2017-08-17 14:10:50 -07001783 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001784 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001785 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001786 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001787 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001788 return;
1789 }
1790
Steve Anton22da89f2018-01-25 13:58:07 -08001791 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1792 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1793 if (IsUnifiedPlan()) {
1794 RTCError error = HandleLegacyOfferOptions(options);
1795 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001796 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001797 return;
1798 }
1799 }
1800
zhihuang1c378ed2017-08-17 14:10:50 -07001801 cricket::MediaSessionOptions session_options;
1802 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001803 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001804}
1805
Steve Anton22da89f2018-01-25 13:58:07 -08001806RTCError PeerConnection::HandleLegacyOfferOptions(
1807 const RTCOfferAnswerOptions& options) {
1808 RTC_DCHECK(IsUnifiedPlan());
1809
1810 if (options.offer_to_receive_audio == 0) {
1811 RemoveRecvDirectionFromReceivingTransceiversOfType(
1812 cricket::MEDIA_TYPE_AUDIO);
1813 } else if (options.offer_to_receive_audio == 1) {
1814 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1815 } else if (options.offer_to_receive_audio > 1) {
1816 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1817 "offer_to_receive_audio > 1 is not supported.");
1818 }
1819
1820 if (options.offer_to_receive_video == 0) {
1821 RemoveRecvDirectionFromReceivingTransceiversOfType(
1822 cricket::MEDIA_TYPE_VIDEO);
1823 } else if (options.offer_to_receive_video == 1) {
1824 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1825 } else if (options.offer_to_receive_video > 1) {
1826 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1827 "offer_to_receive_video > 1 is not supported.");
1828 }
1829
1830 return RTCError::OK();
1831}
1832
1833void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1834 cricket::MediaType media_type) {
1835 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001836 RtpTransceiverDirection new_direction =
1837 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1838 if (new_direction != transceiver->direction()) {
1839 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1840 << " transceiver (MID="
1841 << transceiver->mid().value_or("<not set>") << ") from "
1842 << RtpTransceiverDirectionToString(
1843 transceiver->direction())
1844 << " to "
1845 << RtpTransceiverDirectionToString(new_direction)
1846 << " since CreateOffer specified offer_to_receive=0";
1847 transceiver->internal()->set_direction(new_direction);
1848 }
Steve Anton22da89f2018-01-25 13:58:07 -08001849 }
1850}
1851
1852void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1853 cricket::MediaType media_type) {
1854 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001855 RTC_LOG(LS_INFO)
1856 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1857 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001858 RtpTransceiverInit init;
1859 init.direction = RtpTransceiverDirection::kRecvOnly;
1860 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1861 }
1862}
1863
1864std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1865PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1866 std::vector<
1867 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1868 receiving_transceivers;
1869 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001870 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001871 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1872 receiving_transceivers.push_back(transceiver);
1873 }
1874 }
1875 return receiving_transceivers;
1876}
1877
htaa2a49d92016-03-04 02:51:39 -08001878void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1879 const RTCOfferAnswerOptions& options) {
1880 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001881 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001882 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001883 return;
1884 }
1885
Steve Antondffead82018-02-06 10:31:29 -08001886 if (!(signaling_state_ == kHaveRemoteOffer ||
1887 signaling_state_ == kHaveLocalPrAnswer)) {
1888 std::string error =
1889 "PeerConnection cannot create an answer in a state other than "
1890 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001891 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001892 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001893 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001894 return;
1895 }
1896
Steve Antondffead82018-02-06 10:31:29 -08001897 // The remote description should be set if we're in the right state.
1898 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001899
Steve Anton22da89f2018-01-25 13:58:07 -08001900 if (IsUnifiedPlan()) {
1901 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1902 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1903 "supported with Unified Plan semantics. Use the "
1904 "RtpTransceiver API instead.";
1905 }
1906 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1907 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1908 "supported with Unified Plan semantics. Use the "
1909 "RtpTransceiver API instead.";
1910 }
1911 }
1912
htaa2a49d92016-03-04 02:51:39 -08001913 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001914 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001915
Steve Antond25da372017-11-06 14:50:29 -08001916 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001917}
1918
1919void PeerConnection::SetLocalDescription(
1920 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001921 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001922 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001923
Steve Anton80dd7b52018-02-16 17:08:42 -08001924 // The SetLocalDescription contract is that we take ownership of the session
1925 // description regardless of the outcome, so wrap it in a unique_ptr right
1926 // away. Ideally, SetLocalDescription's signature will be changed to take the
1927 // description as a unique_ptr argument to formalize this agreement.
1928 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1929
nisse7ce109a2017-01-31 00:57:56 -08001930 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001931 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001932 return;
1933 }
Steve Anton8a006912017-12-04 15:25:56 -08001934
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001935 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001936 PostSetSessionDescriptionFailure(
1937 observer,
1938 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001939 return;
1940 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001941
Steve Anton80dd7b52018-02-16 17:08:42 -08001942 // If a session error has occurred the PeerConnection is in a possibly
1943 // inconsistent state so fail right away.
1944 if (session_error() != SessionError::kNone) {
1945 std::string error_message = GetSessionErrorMsg();
1946 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001947 PostSetSessionDescriptionFailure(
1948 observer,
1949 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001950 return;
1951 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001952
Steve Anton80dd7b52018-02-16 17:08:42 -08001953 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1954 if (!error.ok()) {
1955 std::string error_message = GetSetDescriptionErrorMessage(
1956 cricket::CS_LOCAL, desc->GetType(), error);
1957 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001958 PostSetSessionDescriptionFailure(
1959 observer,
1960 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001961 return;
1962 }
1963
1964 // Grab the description type before moving ownership to ApplyLocalDescription,
1965 // which may destroy it before returning.
1966 const SdpType type = desc->GetType();
1967
1968 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001969 // |desc| may be destroyed at this point.
1970
1971 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001972 // If ApplyLocalDescription fails, the PeerConnection could be in an
1973 // inconsistent state, so act conservatively here and set the session error
1974 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1975 SetSessionError(SessionError::kContent, error.message());
1976 std::string error_message =
1977 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1978 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001979 PostSetSessionDescriptionFailure(
1980 observer,
1981 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001982 return;
1983 }
Steve Anton8a006912017-12-04 15:25:56 -08001984 RTC_DCHECK(local_description());
1985
1986 PostSetSessionDescriptionSuccess(observer);
1987
Steve Antonad182762018-09-05 20:22:40 +00001988 // MaybeStartGathering needs to be called after posting
1989 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1990 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001991 transport_controller_->MaybeStartGathering();
1992
Steve Antona3a92c22017-12-07 10:27:41 -08001993 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001994 // TODO(deadbeef): We already had to hop to the network thread for
1995 // MaybeStartGathering...
1996 network_thread()->Invoke<void>(
1997 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1998 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001999 // Make UMA notes about what was agreed to.
2000 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002001 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002002 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002003}
2004
2005RTCError PeerConnection::ApplyLocalDescription(
2006 std::unique_ptr<SessionDescriptionInterface> desc) {
2007 RTC_DCHECK_RUN_ON(signaling_thread());
2008 RTC_DCHECK(desc);
2009
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002010 // Update stats here so that we have the most recent stats for tracks and
2011 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002012 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002013
Steve Antondcc3c022017-12-22 16:02:54 -08002014 // Take a reference to the old local description since it's used below to
2015 // compare against the new local description. When setting the new local
2016 // description, grab ownership of the replaced session description in case it
2017 // is the same as |old_local_description|, to keep it alive for the duration
2018 // of the method.
2019 const SessionDescriptionInterface* old_local_description =
2020 local_description();
2021 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002022 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002023 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002024 replaced_local_description = pending_local_description_
2025 ? std::move(pending_local_description_)
2026 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002027 current_local_description_ = std::move(desc);
2028 pending_local_description_ = nullptr;
2029 current_remote_description_ = std::move(pending_remote_description_);
2030 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002031 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002032 pending_local_description_ = std::move(desc);
2033 }
2034 // The session description to apply now must be accessed by
2035 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002036 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002037
Zhi Huange830e682018-03-30 10:48:35 -07002038 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2039 if (!error.ok()) {
2040 return error;
2041 }
2042
Steve Antondcc3c022017-12-22 16:02:54 -08002043 if (IsUnifiedPlan()) {
2044 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002045 cricket::CS_LOCAL, *local_description(), old_local_description,
2046 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002047 if (!error.ok()) {
2048 return error;
2049 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002050 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2051 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002052 for (auto transceiver : transceivers_) {
2053 const ContentInfo* content =
2054 FindMediaSectionForTransceiver(transceiver, local_description());
2055 if (!content) {
2056 continue;
2057 }
2058 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002059 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2060 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002061 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002062 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2063 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2064 // "recvonly", process the removal of a remote track for the media
2065 // description, given transceiver, removeList, and muteTracks.
2066 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2067 (transceiver->internal()->fired_direction() &&
2068 RtpTransceiverDirectionHasRecv(
2069 *transceiver->internal()->fired_direction()))) {
2070 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2071 &removed_streams);
2072 }
2073 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2074 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002075 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002076 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002077 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002078 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002079 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002080 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002081 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002082 }
2083 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002084 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002085 }
2086 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002087 // Media channels will be created only when offer is set. These may use new
2088 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002089 if (type == SdpType::kOffer) {
2090 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2091 // description is applied. Restore back to old description.
2092 RTCError error = CreateChannels(*local_description()->description());
2093 if (!error.ok()) {
2094 return error;
2095 }
2096 }
Steve Antondcc3c022017-12-22 16:02:54 -08002097 // Remove unused channels if MediaContentDescription is rejected.
2098 RemoveUnusedChannels(local_description()->description());
2099 }
Steve Anton8a006912017-12-04 15:25:56 -08002100
Zhi Huange830e682018-03-30 10:48:35 -07002101 error = UpdateSessionState(type, cricket::CS_LOCAL,
2102 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002103 if (!error.ok()) {
2104 return error;
2105 }
Steve Antondcc3c022017-12-22 16:02:54 -08002106
Steve Anton8a006912017-12-04 15:25:56 -08002107 if (remote_description()) {
2108 // Now that we have a local description, we can push down remote candidates.
2109 UseCandidatesInSessionDescription(remote_description());
2110 }
2111
2112 pending_ice_restarts_.clear();
2113 if (session_error() != SessionError::kNone) {
2114 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2115 }
2116
deadbeefab9b2d12015-10-14 11:33:11 -07002117 // If setting the description decided our SSL role, allocate any necessary
2118 // SCTP sids.
2119 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002120 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002121 AllocateSctpSids(role);
2122 }
2123
Steve Antond3679212018-01-17 17:41:02 -08002124 if (IsUnifiedPlan()) {
2125 for (auto transceiver : transceivers_) {
2126 const ContentInfo* content =
2127 FindMediaSectionForTransceiver(transceiver, local_description());
2128 if (!content) {
2129 continue;
2130 }
Steve Anton74255ff2018-01-24 18:32:57 -08002131 const auto& streams = content->media_description()->streams();
2132 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002133 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002134 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002135 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002136 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002137 } else {
2138 // 0 is a special value meaning "this sender has no associated send
2139 // stream". Need to call this so the sender won't attempt to configure
2140 // a no longer existing stream and run into DCHECKs in the lower
2141 // layers.
2142 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002143 }
2144 }
2145 } else {
2146 // Plan B semantics.
2147
Steve Antondcc3c022017-12-22 16:02:54 -08002148 // Update state and SSRC of local MediaStreams and DataChannels based on the
2149 // local session description.
2150 const cricket::ContentInfo* audio_content =
2151 GetFirstAudioContent(local_description()->description());
2152 if (audio_content) {
2153 if (audio_content->rejected) {
2154 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2155 } else {
2156 const cricket::AudioContentDescription* audio_desc =
2157 audio_content->media_description()->as_audio();
2158 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2159 }
deadbeeffaac4972015-11-12 15:33:07 -08002160 }
deadbeefab9b2d12015-10-14 11:33:11 -07002161
Steve Antondcc3c022017-12-22 16:02:54 -08002162 const cricket::ContentInfo* video_content =
2163 GetFirstVideoContent(local_description()->description());
2164 if (video_content) {
2165 if (video_content->rejected) {
2166 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2167 } else {
2168 const cricket::VideoContentDescription* video_desc =
2169 video_content->media_description()->as_video();
2170 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2171 }
deadbeeffaac4972015-11-12 15:33:07 -08002172 }
deadbeefab9b2d12015-10-14 11:33:11 -07002173 }
2174
2175 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002176 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002177 if (data_content) {
2178 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002179 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002180 if (rtc::starts_with(data_desc->protocol().data(),
2181 cricket::kMediaProtocolRtpPrefix)) {
2182 UpdateLocalRtpDataChannels(data_desc->streams());
2183 }
2184 }
2185
Steve Anton8a006912017-12-04 15:25:56 -08002186 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187}
2188
2189void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002190 SetSessionDescriptionObserver* observer,
2191 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002192 SetRemoteDescription(
2193 std::unique_ptr<SessionDescriptionInterface>(desc),
2194 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2195 new SetRemoteDescriptionObserverAdapter(this, observer)));
2196}
2197
2198void PeerConnection::SetRemoteDescription(
2199 std::unique_ptr<SessionDescriptionInterface> desc,
2200 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002201 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002202
nisse7ce109a2017-01-31 00:57:56 -08002203 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002204 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002205 return;
2206 }
Steve Anton8a006912017-12-04 15:25:56 -08002207
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002208 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002209 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002210 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211 return;
2212 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002213
Steve Anton80dd7b52018-02-16 17:08:42 -08002214 // If a session error has occurred the PeerConnection is in a possibly
2215 // inconsistent state so fail right away.
2216 if (session_error() != SessionError::kNone) {
2217 std::string error_message = GetSessionErrorMsg();
2218 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2219 observer->OnSetRemoteDescriptionComplete(
2220 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2221 return;
2222 }
Steve Anton71439a62018-02-15 11:53:06 -08002223
Steve Antonba42e992018-04-09 14:10:01 -07002224 if (desc->GetType() == SdpType::kOffer) {
2225 // Report to UMA the format of the received offer.
2226 ReportSdpFormatReceived(*desc);
2227 }
2228
Steve Anton80dd7b52018-02-16 17:08:42 -08002229 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002230 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002231 std::string error_message = GetSetDescriptionErrorMessage(
2232 cricket::CS_REMOTE, desc->GetType(), error);
2233 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002234 observer->OnSetRemoteDescriptionComplete(
2235 RTCError(error.type(), std::move(error_message)));
2236 return;
2237 }
Steve Anton71439a62018-02-15 11:53:06 -08002238
Steve Anton80dd7b52018-02-16 17:08:42 -08002239 // Grab the description type before moving ownership to
2240 // ApplyRemoteDescription, which may destroy it before returning.
2241 const SdpType type = desc->GetType();
2242
2243 error = ApplyRemoteDescription(std::move(desc));
2244 // |desc| may be destroyed at this point.
2245
2246 if (!error.ok()) {
2247 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2248 // inconsistent state, so act conservatively here and set the session error
2249 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2250 SetSessionError(SessionError::kContent, error.message());
2251 std::string error_message =
2252 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2253 RTC_LOG(LS_ERROR) << error_message;
2254 observer->OnSetRemoteDescriptionComplete(
2255 RTCError(error.type(), std::move(error_message)));
2256 return;
2257 }
2258 RTC_DCHECK(remote_description());
2259
2260 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002261 // TODO(deadbeef): We already had to hop to the network thread for
2262 // MaybeStartGathering...
2263 network_thread()->Invoke<void>(
2264 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2265 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002266 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002267 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002268 }
2269
2270 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002271 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002272}
2273
2274RTCError PeerConnection::ApplyRemoteDescription(
2275 std::unique_ptr<SessionDescriptionInterface> desc) {
2276 RTC_DCHECK_RUN_ON(signaling_thread());
2277 RTC_DCHECK(desc);
2278
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002279 // Update stats here so that we have the most recent stats for tracks and
2280 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002281 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002282
Steve Antondcc3c022017-12-22 16:02:54 -08002283 // Take a reference to the old remote description since it's used below to
2284 // compare against the new remote description. When setting the new remote
2285 // description, grab ownership of the replaced session description in case it
2286 // is the same as |old_remote_description|, to keep it alive for the duration
2287 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002288 const SessionDescriptionInterface* old_remote_description =
2289 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002290 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002291 SdpType type = desc->GetType();
2292 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002293 replaced_remote_description = pending_remote_description_
2294 ? std::move(pending_remote_description_)
2295 : std::move(current_remote_description_);
2296 current_remote_description_ = std::move(desc);
2297 pending_remote_description_ = nullptr;
2298 current_local_description_ = std::move(pending_local_description_);
2299 } else {
2300 replaced_remote_description = std::move(pending_remote_description_);
2301 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002302 }
Steve Anton8a006912017-12-04 15:25:56 -08002303 // The session description to apply now must be accessed by
2304 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002305 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306
Zhi Huange830e682018-03-30 10:48:35 -07002307 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2308 if (!error.ok()) {
2309 return error;
2310 }
Steve Anton8a006912017-12-04 15:25:56 -08002311 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002312 if (IsUnifiedPlan()) {
2313 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002314 cricket::CS_REMOTE, *remote_description(), local_description(),
2315 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002316 if (!error.ok()) {
2317 return error;
2318 }
Steve Antondcc3c022017-12-22 16:02:54 -08002319 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002320 // Media channels will be created only when offer is set. These may use new
2321 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002322 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002323 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002324 // description is applied. Restore back to old description.
2325 RTCError error = CreateChannels(*remote_description()->description());
2326 if (!error.ok()) {
2327 return error;
2328 }
2329 }
Steve Antondcc3c022017-12-22 16:02:54 -08002330 // Remove unused channels if MediaContentDescription is rejected.
2331 RemoveUnusedChannels(remote_description()->description());
2332 }
Steve Anton8a006912017-12-04 15:25:56 -08002333
Zhi Huange830e682018-03-30 10:48:35 -07002334 // NOTE: Candidates allocation will be initiated only when
2335 // SetLocalDescription is called.
2336 error = UpdateSessionState(type, cricket::CS_REMOTE,
2337 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002338 if (!error.ok()) {
2339 return error;
2340 }
2341
2342 if (local_description() &&
2343 !UseCandidatesInSessionDescription(remote_description())) {
2344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2345 }
2346
2347 if (old_remote_description) {
2348 for (const cricket::ContentInfo& content :
2349 old_remote_description->description()->contents()) {
2350 // Check if this new SessionDescription contains new ICE ufrag and
2351 // password that indicates the remote peer requests an ICE restart.
2352 // TODO(deadbeef): When we start storing both the current and pending
2353 // remote description, this should reset pending_ice_restarts and compare
2354 // against the current description.
2355 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2356 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002357 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002358 pending_ice_restarts_.insert(content.name);
2359 }
2360 } else {
2361 // We retain all received candidates only if ICE is not restarted.
2362 // When ICE is restarted, all previous candidates belong to an old
2363 // generation and should not be kept.
2364 // TODO(deadbeef): This goes against the W3C spec which says the remote
2365 // description should only contain candidates from the last set remote
2366 // description plus any candidates added since then. We should remove
2367 // this once we're sure it won't break anything.
2368 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2369 old_remote_description, content.name, mutable_remote_description());
2370 }
2371 }
2372 }
2373
2374 if (session_error() != SessionError::kNone) {
2375 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2376 }
2377
2378 // Set the the ICE connection state to connecting since the connection may
2379 // become writable with peer reflexive candidates before any remote candidate
2380 // is signaled.
2381 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2382 // is to have a new signal the indicates a change in checking state from the
2383 // transport and expose a new checking() member from transport that can be
2384 // read to determine the current checking state. The existing SignalConnecting
2385 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002386 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002387 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002388 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2389 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2390 }
2391
deadbeefab9b2d12015-10-14 11:33:11 -07002392 // If setting the description decided our SSL role, allocate any necessary
2393 // SCTP sids.
2394 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002395 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002396 AllocateSctpSids(role);
2397 }
2398
Steve Antondcc3c022017-12-22 16:02:54 -08002399 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002400 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002401 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002402 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002403 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002404 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002405 for (auto transceiver : transceivers_) {
2406 const ContentInfo* content =
2407 FindMediaSectionForTransceiver(transceiver, remote_description());
2408 if (!content) {
2409 continue;
2410 }
2411 const MediaContentDescription* media_desc = content->media_description();
2412 RtpTransceiverDirection local_direction =
2413 RtpTransceiverDirectionReversed(media_desc->direction());
2414 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2415 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2416 // transceiver's current direction is neither sendrecv nor recvonly,
2417 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002418 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002419 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002420 // The remote description has signaled the stream IDs.
2421 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002422 }
Steve Antondcc3c022017-12-22 16:02:54 -08002423 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002424 (!transceiver->fired_direction() ||
2425 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002426 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002427 << content->name << " (added to "
2428 << GetStreamIdsString(stream_ids) << ").";
2429
2430 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2431 for (const std::string& stream_id : stream_ids) {
2432 rtc::scoped_refptr<MediaStreamInterface> stream =
2433 remote_streams_->find(stream_id);
2434 if (!stream) {
2435 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2436 MediaStream::Create(stream_id));
2437 remote_streams_->AddStream(stream);
2438 added_streams.push_back(stream);
2439 }
2440 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002441 }
Steve Anton3172c032018-05-03 15:30:18 -07002442 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002443 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2444 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002445 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002446 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002447 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002448 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2449 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2450 // removal of a remote track for the media description, given transceiver,
2451 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002452 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002453 (transceiver->fired_direction() &&
2454 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2455 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2456 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002457 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002458 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2459 transceiver->internal()->set_fired_direction(local_direction);
2460 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2461 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002462 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002463 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2464 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002465 transceiver->internal()->set_current_direction(local_direction);
2466 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002467 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2468 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002469 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002470 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2471 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002472 transceiver->Stop();
2473 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002474 if (!content->rejected &&
2475 RtpTransceiverDirectionHasRecv(local_direction)) {
2476 // Set ssrc to 0 in the case of an unsignalled ssrc.
2477 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002478 if (!media_desc->streams().empty() &&
2479 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002480 ssrc = media_desc->streams()[0].first_ssrc();
2481 }
2482 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002483 }
Steve Antondcc3c022017-12-22 16:02:54 -08002484 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002485 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002486 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002487 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002488 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002489 observer->OnTrack(transceiver);
2490 observer->OnAddTrack(transceiver->receiver(),
2491 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002492 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002493 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002494 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002495 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002496 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002497 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002498 }
2499 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002500 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002501 }
Steve Antondcc3c022017-12-22 16:02:54 -08002502 }
2503
Henrik Boströmfdb92012017-11-09 19:55:44 +01002504 const cricket::ContentInfo* audio_content =
2505 GetFirstAudioContent(remote_description()->description());
2506 const cricket::ContentInfo* video_content =
2507 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002508 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002509 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002510 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002511 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002512 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002513 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002514
2515 // Check if the descriptions include streams, just in case the peer supports
2516 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002517 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002518 (audio_desc && !audio_desc->streams().empty()) ||
2519 (video_desc && !video_desc->streams().empty())) {
2520 remote_peer_supports_msid_ = true;
2521 }
deadbeefab9b2d12015-10-14 11:33:11 -07002522
2523 // We wait to signal new streams until we finish processing the description,
2524 // since only at that point will new streams have all their tracks.
2525 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2526
Steve Antondcc3c022017-12-22 16:02:54 -08002527 if (!IsUnifiedPlan()) {
2528 // TODO(steveanton): When removing RTP senders/receivers in response to a
2529 // rejected media section, there is some cleanup logic that expects the
2530 // voice/ video channel to still be set. But in this method the voice/video
2531 // channel would have been destroyed by the SetRemoteDescription caller
2532 // above so the cleanup that relies on them fails to run. The RemoveSenders
2533 // calls should be moved to right before the DestroyChannel calls to fix
2534 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002535
Steve Antondcc3c022017-12-22 16:02:54 -08002536 // Find all audio rtp streams and create corresponding remote AudioTracks
2537 // and MediaStreams.
2538 if (audio_content) {
2539 if (audio_content->rejected) {
2540 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2541 } else {
2542 bool default_audio_track_needed =
2543 !remote_peer_supports_msid_ &&
2544 RtpTransceiverDirectionHasSend(audio_desc->direction());
2545 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2546 default_audio_track_needed, audio_desc->type(),
2547 new_streams);
2548 }
deadbeeffaac4972015-11-12 15:33:07 -08002549 }
deadbeefab9b2d12015-10-14 11:33:11 -07002550
Steve Antondcc3c022017-12-22 16:02:54 -08002551 // Find all video rtp streams and create corresponding remote VideoTracks
2552 // and MediaStreams.
2553 if (video_content) {
2554 if (video_content->rejected) {
2555 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2556 } else {
2557 bool default_video_track_needed =
2558 !remote_peer_supports_msid_ &&
2559 RtpTransceiverDirectionHasSend(video_desc->direction());
2560 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2561 default_video_track_needed, video_desc->type(),
2562 new_streams);
2563 }
deadbeeffaac4972015-11-12 15:33:07 -08002564 }
deadbeefab9b2d12015-10-14 11:33:11 -07002565
Steve Antondcc3c022017-12-22 16:02:54 -08002566 // Update the DataChannels with the information from the remote peer.
2567 if (data_desc) {
2568 if (rtc::starts_with(data_desc->protocol().data(),
2569 cricket::kMediaProtocolRtpPrefix)) {
2570 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2571 }
deadbeefab9b2d12015-10-14 11:33:11 -07002572 }
deadbeefab9b2d12015-10-14 11:33:11 -07002573
Steve Antondcc3c022017-12-22 16:02:54 -08002574 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002575 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002576 for (size_t i = 0; i < new_streams->count(); ++i) {
2577 MediaStreamInterface* new_stream = new_streams->at(i);
2578 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002579 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002580 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2581 }
deadbeefab9b2d12015-10-14 11:33:11 -07002582
Steve Antondcc3c022017-12-22 16:02:54 -08002583 UpdateEndedRemoteMediaStreams();
2584 }
deadbeefab9b2d12015-10-14 11:33:11 -07002585
Steve Anton8a006912017-12-04 15:25:56 -08002586 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002587}
2588
Steve Anton0f5400a2018-07-17 14:25:36 -07002589void PeerConnection::ProcessRemovalOfRemoteTrack(
2590 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2591 transceiver,
2592 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2593 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2594 RTC_DCHECK(transceiver->mid());
2595 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2596 << *transceiver->mid();
2597 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2598 transceiver->internal()->receiver_internal()->streams();
2599 // This will remove the remote track from the streams.
2600 transceiver->internal()->receiver_internal()->set_stream_ids({});
2601 remove_list->push_back(transceiver);
2602 // Remove any streams that no longer have tracks.
2603 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2604 // of streams, see if the stream was removed by checking if this was the
2605 // last receiver with that stream ID.
2606 for (auto stream : media_streams) {
2607 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2608 remote_streams_->RemoveStream(stream);
2609 removed_streams->push_back(stream);
2610 }
2611 }
2612}
2613
Steve Antondcc3c022017-12-22 16:02:54 -08002614RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2615 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002616 const SessionDescriptionInterface& new_session,
2617 const SessionDescriptionInterface* old_local_description,
2618 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002619 RTC_DCHECK(IsUnifiedPlan());
2620
Steve Anton7464fca2018-01-19 11:10:37 -08002621 const cricket::ContentGroup* bundle_group = nullptr;
2622 if (new_session.GetType() == SdpType::kOffer) {
2623 auto bundle_group_or_error =
2624 GetEarlyBundleGroup(*new_session.description());
2625 if (!bundle_group_or_error.ok()) {
2626 return bundle_group_or_error.MoveError();
2627 }
2628 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002629 }
Steve Antondcc3c022017-12-22 16:02:54 -08002630
Steve Antondcc3c022017-12-22 16:02:54 -08002631 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002632 for (size_t i = 0; i < new_contents.size(); ++i) {
2633 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002634 cricket::MediaType media_type = new_content.media_description()->type();
2635 seen_mids_.insert(new_content.name);
2636 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2637 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002638 const cricket::ContentInfo* old_local_content = nullptr;
2639 if (old_local_description &&
2640 i < old_local_description->description()->contents().size()) {
2641 old_local_content =
2642 &old_local_description->description()->contents()[i];
2643 }
2644 const cricket::ContentInfo* old_remote_content = nullptr;
2645 if (old_remote_description &&
2646 i < old_remote_description->description()->contents().size()) {
2647 old_remote_content =
2648 &old_remote_description->description()->contents()[i];
2649 }
Steve Antondcc3c022017-12-22 16:02:54 -08002650 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002651 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2652 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002653 if (!transceiver_or_error.ok()) {
2654 return transceiver_or_error.MoveError();
2655 }
2656 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002657 RTCError error =
2658 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2659 if (!error.ok()) {
2660 return error;
2661 }
2662 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002663 if (GetDataMid() && new_content.name != *GetDataMid()) {
2664 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002665 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2666 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002667 continue;
2668 }
2669 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2670 if (!error.ok()) {
2671 return error;
2672 }
Steve Antondcc3c022017-12-22 16:02:54 -08002673 } else {
2674 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2675 "Unknown section type.");
2676 }
2677 }
2678
2679 return RTCError::OK();
2680}
2681
2682RTCError PeerConnection::UpdateTransceiverChannel(
2683 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2684 transceiver,
2685 const cricket::ContentInfo& content,
2686 const cricket::ContentGroup* bundle_group) {
2687 RTC_DCHECK(IsUnifiedPlan());
2688 RTC_DCHECK(transceiver);
2689 cricket::BaseChannel* channel = transceiver->internal()->channel();
2690 if (content.rejected) {
2691 if (channel) {
2692 transceiver->internal()->SetChannel(nullptr);
2693 DestroyBaseChannel(channel);
2694 }
2695 } else {
2696 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002697 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002698 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002699 } else {
Steve Anton69470252018-02-09 11:43:08 -08002700 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002701 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002702 }
2703 if (!channel) {
2704 LOG_AND_RETURN_ERROR(
2705 RTCErrorType::INTERNAL_ERROR,
2706 "Failed to create channel for mid=" + content.name);
2707 }
2708 transceiver->internal()->SetChannel(channel);
2709 }
2710 }
2711 return RTCError::OK();
2712}
2713
Steve Antonfa2260d2017-12-28 16:38:23 -08002714RTCError PeerConnection::UpdateDataChannel(
2715 cricket::ContentSource source,
2716 const cricket::ContentInfo& content,
2717 const cricket::ContentGroup* bundle_group) {
2718 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002719 // If data channels are disabled, ignore this media section. CreateAnswer
2720 // will take care of rejecting it.
2721 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002722 }
2723 if (content.rejected) {
2724 DestroyDataChannel();
2725 } else {
2726 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002727 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002728 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2729 "Failed to create data channel.");
2730 }
2731 }
2732 if (source == cricket::CS_REMOTE) {
2733 const MediaContentDescription* data_desc = content.media_description();
2734 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2735 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2736 }
2737 }
2738 }
2739 return RTCError::OK();
2740}
2741
Steve Antondcc3c022017-12-22 16:02:54 -08002742RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2743PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002744 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002745 size_t mline_index,
2746 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002747 const ContentInfo* old_local_content,
2748 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002749 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002750 // If this is an offer then the m= section might be recycled. If the m=
2751 // section is being recycled (defined as: rejected in the current local or
2752 // remote description and not rejected in new description), dissociate the
2753 // currently associated RtpTransceiver by setting its mid property to null,
2754 // and discard the mapping between the transceiver and its m= section index.
2755 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2756 old_remote_content)) {
2757 // We want to dissociate the transceiver that has the rejected mid.
2758 const std::string& old_mid =
2759 (old_local_content && old_local_content->rejected)
2760 ? old_local_content->name
2761 : old_remote_content->name;
2762 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002763 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002764 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2765 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002766 old_transceiver->internal()->set_mid(absl::nullopt);
2767 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002768 }
2769 }
2770 const MediaContentDescription* media_desc = content.media_description();
2771 auto transceiver = GetAssociatedTransceiver(content.name);
2772 if (source == cricket::CS_LOCAL) {
2773 // Find the RtpTransceiver that corresponds to this m= section, using the
2774 // mapping between transceivers and m= section indices established when
2775 // creating the offer.
2776 if (!transceiver) {
2777 transceiver = GetTransceiverByMLineIndex(mline_index);
2778 }
2779 if (!transceiver) {
2780 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2781 "Unknown transceiver");
2782 }
2783 } else {
2784 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2785 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2786 // of the same type...
2787 if (!transceiver &&
2788 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2789 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2790 }
2791 // If no RtpTransceiver was found in the previous step, create one with a
2792 // recvonly direction.
2793 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002794 RTC_LOG(LS_INFO) << "Adding "
2795 << cricket::MediaTypeToString(media_desc->type())
2796 << " transceiver for MID=" << content.name
2797 << " at i=" << mline_index
2798 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002799 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002800 auto sender =
2801 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002802 std::string receiver_id;
2803 if (!media_desc->streams().empty()) {
2804 receiver_id = media_desc->streams()[0].id;
2805 } else {
2806 receiver_id = rtc::CreateRandomUuid();
2807 }
2808 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002809 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002810 transceiver->internal()->set_direction(
2811 RtpTransceiverDirection::kRecvOnly);
2812 }
2813 }
2814 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002815 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002816 LOG_AND_RETURN_ERROR(
2817 RTCErrorType::INVALID_PARAMETER,
2818 "Transceiver type does not match media description type.");
2819 }
2820 // Associate the found or created RtpTransceiver with the m= section by
2821 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2822 // section, and establish a mapping between the transceiver and the index of
2823 // the m= section.
2824 transceiver->internal()->set_mid(content.name);
2825 transceiver->internal()->set_mline_index(mline_index);
2826 return std::move(transceiver);
2827}
2828
2829rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2830PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2831 RTC_DCHECK(IsUnifiedPlan());
2832 for (auto transceiver : transceivers_) {
2833 if (transceiver->mid() == mid) {
2834 return transceiver;
2835 }
2836 }
2837 return nullptr;
2838}
2839
2840rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2841PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2842 RTC_DCHECK(IsUnifiedPlan());
2843 for (auto transceiver : transceivers_) {
2844 if (transceiver->internal()->mline_index() == mline_index) {
2845 return transceiver;
2846 }
2847 }
2848 return nullptr;
2849}
2850
2851rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2852PeerConnection::FindAvailableTransceiverToReceive(
2853 cricket::MediaType media_type) const {
2854 RTC_DCHECK(IsUnifiedPlan());
2855 // From JSEP section 5.10 (Applying a Remote Description):
2856 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2857 // the same type that were added to the PeerConnection by addTrack and are not
2858 // associated with any m= section and are not stopped, find the first such
2859 // RtpTransceiver.
2860 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002861 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002862 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2863 !transceiver->stopped()) {
2864 return transceiver;
2865 }
2866 }
2867 return nullptr;
2868}
2869
Steve Antoned10bd92017-12-05 10:52:59 -08002870const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2871 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2872 transceiver,
2873 const SessionDescriptionInterface* sdesc) const {
2874 RTC_DCHECK(transceiver);
2875 RTC_DCHECK(sdesc);
2876 if (IsUnifiedPlan()) {
2877 if (!transceiver->internal()->mid()) {
2878 // This transceiver is not associated with a media section yet.
2879 return nullptr;
2880 }
2881 return sdesc->description()->GetContentByName(
2882 *transceiver->internal()->mid());
2883 } else {
2884 // Plan B only allows at most one audio and one video section, so use the
2885 // first media section of that type.
2886 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002887 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002888 }
2889}
2890
deadbeef46c73892016-11-16 19:42:04 -08002891PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2892 return configuration_;
2893}
2894
deadbeef293e9262017-01-11 12:28:30 -08002895bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2896 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002897 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002898 if (IsClosed()) {
2899 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2900 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2901 }
2902
Qingsi Wanga2d60672018-04-11 16:57:45 -07002903 // According to JSEP, after setLocalDescription, changing the candidate pool
2904 // size is not allowed, and changing the set of ICE servers will not result
2905 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002906 if (local_description() && configuration.ice_candidate_pool_size !=
2907 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002908 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2909 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002910 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002911 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002912
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002913 if (local_description() &&
2914 configuration.use_media_transport != configuration_.use_media_transport) {
2915 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2916 "SetLocalDescription.";
2917 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2918 }
2919
2920 if (remote_description() &&
2921 configuration.use_media_transport != configuration_.use_media_transport) {
2922 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2923 "SetRemoteDescription.";
2924 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2925 }
2926
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002927 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002928 configuration.use_media_transport_for_data_channels !=
2929 configuration_.use_media_transport_for_data_channels) {
2930 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2931 "after calling SetLocalDescription.";
2932 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2933 }
2934
2935 if (remote_description() &&
2936 configuration.use_media_transport_for_data_channels !=
2937 configuration_.use_media_transport_for_data_channels) {
2938 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2939 "after calling SetRemoteDescription.";
2940 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2941 }
2942
2943 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002944 configuration.crypto_options != configuration_.crypto_options) {
2945 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2946 "SetLocalDescription.";
2947 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2948 }
2949
deadbeef293e9262017-01-11 12:28:30 -08002950 // The simplest (and most future-compatible) way to tell if the config was
2951 // modified in an invalid way is to copy each property we do support
2952 // modifying, then use operator==. There are far more properties we don't
2953 // support modifying than those we do, and more could be added.
2954 RTCConfiguration modified_config = configuration_;
2955 modified_config.servers = configuration.servers;
2956 modified_config.type = configuration.type;
2957 modified_config.ice_candidate_pool_size =
2958 configuration.ice_candidate_pool_size;
2959 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002960 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002961 modified_config.ice_check_interval_strong_connectivity =
2962 configuration.ice_check_interval_strong_connectivity;
2963 modified_config.ice_check_interval_weak_connectivity =
2964 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002965 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2966 modified_config.ice_unwritable_min_checks =
2967 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002968 modified_config.stun_candidate_keepalive_interval =
2969 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002970 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002971 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002972 modified_config.active_reset_srtp_params =
2973 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002974 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002975 modified_config.use_media_transport_for_data_channels =
2976 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08002977 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002978 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002979 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2980 }
2981
Steve Anton038834f2017-07-14 15:59:59 -07002982 // Validate the modified configuration.
2983 RTCError validate_error = ValidateConfiguration(modified_config);
2984 if (!validate_error.ok()) {
2985 return SafeSetError(std::move(validate_error), error);
2986 }
2987
deadbeef293e9262017-01-11 12:28:30 -08002988 // Note that this isn't possible through chromium, since it's an unsigned
2989 // short in WebIDL.
2990 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002991 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002992 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2993 }
2994
2995 // Parse ICE servers before hopping to network thread.
2996 cricket::ServerAddresses stun_servers;
2997 std::vector<cricket::RelayServerConfig> turn_servers;
2998 RTCErrorType parse_error =
2999 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3000 if (parse_error != RTCErrorType::NONE) {
3001 return SafeSetError(parse_error, error);
3002 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003003 // Note if STUN or TURN servers were supplied.
3004 if (!stun_servers.empty()) {
3005 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3006 }
3007 if (!turn_servers.empty()) {
3008 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3009 }
deadbeef293e9262017-01-11 12:28:30 -08003010
3011 // In theory this shouldn't fail.
3012 if (!network_thread()->Invoke<bool>(
3013 RTC_FROM_HERE,
3014 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3015 stun_servers, turn_servers, modified_config.type,
3016 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003017 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003018 modified_config.turn_customizer,
3019 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003020 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003021 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3022 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003023
deadbeefd1a38b52016-12-10 13:15:33 -08003024 // As described in JSEP, calling setConfiguration with new ICE servers or
3025 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3026 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003027 if (modified_config.servers != configuration_.servers ||
3028 modified_config.type != configuration_.type ||
3029 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003030 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003031 }
skvladd1f5fda2017-02-03 16:54:05 -08003032
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003033 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003034 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003035 modified_config.use_media_transport ||
3036 modified_config.use_media_transport_for_data_channels
3037 ? factory_->media_transport_factory()
3038 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003039
Zhi Huangb57e1692018-06-12 11:41:11 -07003040 if (configuration_.active_reset_srtp_params !=
3041 modified_config.active_reset_srtp_params) {
3042 transport_controller_->SetActiveResetSrtpParams(
3043 modified_config.active_reset_srtp_params);
3044 }
3045
deadbeef293e9262017-01-11 12:28:30 -08003046 configuration_ = modified_config;
3047 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003048}
3049
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003050bool PeerConnection::AddIceCandidate(
3051 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003052 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003053 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003054 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003055 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003056 return false;
3057 }
Steve Antond25da372017-11-06 14:50:29 -08003058
3059 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003060 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003061 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003062 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003063 return false;
3064 }
3065
3066 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003067 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003068 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003069 return false;
3070 }
3071
3072 bool valid = false;
3073 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3074 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003075 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003076 return false;
3077 }
3078
3079 // Add this candidate to the remote session description.
3080 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003081 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003082 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003083 return false;
3084 }
3085
3086 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003087 bool result = UseCandidate(ice_candidate);
3088 if (result) {
3089 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3090 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3091 } else {
3092 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3093 }
3094 return result;
Steve Antond25da372017-11-06 14:50:29 -08003095 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003096 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003097 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003098 return true;
3099 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003100}
3101
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003102bool PeerConnection::RemoveIceCandidates(
3103 const std::vector<cricket::Candidate>& candidates) {
3104 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003105 if (IsClosed()) {
3106 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3107 return false;
3108 }
3109
Steve Antond25da372017-11-06 14:50:29 -08003110 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003111 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3112 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003113 return false;
3114 }
3115
3116 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003117 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003118 return false;
3119 }
3120
3121 size_t number_removed =
3122 mutable_remote_description()->RemoveCandidates(candidates);
3123 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003124 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003125 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003126 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003127 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003128 }
3129
3130 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003131 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3132 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003133 RTC_LOG(LS_ERROR)
3134 << "RemoveIceCandidates: Error when removing remote candidates: "
3135 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003136 }
3137 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003138}
3139
Niels Möller0c4f7be2018-05-07 14:01:37 +02003140RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003141 if (!worker_thread()->IsCurrent()) {
3142 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003143 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003144 }
3145
Niels Möller0c4f7be2018-05-07 14:01:37 +02003146 const bool has_min = bitrate.min_bitrate_bps.has_value();
3147 const bool has_start = bitrate.start_bitrate_bps.has_value();
3148 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003149 if (has_min && *bitrate.min_bitrate_bps < 0) {
3150 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3151 "min_bitrate_bps <= 0");
3152 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003153 if (has_start) {
3154 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003155 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003156 "start_bitrate_bps < min_bitrate_bps");
3157 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003158 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3159 "curent_bitrate_bps < 0");
3160 }
3161 }
3162 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003163 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003164 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003165 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003166 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3167 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3168 "max_bitrate_bps < min_bitrate_bps");
3169 } else if (*bitrate.max_bitrate_bps < 0) {
3170 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3171 "max_bitrate_bps < 0");
3172 }
3173 }
3174
zstein4b979802017-06-02 14:37:37 -07003175 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003176 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003177
3178 return RTCError::OK();
3179}
3180
Alex Narest78609d52017-10-20 10:37:47 +02003181void PeerConnection::SetBitrateAllocationStrategy(
3182 std::unique_ptr<rtc::BitrateAllocationStrategy>
3183 bitrate_allocation_strategy) {
3184 rtc::Thread* worker_thread = factory_->worker_thread();
3185 if (!worker_thread->IsCurrent()) {
3186 rtc::BitrateAllocationStrategy* strategy_raw =
3187 bitrate_allocation_strategy.release();
3188 auto functor = [this, strategy_raw]() {
3189 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003190 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003191 };
3192 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3193 return;
3194 }
3195 RTC_DCHECK(call_.get());
3196 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3197}
3198
henrika5f6bf242017-11-01 11:06:56 +01003199void PeerConnection::SetAudioPlayout(bool playout) {
3200 if (!worker_thread()->IsCurrent()) {
3201 worker_thread()->Invoke<void>(
3202 RTC_FROM_HERE,
3203 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3204 return;
3205 }
3206 auto audio_state =
3207 factory_->channel_manager()->media_engine()->GetAudioState();
3208 audio_state->SetPlayout(playout);
3209}
3210
3211void PeerConnection::SetAudioRecording(bool recording) {
3212 if (!worker_thread()->IsCurrent()) {
3213 worker_thread()->Invoke<void>(
3214 RTC_FROM_HERE,
3215 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3216 return;
3217 }
3218 auto audio_state =
3219 factory_->channel_manager()->media_engine()->GetAudioState();
3220 audio_state->SetRecording(recording);
3221}
3222
Steve Anton8c0f7a72017-10-03 10:03:10 -07003223std::unique_ptr<rtc::SSLCertificate>
3224PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003225 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3226 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003227 return nullptr;
3228 }
Steve Antonf25303e2018-10-16 15:23:31 -07003229 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003230}
3231
Zhi Huang70b820f2018-01-27 14:16:15 -08003232std::unique_ptr<rtc::SSLCertChain>
3233PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003234 auto audio_transceiver = GetFirstAudioTransceiver();
3235 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003236 return nullptr;
3237 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003238 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003239 audio_transceiver->internal()->channel()->transport_name());
3240}
3241
3242rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3243PeerConnection::GetFirstAudioTransceiver() const {
3244 for (auto transceiver : transceivers_) {
3245 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3246 return transceiver;
3247 }
3248 }
3249 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003250}
3251
ivoc14d5dbe2016-07-04 07:06:55 -07003252bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3253 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003254 // TODO(eladalon): It would be better to not allow negative values into PC.
3255 const size_t max_size = (max_size_bytes < 0)
3256 ? RtcEventLog::kUnlimitedOutput
3257 : rtc::saturated_cast<size_t>(max_size_bytes);
3258 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003259 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003260 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003261}
3262
Bjorn Tereliusde939432017-11-20 17:38:14 +01003263bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3264 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003265 // TODO(eladalon): In C++14, this can be done with a lambda.
3266 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003267 bool operator()() {
3268 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3269 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003270 PeerConnection* const pc;
3271 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003272 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003273 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003274 return worker_thread()->Invoke<bool>(
3275 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003276}
3277
3278void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003279 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003280 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3281}
3282
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003283const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003284 return pending_local_description_ ? pending_local_description_.get()
3285 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003286}
3287
3288const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003289 return pending_remote_description_ ? pending_remote_description_.get()
3290 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003291}
3292
deadbeeffe4a8a42016-12-20 17:56:17 -08003293const SessionDescriptionInterface* PeerConnection::current_local_description()
3294 const {
Steve Anton75737c02017-11-06 10:37:17 -08003295 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003296}
3297
3298const SessionDescriptionInterface* PeerConnection::current_remote_description()
3299 const {
Steve Anton75737c02017-11-06 10:37:17 -08003300 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003301}
3302
3303const SessionDescriptionInterface* PeerConnection::pending_local_description()
3304 const {
Steve Anton75737c02017-11-06 10:37:17 -08003305 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003306}
3307
3308const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3309 const {
Steve Anton75737c02017-11-06 10:37:17 -08003310 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003311}
3312
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003313void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003314 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003315 // Update stats here so that we have the most recent stats for tracks and
3316 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003317 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003318
Steve Anton75737c02017-11-06 10:37:17 -08003319 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003320 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003321
Steve Anton8af21862017-12-15 11:20:13 -08003322 for (auto transceiver : transceivers_) {
3323 transceiver->Stop();
3324 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003325
3326 // Ensure that all asynchronous stats requests are completed before destroying
3327 // the transport controller below.
3328 if (stats_collector_) {
3329 stats_collector_->WaitForPendingRequest();
3330 }
3331
3332 // Don't destroy BaseChannels until after stats has been cleaned up so that
3333 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003334 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003335
Qingsi Wang93a84392018-01-30 17:13:09 -08003336 // The event log is used in the transport controller, which must be outlived
3337 // by the former. CreateOffer by the peer connection is implemented
3338 // asynchronously and if the peer connection is closed without resetting the
3339 // WebRTC session description factory, the session description factory would
3340 // call the transport controller.
3341 webrtc_session_desc_factory_.reset();
3342 transport_controller_.reset();
3343
deadbeef42a42632017-03-10 15:18:00 -08003344 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003345 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3346 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003347
Steve Anton978b8762017-09-29 12:15:02 -07003348 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003349 call_.reset();
3350 // The event log must outlive call (and any other object that uses it).
3351 event_log_.reset();
3352 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003353 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003354 // The .h file says that observer can be discarded after close() returns.
3355 // Make sure this is true.
3356 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
Steve Antonad182762018-09-05 20:22:40 +00003359void PeerConnection::OnMessage(rtc::Message* msg) {
3360 switch (msg->message_id) {
3361 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3362 SetSessionDescriptionMsg* param =
3363 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3364 param->observer->OnSuccess();
3365 delete param;
3366 break;
3367 }
3368 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3369 SetSessionDescriptionMsg* param =
3370 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3371 param->observer->OnFailure(std::move(param->error));
3372 delete param;
3373 break;
3374 }
3375 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3376 CreateSessionDescriptionMsg* param =
3377 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3378 param->observer->OnFailure(std::move(param->error));
3379 delete param;
3380 break;
3381 }
3382 case MSG_GETSTATS: {
3383 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3384 StatsReports reports;
3385 stats_->GetStats(param->track, &reports);
3386 param->observer->OnComplete(reports);
3387 delete param;
3388 break;
3389 }
3390 case MSG_FREE_DATACHANNELS: {
3391 sctp_data_channels_to_free_.clear();
3392 break;
3393 }
3394 case MSG_REPORT_USAGE_PATTERN: {
3395 ReportUsagePattern();
3396 break;
3397 }
3398 default:
3399 RTC_NOTREACHED() << "Not implemented";
3400 break;
3401 }
3402}
3403
Steve Antonafb0bb72018-02-20 11:35:37 -08003404cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3405 RTC_DCHECK(!IsUnifiedPlan());
3406 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3407 GetAudioTransceiver()->internal()->channel());
3408 if (voice_channel) {
3409 return voice_channel->media_channel();
3410 } else {
3411 return nullptr;
3412 }
3413}
3414
3415cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3416 RTC_DCHECK(!IsUnifiedPlan());
3417 auto* video_channel = static_cast<cricket::VideoChannel*>(
3418 GetVideoTransceiver()->internal()->channel());
3419 if (video_channel) {
3420 return video_channel->media_channel();
3421 } else {
3422 return nullptr;
3423 }
3424}
3425
Steve Anton4171afb2017-11-20 10:20:22 -08003426void PeerConnection::CreateAudioReceiver(
3427 MediaStreamInterface* stream,
3428 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003429 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3430 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003431 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3432 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003433 auto* audio_receiver = new AudioRtpReceiver(
3434 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003435 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003436 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3437 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3438 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003439 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003440 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003441 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003442}
3443
Steve Anton4171afb2017-11-20 10:20:22 -08003444void PeerConnection::CreateVideoReceiver(
3445 MediaStreamInterface* stream,
3446 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003447 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3448 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003449 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3450 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003451 auto* video_receiver = new VideoRtpReceiver(
3452 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003453 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003454 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3455 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3456 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003457 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003458 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003459 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003460}
3461
deadbeef70ab1a12015-09-28 16:53:55 -07003462// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3463// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003464rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003465 const RtpSenderInfo& remote_sender_info) {
3466 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3467 if (!receiver) {
3468 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3469 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003470 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003471 }
Steve Anton4171afb2017-11-20 10:20:22 -08003472 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3473 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3474 } else {
3475 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3476 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003477 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003478}
3479
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003480void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3481 MediaStreamInterface* stream) {
3482 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003483 RTC_DCHECK(track);
3484 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003485 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003486 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003487 // We already have a sender for this track, so just change the stream_id
3488 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003489 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003490 return;
3491 }
3492
3493 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003494 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003495 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003496 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003497 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003498 // If the sender has already been configured in SDP, we call SetSsrc,
3499 // which will connect the sender to the underlying transport. This can
3500 // occur if a local session description that contains the ID of the sender
3501 // is set before AddStream is called. It can also occur if the local
3502 // session description is not changed and RemoveStream is called, and
3503 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003504 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003505 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003506 if (sender_info) {
3507 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003508 }
3509}
3510
3511// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3512// indefinitely, when we have unified plan SDP.
3513void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3514 MediaStreamInterface* stream) {
3515 RTC_DCHECK(!IsClosed());
3516 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003517 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003518 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3519 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003520 return;
3521 }
Steve Anton4171afb2017-11-20 10:20:22 -08003522 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003523}
3524
3525void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3526 MediaStreamInterface* stream) {
3527 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003528 RTC_DCHECK(track);
3529 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003530 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003531 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003532 // We already have a sender for this track, so just change the stream_id
3533 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003534 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003535 return;
3536 }
3537
3538 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003539 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003540 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003541 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003542 GetVideoTransceiver()->internal()->AddSender(new_sender);
3543 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003544 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003545 if (sender_info) {
3546 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003547 }
3548}
3549
3550void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3551 MediaStreamInterface* stream) {
3552 RTC_DCHECK(!IsClosed());
3553 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003554 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003555 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3556 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003557 return;
3558 }
Steve Anton4171afb2017-11-20 10:20:22 -08003559 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003560}
3561
Steve Antonba818672017-11-06 10:21:57 -08003562void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003563 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003564 if (ice_connection_state_ == new_state) {
3565 return;
3566 }
3567
deadbeefcbecd352015-09-23 11:50:27 -07003568 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003569 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003570 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003571 return;
3572 }
Steve Antonba818672017-11-06 10:21:57 -08003573
Mirko Bonadei675513b2017-11-09 11:09:25 +01003574 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3575 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003576 RTC_DCHECK(ice_connection_state_ !=
3577 PeerConnectionInterface::kIceConnectionClosed);
3578
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003579 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003580 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003581}
3582
Jonas Olsson635474e2018-10-18 15:58:17 +02003583void PeerConnection::SetStandardizedIceConnectionState(
3584 PeerConnectionInterface::IceConnectionState new_state) {
3585 RTC_DCHECK(signaling_thread()->IsCurrent());
3586 if (standardized_ice_connection_state_ == new_state)
3587 return;
3588 if (IsClosed())
3589 return;
3590 standardized_ice_connection_state_ = new_state;
3591 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3592 // the old one once disconnects are handled properly.
3593}
3594
3595void PeerConnection::SetConnectionState(
3596 PeerConnectionInterface::PeerConnectionState new_state) {
3597 RTC_DCHECK(signaling_thread()->IsCurrent());
3598 if (connection_state_ == new_state)
3599 return;
3600 if (IsClosed())
3601 return;
3602 connection_state_ = new_state;
3603 Observer()->OnConnectionChange(new_state);
3604}
3605
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003606void PeerConnection::OnIceGatheringChange(
3607 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003608 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003609 if (IsClosed()) {
3610 return;
3611 }
3612 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003613 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003614}
3615
jbauch81bf7b02017-03-25 08:31:12 -07003616void PeerConnection::OnIceCandidate(
3617 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003618 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003619 if (IsClosed()) {
3620 return;
3621 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003622 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003623 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3624 candidate->candidate().address().IsPrivateIP()) {
3625 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3626 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003627 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003628}
3629
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003630void PeerConnection::OnIceCandidatesRemoved(
3631 const std::vector<cricket::Candidate>& candidates) {
3632 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003633 if (IsClosed()) {
3634 return;
3635 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003636 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003637}
3638
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003639void PeerConnection::ChangeSignalingState(
3640 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003641 RTC_DCHECK(signaling_thread()->IsCurrent());
3642 if (signaling_state_ == signaling_state) {
3643 return;
3644 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003645 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3646 << GetSignalingStateString(signaling_state_)
3647 << " New state: "
3648 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003649 signaling_state_ = signaling_state;
3650 if (signaling_state == kClosed) {
3651 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003652 Observer()->OnIceConnectionChange(ice_connection_state_);
Jonas Olsson635474e2018-10-18 15:58:17 +02003653 standardized_ice_connection_state_ =
3654 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
3655 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3656 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003657 if (ice_gathering_state_ != kIceGatheringComplete) {
3658 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003659 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003660 }
3661 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003662 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003663}
3664
deadbeefeb459812015-12-15 19:24:43 -08003665void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3666 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003667 if (IsClosed()) {
3668 return;
3669 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003670 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003671 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003672}
3673
deadbeefeb459812015-12-15 19:24:43 -08003674void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3675 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003676 if (IsClosed()) {
3677 return;
3678 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003679 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003680 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003681}
3682
3683void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3684 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003685 if (IsClosed()) {
3686 return;
3687 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003688 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003689 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003690}
3691
3692void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3693 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003694 if (IsClosed()) {
3695 return;
3696 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003697 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003698 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003699}
3700
Henrik Boström31638672017-11-23 17:48:32 +01003701void PeerConnection::PostSetSessionDescriptionSuccess(
3702 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003703 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3704 signaling_thread()->Post(RTC_FROM_HERE, this,
3705 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003706}
3707
deadbeefab9b2d12015-10-14 11:33:11 -07003708void PeerConnection::PostSetSessionDescriptionFailure(
3709 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003710 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003711 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003712 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3713 msg->error = std::move(error);
3714 signaling_thread()->Post(RTC_FROM_HERE, this,
3715 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003716}
3717
3718void PeerConnection::PostCreateSessionDescriptionFailure(
3719 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003720 RTCError error) {
3721 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003722 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3723 msg->error = std::move(error);
3724 signaling_thread()->Post(RTC_FROM_HERE, this,
3725 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003726}
3727
zhihuang1c378ed2017-08-17 14:10:50 -07003728void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003729 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003730 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003731 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003732
Steve Antondcc3c022017-12-22 16:02:54 -08003733 if (IsUnifiedPlan()) {
3734 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3735 } else {
3736 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3737 }
3738
Steve Antonfa2260d2017-12-28 16:38:23 -08003739 // Intentionally unset the data channel type for RTP data channel with the
3740 // second condition. Otherwise the RTP data channels would be successfully
3741 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3742 // when building with chromium. We want to leave RTP data channels broken, so
3743 // people won't try to use them.
3744 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3745 session_options->data_channel_type = data_channel_type();
3746 }
3747
Steve Antondcc3c022017-12-22 16:02:54 -08003748 // Apply ICE restart flag and renomination flag.
3749 for (auto& options : session_options->media_description_options) {
3750 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3751 options.transport_options.enable_ice_renomination =
3752 configuration_.enable_ice_renomination;
3753 }
3754
3755 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003756 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08003757 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003758 session_options->pooled_ice_credentials =
3759 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3760 RTC_FROM_HERE,
3761 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3762 port_allocator_.get()));
Steve Antondcc3c022017-12-22 16:02:54 -08003763}
3764
3765void PeerConnection::GetOptionsForPlanBOffer(
3766 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3767 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003768 // Figure out transceiver directional preferences.
3769 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3770 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3771
3772 // By default, generate sendrecv/recvonly m= sections.
3773 bool recv_audio = true;
3774 bool recv_video = true;
3775
3776 // By default, only offer a new m= section if we have media to send with it.
3777 bool offer_new_audio_description = send_audio;
3778 bool offer_new_video_description = send_video;
3779 bool offer_new_data_description = HasDataChannels();
3780
3781 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003782 if (offer_answer_options.offer_to_receive_audio !=
3783 RTCOfferAnswerOptions::kUndefined) {
3784 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003785 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003786 offer_new_audio_description ||
3787 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003788 }
Steve Antondcc3c022017-12-22 16:02:54 -08003789 if (offer_answer_options.offer_to_receive_video !=
3790 RTCOfferAnswerOptions::kUndefined) {
3791 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003792 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003793 offer_new_video_description ||
3794 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003795 }
3796
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003797 absl::optional<size_t> audio_index;
3798 absl::optional<size_t> video_index;
3799 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003800 // If a current description exists, generate m= sections in the same order,
3801 // using the first audio/video/data section that appears and rejecting
3802 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003803 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003804 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003805 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003806 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3807 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3808 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003809 }
3810
zhihuang1c378ed2017-08-17 14:10:50 -07003811 // Add audio/video/data m= sections to the end if needed.
3812 if (!audio_index && offer_new_audio_description) {
3813 session_options->media_description_options.push_back(
3814 cricket::MediaDescriptionOptions(
3815 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003816 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3817 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003818 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003819 }
zhihuang1c378ed2017-08-17 14:10:50 -07003820 if (!video_index && offer_new_video_description) {
3821 session_options->media_description_options.push_back(
3822 cricket::MediaDescriptionOptions(
3823 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003824 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3825 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003826 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003827 }
zhihuang1c378ed2017-08-17 14:10:50 -07003828 if (!data_index && offer_new_data_description) {
3829 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003830 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003831 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003832 }
3833
3834 cricket::MediaDescriptionOptions* audio_media_description_options =
3835 !audio_index ? nullptr
3836 : &session_options->media_description_options[*audio_index];
3837 cricket::MediaDescriptionOptions* video_media_description_options =
3838 !video_index ? nullptr
3839 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003840
Steve Anton4171afb2017-11-20 10:20:22 -08003841 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003842 video_media_description_options,
3843 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003844}
3845
3846// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3847// and return a reference to it.
3848// Generated MIDs should be no more than 3 bytes long to take up less space in
3849// the RTP packet.
3850static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3851 RTC_DCHECK(used_mids);
3852 // We're boring: just generate MIDs 0, 1, 2, ...
3853 size_t i = 0;
3854 std::set<std::string>::iterator it;
3855 bool inserted;
3856 do {
3857 std::string mid = rtc::ToString(i++);
3858 auto insert_result = used_mids->insert(mid);
3859 it = insert_result.first;
3860 inserted = insert_result.second;
3861 } while (!inserted);
3862 return *it;
3863}
3864
3865static cricket::MediaDescriptionOptions
3866GetMediaDescriptionOptionsForTransceiver(
3867 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3868 transceiver,
3869 const std::string& mid) {
3870 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003871 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003872 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003873 // This behavior is specified in JSEP. The gist is that:
3874 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3875 // sendrecv.
3876 // 2. If the MSID is included, then it must be included in any subsequent
3877 // offer/answer exactly the same until the RtpTransceiver is stopped.
3878 if (!transceiver->stopped() &&
3879 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3880 transceiver->internal()->has_ever_been_used_to_send())) {
3881 cricket::SenderOptions sender_options;
3882 sender_options.track_id = transceiver->sender()->id();
3883 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003884 int num_send_encoding_layers =
3885 transceiver->sender()->init_send_encodings().size();
3886 sender_options.num_sim_layers =
3887 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003888 media_description_options.sender_options.push_back(sender_options);
3889 }
Steve Antondcc3c022017-12-22 16:02:54 -08003890 return media_description_options;
3891}
3892
3893void PeerConnection::GetOptionsForUnifiedPlanOffer(
3894 const RTCOfferAnswerOptions& offer_answer_options,
3895 cricket::MediaSessionOptions* session_options) {
3896 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3897 // Offers) and 5.2.2 (Subsequent Offers).
3898 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3899 const ContentInfos& local_contents =
3900 (local_description() ? local_description()->description()->contents()
3901 : ContentInfos());
3902 const ContentInfos& remote_contents =
3903 (remote_description() ? remote_description()->description()->contents()
3904 : ContentInfos());
3905 // The mline indices that can be recycled. New transceivers should reuse these
3906 // slots first.
3907 std::queue<size_t> recycleable_mline_indices;
3908 // Track the MIDs used in previous offer/answer exchanges and the current
3909 // offer so that new, unique MIDs are generated.
3910 std::set<std::string> used_mids = seen_mids_;
3911 // First, go through each media section that exists in either the local or
3912 // remote description and generate a media section in this offer for the
3913 // associated transceiver. If a media section can be recycled, generate a
3914 // default, rejected media section here that can be later overwritten.
3915 for (size_t i = 0;
3916 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3917 // Either |local_content| or |remote_content| is non-null.
3918 const ContentInfo* local_content =
3919 (i < local_contents.size() ? &local_contents[i] : nullptr);
3920 const ContentInfo* remote_content =
3921 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3922 bool had_been_rejected = (local_content && local_content->rejected) ||
3923 (remote_content && remote_content->rejected);
3924 const std::string& mid =
3925 (local_content ? local_content->name : remote_content->name);
3926 cricket::MediaType media_type =
3927 (local_content ? local_content->media_description()->type()
3928 : remote_content->media_description()->type());
3929 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3930 media_type == cricket::MEDIA_TYPE_VIDEO) {
3931 auto transceiver = GetAssociatedTransceiver(mid);
3932 RTC_CHECK(transceiver);
3933 // A media section is considered eligible for recycling if it is marked as
3934 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003935 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003936 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003937 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3938 RtpTransceiverDirection::kInactive,
3939 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003940 recycleable_mline_indices.push(i);
3941 } else {
3942 session_options->media_description_options.push_back(
3943 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3944 // CreateOffer shouldn't really cause any state changes in
3945 // PeerConnection, but we need a way to match new transceivers to new
3946 // media sections in SetLocalDescription and JSEP specifies this is done
3947 // by recording the index of the media section generated for the
3948 // transceiver in the offer.
3949 transceiver->internal()->set_mline_index(i);
3950 }
3951 } else {
3952 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003953 RTC_CHECK(GetDataMid());
3954 if (had_been_rejected || mid != *GetDataMid()) {
3955 session_options->media_description_options.push_back(
3956 GetMediaDescriptionOptionsForRejectedData(mid));
3957 } else {
3958 session_options->media_description_options.push_back(
3959 GetMediaDescriptionOptionsForActiveData(mid));
3960 }
Steve Antondcc3c022017-12-22 16:02:54 -08003961 }
3962 }
3963 // Next, look for transceivers that are newly added (that is, are not stopped
3964 // and not associated). Reuse media sections marked as recyclable first,
3965 // otherwise append to the end of the offer. New media sections should be
3966 // added in the order they were added to the PeerConnection.
3967 for (auto transceiver : transceivers_) {
3968 if (transceiver->mid() || transceiver->stopped()) {
3969 continue;
3970 }
3971 size_t mline_index;
3972 if (!recycleable_mline_indices.empty()) {
3973 mline_index = recycleable_mline_indices.front();
3974 recycleable_mline_indices.pop();
3975 session_options->media_description_options[mline_index] =
3976 GetMediaDescriptionOptionsForTransceiver(transceiver,
3977 AllocateMid(&used_mids));
3978 } else {
3979 mline_index = session_options->media_description_options.size();
3980 session_options->media_description_options.push_back(
3981 GetMediaDescriptionOptionsForTransceiver(transceiver,
3982 AllocateMid(&used_mids)));
3983 }
3984 // See comment above for why CreateOffer changes the transceiver's state.
3985 transceiver->internal()->set_mline_index(mline_index);
3986 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003987 // Lastly, add a m-section if we have local data channels and an m section
3988 // does not already exist.
3989 if (!GetDataMid() && HasDataChannels()) {
3990 session_options->media_description_options.push_back(
3991 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3992 }
Steve Antondcc3c022017-12-22 16:02:54 -08003993}
3994
3995void PeerConnection::GetOptionsForAnswer(
3996 const RTCOfferAnswerOptions& offer_answer_options,
3997 cricket::MediaSessionOptions* session_options) {
3998 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3999
4000 if (IsUnifiedPlan()) {
4001 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4002 } else {
4003 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4004 }
4005
Steve Antonfa2260d2017-12-28 16:38:23 -08004006 // Intentionally unset the data channel type for RTP data channel. Otherwise
4007 // the RTP data channels would be successfully negotiated by default and the
4008 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4009 // We want to leave RTP data channels broken, so people won't try to use them.
4010 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4011 session_options->data_channel_type = data_channel_type();
4012 }
4013
Steve Antondcc3c022017-12-22 16:02:54 -08004014 // Apply ICE renomination flag.
4015 for (auto& options : session_options->media_description_options) {
4016 options.transport_options.enable_ice_renomination =
4017 configuration_.enable_ice_renomination;
4018 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004019
4020 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004021 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08004022 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004023 session_options->pooled_ice_credentials =
4024 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4025 RTC_FROM_HERE,
4026 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4027 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004028}
4029
Steve Antondcc3c022017-12-22 16:02:54 -08004030void PeerConnection::GetOptionsForPlanBAnswer(
4031 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004032 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004033 // Figure out transceiver directional preferences.
4034 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4035 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4036
4037 // By default, generate sendrecv/recvonly m= sections. The direction is also
4038 // restricted by the direction in the offer.
4039 bool recv_audio = true;
4040 bool recv_video = true;
4041
4042 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004043 if (offer_answer_options.offer_to_receive_audio !=
4044 RTCOfferAnswerOptions::kUndefined) {
4045 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004046 }
Steve Antondcc3c022017-12-22 16:02:54 -08004047 if (offer_answer_options.offer_to_receive_video !=
4048 RTCOfferAnswerOptions::kUndefined) {
4049 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004050 }
4051
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004052 absl::optional<size_t> audio_index;
4053 absl::optional<size_t> video_index;
4054 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004055
4056 // Generate m= sections that match those in the offer.
4057 // Note that mediasession.cc will handle intersection our preferred
4058 // direction with the offered direction.
4059 GenerateMediaDescriptionOptions(
4060 remote_description(),
4061 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4062 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4063 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004064
4065 cricket::MediaDescriptionOptions* audio_media_description_options =
4066 !audio_index ? nullptr
4067 : &session_options->media_description_options[*audio_index];
4068 cricket::MediaDescriptionOptions* video_media_description_options =
4069 !video_index ? nullptr
4070 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004071
Steve Anton4171afb2017-11-20 10:20:22 -08004072 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004073 video_media_description_options,
4074 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004075}
zhihuangaf388472016-11-02 16:49:48 -07004076
Steve Antondcc3c022017-12-22 16:02:54 -08004077void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4078 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4079 cricket::MediaSessionOptions* session_options) {
4080 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4081 // Answers) and 5.3.2 (Subsequent Answers).
4082 RTC_DCHECK(remote_description());
4083 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4084 for (const ContentInfo& content :
4085 remote_description()->description()->contents()) {
4086 cricket::MediaType media_type = content.media_description()->type();
4087 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4088 media_type == cricket::MEDIA_TYPE_VIDEO) {
4089 auto transceiver = GetAssociatedTransceiver(content.name);
4090 RTC_CHECK(transceiver);
4091 session_options->media_description_options.push_back(
4092 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4093 } else {
4094 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004095 // Reject all data sections if data channels are disabled.
4096 // Reject a data section if it has already been rejected.
4097 // Reject all data sections except for the first one.
4098 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4099 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004100 session_options->media_description_options.push_back(
4101 GetMediaDescriptionOptionsForRejectedData(content.name));
4102 } else {
4103 session_options->media_description_options.push_back(
4104 GetMediaDescriptionOptionsForActiveData(content.name));
4105 }
Steve Antondcc3c022017-12-22 16:02:54 -08004106 }
4107 }
htaa2a49d92016-03-04 02:51:39 -08004108}
4109
zhihuang1c378ed2017-08-17 14:10:50 -07004110void PeerConnection::GenerateMediaDescriptionOptions(
4111 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004112 RtpTransceiverDirection audio_direction,
4113 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004114 absl::optional<size_t>* audio_index,
4115 absl::optional<size_t>* video_index,
4116 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004117 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004118 for (const cricket::ContentInfo& content :
4119 session_desc->description()->contents()) {
4120 if (IsAudioContent(&content)) {
4121 // If we already have an audio m= section, reject this extra one.
4122 if (*audio_index) {
4123 session_options->media_description_options.push_back(
4124 cricket::MediaDescriptionOptions(
4125 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004126 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004127 } else {
4128 session_options->media_description_options.push_back(
4129 cricket::MediaDescriptionOptions(
4130 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004131 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004132 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004133 }
4134 } else if (IsVideoContent(&content)) {
4135 // If we already have an video m= section, reject this extra one.
4136 if (*video_index) {
4137 session_options->media_description_options.push_back(
4138 cricket::MediaDescriptionOptions(
4139 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004140 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004141 } else {
4142 session_options->media_description_options.push_back(
4143 cricket::MediaDescriptionOptions(
4144 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004145 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004146 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004147 }
4148 } else {
4149 RTC_DCHECK(IsDataContent(&content));
4150 // If we already have an data m= section, reject this extra one.
4151 if (*data_index) {
4152 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004153 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004154 } else {
4155 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004156 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004157 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004158 }
4159 }
htaa2a49d92016-03-04 02:51:39 -08004160 }
deadbeefab9b2d12015-10-14 11:33:11 -07004161}
4162
Steve Antonfa2260d2017-12-28 16:38:23 -08004163cricket::MediaDescriptionOptions
4164PeerConnection::GetMediaDescriptionOptionsForActiveData(
4165 const std::string& mid) const {
4166 // Direction for data sections is meaningless, but legacy endpoints might
4167 // expect sendrecv.
4168 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4169 RtpTransceiverDirection::kSendRecv,
4170 /*stopped=*/false);
4171 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4172 return options;
4173}
4174
4175cricket::MediaDescriptionOptions
4176PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4177 const std::string& mid) const {
4178 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4179 RtpTransceiverDirection::kInactive,
4180 /*stopped=*/true);
4181 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4182 return options;
4183}
4184
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004185absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004186 switch (data_channel_type_) {
4187 case cricket::DCT_RTP:
4188 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004189 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004190 }
4191 return rtp_data_channel_->content_name();
4192 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004193 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004194 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004195 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004196 }
4197}
4198
Steve Anton4171afb2017-11-20 10:20:22 -08004199void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4200 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4201 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004202 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004203}
4204
Steve Anton4171afb2017-11-20 10:20:22 -08004205void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004206 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004207 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004208 cricket::MediaType media_type,
4209 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004210 RTC_DCHECK(!IsUnifiedPlan());
4211
Steve Anton4171afb2017-11-20 10:20:22 -08004212 std::vector<RtpSenderInfo>* current_senders =
4213 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004214
Steve Anton4171afb2017-11-20 10:20:22 -08004215 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004216 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004217 for (auto sender_it = current_senders->begin();
4218 sender_it != current_senders->end();
4219 /* incremented manually */) {
4220 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004221 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004222 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004223 std::string params_stream_id;
4224 if (params) {
4225 params_stream_id =
4226 (!params->first_stream_id().empty() ? params->first_stream_id()
4227 : kDefaultStreamId);
4228 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004229 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004230 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004231 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004232 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004233 sender_exists) {
4234 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004235 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004236 OnRemoteSenderRemoved(info, media_type);
4237 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004238 }
4239 }
4240
Steve Anton4171afb2017-11-20 10:20:22 -08004241 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004242 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004243 if (!params.has_ssrcs()) {
4244 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4245 // sender, this means it is coming from a Unified Plan endpoint,so we just
4246 // create a default.
4247 default_sender_needed = true;
4248 break;
4249 }
4250
Seth Hampson845e8782018-03-02 11:34:10 -08004251 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004252 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004253 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4254 // not supported in Plan B, we just take the first here and create the
4255 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004256 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004257 (!params.first_stream_id().empty() ? params.first_stream_id()
4258 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004259 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004260 uint32_t ssrc = params.first_ssrc();
4261
4262 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004263 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004264 if (!stream) {
4265 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004266 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004267 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004268 remote_streams_->AddStream(stream);
4269 new_streams->AddStream(stream);
4270 }
4271
Steve Anton4171afb2017-11-20 10:20:22 -08004272 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004273 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004274 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004275 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004276 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004277 }
4278 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004279
Steve Anton4171afb2017-11-20 10:20:22 -08004280 // Add default sender if necessary.
4281 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004282 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004283 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004284 if (!default_stream) {
4285 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004286 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004287 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004288 remote_streams_->AddStream(default_stream);
4289 new_streams->AddStream(default_stream);
4290 }
Steve Anton4171afb2017-11-20 10:20:22 -08004291 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4292 ? kDefaultAudioSenderId
4293 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004294 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004295 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004296 if (!default_sender_info) {
4297 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004298 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004299 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004300 }
4301 }
deadbeefab9b2d12015-10-14 11:33:11 -07004302}
4303
Steve Anton4171afb2017-11-20 10:20:22 -08004304void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4305 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004306 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4307 << " receiver for track_id=" << sender_info.sender_id
4308 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004309
Steve Anton3d954a62018-04-02 11:27:23 -07004310 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004311 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004312 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004313 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004314 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004315 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004316 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004317 }
4318}
4319
Steve Anton4171afb2017-11-20 10:20:22 -08004320void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4321 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004322 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4323 << " receiver for track_id=" << sender_info.sender_id
4324 << " and stream_id=" << sender_info.stream_id;
4325
Seth Hampson845e8782018-03-02 11:34:10 -08004326 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004327
Henrik Boström933d8b02017-10-10 10:05:16 -07004328 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004329 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004330 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4331 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004332 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004333 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004334 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004335 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004336 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004337 }
4338 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004339 // Stopping or destroying a VideoRtpReceiver will end the
4340 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004341 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004342 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004343 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004344 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004345 // There's no guarantee the track is still available, e.g. the track may
4346 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004347 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004348 }
4349 } else {
nisseede5da42017-01-12 05:15:36 -08004350 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004351 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004352 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004353 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004354 }
deadbeefab9b2d12015-10-14 11:33:11 -07004355}
4356
4357void PeerConnection::UpdateEndedRemoteMediaStreams() {
4358 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4359 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4360 MediaStreamInterface* stream = remote_streams_->at(i);
4361 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4362 streams_to_remove.push_back(stream);
4363 }
4364 }
4365
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004366 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004367 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004368 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004369 }
4370}
4371
Steve Anton4171afb2017-11-20 10:20:22 -08004372void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004373 const std::vector<cricket::StreamParams>& streams,
4374 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004375 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004376
Seth Hampson845e8782018-03-02 11:34:10 -08004377 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004378 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004379 for (auto sender_it = current_senders->begin();
4380 sender_it != current_senders->end();
4381 /* incremented manually */) {
4382 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004383 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004384 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4385 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004386 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004387 OnLocalSenderRemoved(info, media_type);
4388 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004389 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004390 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004391 }
4392 }
4393
Steve Anton4171afb2017-11-20 10:20:22 -08004394 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004395 for (const cricket::StreamParams& params : streams) {
4396 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004397 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004398 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004399 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004400 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004401 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004402 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004403 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004404 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004405 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004406 }
4407 }
4408}
4409
Steve Anton4171afb2017-11-20 10:20:22 -08004410void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4411 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004412 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004413 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004414 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004415 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4416 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004417 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004418 return;
4419 }
4420
deadbeeffac06552015-11-25 11:26:01 -08004421 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004422 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004423 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004424 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004425 }
deadbeeffac06552015-11-25 11:26:01 -08004426
Seth Hampson5b4f0752018-04-02 16:31:36 -07004427 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004428 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004429}
4430
Steve Anton4171afb2017-11-20 10:20:22 -08004431void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4432 cricket::MediaType media_type) {
4433 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004434 if (!sender) {
4435 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004436 // SessionDescriptions has been renegotiated.
4437 return;
4438 }
deadbeeffac06552015-11-25 11:26:01 -08004439
4440 // A sender has been removed from the SessionDescription but it's still
4441 // associated with the PeerConnection. This only occurs if the SDP doesn't
4442 // match with the calls to CreateSender, AddStream and RemoveStream.
4443 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004444 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004445 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004446 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004447 }
deadbeeffac06552015-11-25 11:26:01 -08004448
Steve Anton4171afb2017-11-20 10:20:22 -08004449 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004450}
4451
4452void PeerConnection::UpdateLocalRtpDataChannels(
4453 const cricket::StreamParamsVec& streams) {
4454 std::vector<std::string> existing_channels;
4455
4456 // Find new and active data channels.
4457 for (const cricket::StreamParams& params : streams) {
4458 // |it->sync_label| is actually the data channel label. The reason is that
4459 // we use the same naming of data channels as we do for
4460 // MediaStreams and Tracks.
4461 // For MediaStreams, the sync_label is the MediaStream label and the
4462 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004463 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004464 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004465 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004466 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004467 continue;
4468 }
4469 // Set the SSRC the data channel should use for sending.
4470 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4471 existing_channels.push_back(data_channel_it->first);
4472 }
4473
4474 UpdateClosingRtpDataChannels(existing_channels, true);
4475}
4476
4477void PeerConnection::UpdateRemoteRtpDataChannels(
4478 const cricket::StreamParamsVec& streams) {
4479 std::vector<std::string> existing_channels;
4480
4481 // Find new and active data channels.
4482 for (const cricket::StreamParams& params : streams) {
4483 // The data channel label is either the mslabel or the SSRC if the mslabel
4484 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004485 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004486 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004487 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004488 auto data_channel_it = rtp_data_channels_.find(label);
4489 if (data_channel_it == rtp_data_channels_.end()) {
4490 // This is a new data channel.
4491 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4492 } else {
4493 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4494 }
4495 existing_channels.push_back(label);
4496 }
4497
4498 UpdateClosingRtpDataChannels(existing_channels, false);
4499}
4500
4501void PeerConnection::UpdateClosingRtpDataChannels(
4502 const std::vector<std::string>& active_channels,
4503 bool is_local_update) {
4504 auto it = rtp_data_channels_.begin();
4505 while (it != rtp_data_channels_.end()) {
4506 DataChannel* data_channel = it->second;
4507 if (std::find(active_channels.begin(), active_channels.end(),
4508 data_channel->label()) != active_channels.end()) {
4509 ++it;
4510 continue;
4511 }
4512
4513 if (is_local_update) {
4514 data_channel->SetSendSsrc(0);
4515 } else {
4516 data_channel->RemotePeerRequestClose();
4517 }
4518
4519 if (data_channel->state() == DataChannel::kClosed) {
4520 rtp_data_channels_.erase(it);
4521 it = rtp_data_channels_.begin();
4522 } else {
4523 ++it;
4524 }
4525 }
4526}
4527
4528void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4529 uint32_t remote_ssrc) {
4530 rtc::scoped_refptr<DataChannel> channel(
4531 InternalCreateDataChannel(label, nullptr));
4532 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004533 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004534 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004535 return;
4536 }
4537 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004538 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4539 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004540 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004541}
4542
4543rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4544 const std::string& label,
4545 const InternalDataChannelInit* config) {
4546 if (IsClosed()) {
4547 return nullptr;
4548 }
Steve Anton75737c02017-11-06 10:37:17 -08004549 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004550 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004551 << "InternalCreateDataChannel: Data is not supported in this call.";
4552 return nullptr;
4553 }
4554 InternalDataChannelInit new_config =
4555 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004556 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004557 if (new_config.id < 0) {
4558 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004559 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004560 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004561 RTC_LOG(LS_ERROR)
4562 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004563 return nullptr;
4564 }
4565 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004566 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004567 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004568 return nullptr;
4569 }
4570 }
4571
Steve Anton75737c02017-11-06 10:37:17 -08004572 rtc::scoped_refptr<DataChannel> channel(
4573 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004574 if (!channel) {
4575 sid_allocator_.ReleaseSid(new_config.id);
4576 return nullptr;
4577 }
4578
4579 if (channel->data_channel_type() == cricket::DCT_RTP) {
4580 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004581 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4582 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004583 return nullptr;
4584 }
4585 rtp_data_channels_[channel->label()] = channel;
4586 } else {
4587 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4588 sctp_data_channels_.push_back(channel);
4589 channel->SignalClosed.connect(this,
4590 &PeerConnection::OnSctpDataChannelClosed);
4591 }
4592
Steve Anton2d8609c2018-01-23 16:38:46 -08004593 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004594 return channel;
4595}
4596
4597bool PeerConnection::HasDataChannels() const {
4598 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4599}
4600
4601void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4602 for (const auto& channel : sctp_data_channels_) {
4603 if (channel->id() < 0) {
4604 int sid;
4605 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004606 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004607 continue;
4608 }
4609 channel->SetSctpSid(sid);
4610 }
4611 }
4612}
4613
4614void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004615 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004616 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4617 ++it) {
4618 if (it->get() == channel) {
4619 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004620 // After the closing procedure is done, it's safe to use this ID for
4621 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004622 sid_allocator_.ReleaseSid(channel->id());
4623 }
deadbeefbd292462015-12-14 18:15:29 -08004624 // Since this method is triggered by a signal from the DataChannel,
4625 // we can't free it directly here; we need to free it asynchronously.
4626 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004627 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004628 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4629 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004630 return;
4631 }
4632 }
4633}
4634
deadbeefab9b2d12015-10-14 11:33:11 -07004635void PeerConnection::OnDataChannelDestroyed() {
4636 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4637 // DataChannel may callback to us and try to modify the list.
4638 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4639 temp_rtp_dcs.swap(rtp_data_channels_);
4640 for (const auto& kv : temp_rtp_dcs) {
4641 kv.second->OnTransportChannelDestroyed();
4642 }
4643
4644 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4645 temp_sctp_dcs.swap(sctp_data_channels_);
4646 for (const auto& channel : temp_sctp_dcs) {
4647 channel->OnTransportChannelDestroyed();
4648 }
4649}
4650
4651void PeerConnection::OnDataChannelOpenMessage(
4652 const std::string& label,
4653 const InternalDataChannelInit& config) {
4654 rtc::scoped_refptr<DataChannel> channel(
4655 InternalCreateDataChannel(label, &config));
4656 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004657 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004658 return;
4659 }
4660
deadbeefa601f5c2016-06-06 14:27:39 -07004661 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4662 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004663 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004664 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004665}
4666
Steve Anton4171afb2017-11-20 10:20:22 -08004667rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4668PeerConnection::GetAudioTransceiver() const {
4669 // This method only works with Plan B SDP, where there is a single
4670 // audio/video transceiver.
4671 RTC_DCHECK(!IsUnifiedPlan());
4672 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004673 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004674 return transceiver;
4675 }
4676 }
4677 RTC_NOTREACHED();
4678 return nullptr;
4679}
4680
4681rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4682PeerConnection::GetVideoTransceiver() const {
4683 // This method only works with Plan B SDP, where there is a single
4684 // audio/video transceiver.
4685 RTC_DCHECK(!IsUnifiedPlan());
4686 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004687 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004688 return transceiver;
4689 }
4690 }
4691 RTC_NOTREACHED();
4692 return nullptr;
4693}
4694
4695// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4696// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004697bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004698 switch (type) {
4699 case cricket::MEDIA_TYPE_AUDIO:
4700 return !GetAudioTransceiver()->internal()->senders().empty();
4701 case cricket::MEDIA_TYPE_VIDEO:
4702 return !GetVideoTransceiver()->internal()->senders().empty();
4703 case cricket::MEDIA_TYPE_DATA:
4704 return false;
4705 }
4706 RTC_NOTREACHED();
4707 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004708}
4709
Steve Anton4171afb2017-11-20 10:20:22 -08004710rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4711PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4712 for (auto transceiver : transceivers_) {
4713 for (auto sender : transceiver->internal()->senders()) {
4714 if (sender->track() == track) {
4715 return sender;
4716 }
4717 }
4718 }
4719 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004720}
4721
Steve Anton4171afb2017-11-20 10:20:22 -08004722rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4723PeerConnection::FindSenderById(const std::string& sender_id) const {
4724 for (auto transceiver : transceivers_) {
4725 for (auto sender : transceiver->internal()->senders()) {
4726 if (sender->id() == sender_id) {
4727 return sender;
4728 }
4729 }
4730 }
4731 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004732}
4733
Steve Anton4171afb2017-11-20 10:20:22 -08004734rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4735PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4736 for (auto transceiver : transceivers_) {
4737 for (auto receiver : transceiver->internal()->receivers()) {
4738 if (receiver->id() == receiver_id) {
4739 return receiver;
4740 }
4741 }
4742 }
4743 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004744}
4745
Steve Anton4171afb2017-11-20 10:20:22 -08004746std::vector<PeerConnection::RtpSenderInfo>*
4747PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4748 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4749 media_type == cricket::MEDIA_TYPE_VIDEO);
4750 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4751 ? &remote_audio_sender_infos_
4752 : &remote_video_sender_infos_;
4753}
4754
4755std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004756 cricket::MediaType media_type) {
4757 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4758 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004759 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4760 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004761}
4762
Steve Anton4171afb2017-11-20 10:20:22 -08004763const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4764 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004765 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004766 const std::string sender_id) const {
4767 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004768 if (sender_info.stream_id == stream_id &&
4769 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004770 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004771 }
4772 }
4773 return nullptr;
4774}
4775
4776DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4777 for (const auto& channel : sctp_data_channels_) {
4778 if (channel->id() == sid) {
4779 return channel;
4780 }
4781 }
4782 return nullptr;
4783}
4784
deadbeef91dd5672016-05-18 16:55:30 -07004785bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004786 const cricket::ServerAddresses& stun_servers,
4787 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004788 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004789 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004790 // To handle both internal and externally created port allocator, we will
4791 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004792 port_allocator_flags_ = port_allocator_->flags();
4793 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4794 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4795 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004796 // If the disable-IPv6 flag was specified, we'll not override it
4797 // by experiment.
4798 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004799 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004800 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4801 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004802 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004803 }
4804
zhihuangb09b3f92017-03-07 14:40:51 -08004805 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004806 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004807 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004808 }
4809
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004810 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004811 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004812 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004813 }
4814
honghaiz60347052016-05-31 18:29:12 -07004815 if (configuration.candidate_network_policy ==
4816 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004817 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004818 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004819 }
4820
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004821 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004822 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004823 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4824 }
4825
Qingsi Wanga2d60672018-04-11 16:57:45 -07004826 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004827 // No step delay is used while allocating ports.
4828 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4829 port_allocator_->set_candidate_filter(
4830 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004831 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004832
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004833 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004834 for (auto& turn_server : turn_servers_copy) {
4835 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004836 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004837 // Call this last since it may create pooled allocator sessions using the
4838 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004839 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004840 stun_servers, std::move(turn_servers_copy),
4841 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4842 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004843 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004844 return true;
4845}
4846
deadbeef91dd5672016-05-18 16:55:30 -07004847bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004848 const cricket::ServerAddresses& stun_servers,
4849 const std::vector<cricket::RelayServerConfig>& turn_servers,
4850 IceTransportsType type,
4851 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004852 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004853 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004854 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004855 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004856 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004857 // According to JSEP, after setLocalDescription, changing the candidate pool
4858 // size is not allowed, and changing the set of ICE servers will not result
4859 // in new candidates being gathered.
4860 if (local_description()) {
4861 port_allocator_->FreezeCandidatePool();
4862 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004863 // Add the custom tls turn servers if they exist.
4864 auto turn_servers_copy = turn_servers;
4865 for (auto& turn_server : turn_servers_copy) {
4866 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4867 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004868 // Call this last since it may create pooled allocator sessions using the
4869 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004870 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004871 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4872 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004873}
4874
Steve Antonba818672017-11-06 10:21:57 -08004875cricket::ChannelManager* PeerConnection::channel_manager() const {
4876 return factory_->channel_manager();
4877}
4878
Elad Alon99c3fe52017-10-13 16:29:40 +02004879bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004880 std::unique_ptr<RtcEventLogOutput> output,
4881 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004882 if (!event_log_) {
4883 return false;
4884 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004885 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004886}
4887
4888void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004889 if (event_log_) {
4890 event_log_->StopLogging();
4891 }
ivoc14d5dbe2016-07-04 07:06:55 -07004892}
nisseeaabdf62017-05-05 02:23:02 -07004893
Steve Anton75737c02017-11-06 10:37:17 -08004894cricket::BaseChannel* PeerConnection::GetChannel(
4895 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004896 for (auto transceiver : transceivers_) {
4897 cricket::BaseChannel* channel = transceiver->internal()->channel();
4898 if (channel && channel->content_name() == content_name) {
4899 return channel;
4900 }
Steve Anton75737c02017-11-06 10:37:17 -08004901 }
4902 if (rtp_data_channel() &&
4903 rtp_data_channel()->content_name() == content_name) {
4904 return rtp_data_channel();
4905 }
4906 return nullptr;
4907}
4908
4909bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4910 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004911 RTC_LOG(LS_INFO)
4912 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004913 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004914 return false;
4915 }
4916 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004917 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004918 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004919 return false;
4920 }
4921
Zhi Huange830e682018-03-30 10:48:35 -07004922 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4923 if (dtls_role) {
4924 *role = *dtls_role;
4925 return true;
4926 }
4927 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004928}
4929
4930bool PeerConnection::GetSslRole(const std::string& content_name,
4931 rtc::SSLRole* role) {
4932 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004933 RTC_LOG(LS_INFO)
4934 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004935 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004936 return false;
4937 }
4938
Zhi Huange830e682018-03-30 10:48:35 -07004939 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4940 if (dtls_role) {
4941 *role = *dtls_role;
4942 return true;
4943 }
4944 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004945}
4946
Steve Antonf8470812017-12-04 10:46:21 -08004947void PeerConnection::SetSessionError(SessionError error,
4948 const std::string& error_desc) {
4949 RTC_DCHECK_RUN_ON(signaling_thread());
4950 if (error != session_error_) {
4951 session_error_ = error;
4952 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004953 }
4954}
4955
Zhi Huange830e682018-03-30 10:48:35 -07004956RTCError PeerConnection::UpdateSessionState(
4957 SdpType type,
4958 cricket::ContentSource source,
4959 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004960 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004961
4962 // If there's already a pending error then no state transition should happen.
4963 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004964 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004965
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004966 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004967 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004968 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004969 }
4970
4971 // Update the signaling state according to the specified state machine (see
4972 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004973 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004974 ChangeSignalingState(source == cricket::CS_LOCAL
4975 ? PeerConnectionInterface::kHaveLocalOffer
4976 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004977 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004978 ChangeSignalingState(source == cricket::CS_LOCAL
4979 ? PeerConnectionInterface::kHaveLocalPrAnswer
4980 : PeerConnectionInterface::kHaveRemotePrAnswer);
4981 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004982 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004983 ChangeSignalingState(PeerConnectionInterface::kStable);
4984 }
4985
4986 // Update internal objects according to the session description's media
4987 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004988 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004989 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004990 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004991 }
4992
Steve Anton8a006912017-12-04 15:25:56 -08004993 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004994}
4995
Steve Anton8a006912017-12-04 15:25:56 -08004996RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004997 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004998 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004999 const SessionDescriptionInterface* sdesc =
5000 (source == cricket::CS_LOCAL ? local_description()
5001 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005002 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005003
5004 // Push down the new SDP media section for each audio/video transceiver.
5005 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005006 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005007 FindMediaSectionForTransceiver(transceiver, sdesc);
5008 cricket::BaseChannel* channel = transceiver->internal()->channel();
5009 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005010 continue;
5011 }
5012 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005013 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005014 if (!content_desc) {
5015 continue;
5016 }
5017 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005018 bool success = (source == cricket::CS_LOCAL)
5019 ? channel->SetLocalContent(content_desc, type, &error)
5020 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005021 if (!success) {
5022 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5023 }
5024 }
5025
5026 // If using the RtpDataChannel, push down the new SDP section for it too.
5027 if (rtp_data_channel_) {
5028 const ContentInfo* data_content =
5029 cricket::GetFirstDataContent(sdesc->description());
5030 if (data_content && !data_content->rejected) {
5031 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005032 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005033 if (data_desc) {
5034 std::string error;
5035 bool success =
5036 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005037 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005038 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005039 if (!success) {
5040 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5041 std::move(error));
5042 }
Steve Anton75737c02017-11-06 10:37:17 -08005043 }
5044 }
5045 }
Steve Antoned10bd92017-12-05 10:52:59 -08005046
Steve Anton75737c02017-11-06 10:37:17 -08005047 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5048 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5049 if (sctp_transport_ && local_description() && remote_description() &&
5050 cricket::GetFirstDataContent(local_description()->description()) &&
5051 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005052 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005053 RTC_FROM_HERE,
5054 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005055 if (!success) {
5056 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5057 "Failed to push down SCTP parameters.");
5058 }
Steve Anton75737c02017-11-06 10:37:17 -08005059 }
Steve Antoned10bd92017-12-05 10:52:59 -08005060
Steve Anton8a006912017-12-04 15:25:56 -08005061 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005062}
5063
5064bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5065 RTC_DCHECK(network_thread()->IsCurrent());
5066 RTC_DCHECK(local_description());
5067 RTC_DCHECK(remote_description());
5068 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5069 // When we support "max-message-size", that would also be pushed down here.
5070 return sctp_transport_->Start(
5071 GetSctpPort(local_description()->description()),
5072 GetSctpPort(remote_description()->description()));
5073}
5074
Steve Anton8a006912017-12-04 15:25:56 -08005075RTCError PeerConnection::PushdownTransportDescription(
5076 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005077 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005078 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005079
Zhi Huange830e682018-03-30 10:48:35 -07005080 if (source == cricket::CS_LOCAL) {
5081 const SessionDescriptionInterface* sdesc = local_description();
5082 RTC_DCHECK(sdesc);
5083 return transport_controller_->SetLocalDescription(type,
5084 sdesc->description());
5085 } else {
5086 const SessionDescriptionInterface* sdesc = remote_description();
5087 RTC_DCHECK(sdesc);
5088 return transport_controller_->SetRemoteDescription(type,
5089 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005090 }
Steve Anton75737c02017-11-06 10:37:17 -08005091}
5092
5093bool PeerConnection::GetTransportDescription(
5094 const SessionDescription* description,
5095 const std::string& content_name,
5096 cricket::TransportDescription* tdesc) {
5097 if (!description || !tdesc) {
5098 return false;
5099 }
5100 const TransportInfo* transport_info =
5101 description->GetTransportInfoByName(content_name);
5102 if (!transport_info) {
5103 return false;
5104 }
5105 *tdesc = transport_info->description;
5106 return true;
5107}
5108
Steve Anton75737c02017-11-06 10:37:17 -08005109cricket::IceConfig PeerConnection::ParseIceConfig(
5110 const PeerConnectionInterface::RTCConfiguration& config) const {
5111 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005112 switch (config.continual_gathering_policy) {
5113 case PeerConnectionInterface::GATHER_ONCE:
5114 gathering_policy = cricket::GATHER_ONCE;
5115 break;
5116 case PeerConnectionInterface::GATHER_CONTINUALLY:
5117 gathering_policy = cricket::GATHER_CONTINUALLY;
5118 break;
5119 default:
5120 RTC_NOTREACHED();
5121 gathering_policy = cricket::GATHER_ONCE;
5122 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005123
Steve Anton75737c02017-11-06 10:37:17 -08005124 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005125 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5126 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005127 ice_config.prioritize_most_likely_candidate_pairs =
5128 config.prioritize_most_likely_ice_candidate_pairs;
5129 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005130 RTCConfigurationToIceConfigOptionalInt(
5131 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005132 ice_config.continual_gathering_policy = gathering_policy;
5133 ice_config.presume_writable_when_fully_relayed =
5134 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005135 ice_config.ice_check_interval_strong_connectivity =
5136 config.ice_check_interval_strong_connectivity;
5137 ice_config.ice_check_interval_weak_connectivity =
5138 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005139 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005140 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005141 ice_config.regather_all_networks_interval_range =
5142 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005143 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005144 return ice_config;
5145}
5146
Steve Anton75737c02017-11-06 10:37:17 -08005147bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5148 std::string* track_id) {
5149 if (!local_description()) {
5150 return false;
5151 }
5152 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5153 track_id);
5154}
5155
5156bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5157 std::string* track_id) {
5158 if (!remote_description()) {
5159 return false;
5160 }
5161 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5162 track_id);
5163}
5164
5165bool PeerConnection::SendData(const cricket::SendDataParams& params,
5166 const rtc::CopyOnWriteBuffer& payload,
5167 cricket::SendDataResult* result) {
5168 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005169 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005170 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005171 return false;
5172 }
5173 return rtp_data_channel_
5174 ? rtp_data_channel_->SendData(params, payload, result)
5175 : network_thread()->Invoke<bool>(
5176 RTC_FROM_HERE,
5177 Bind(&cricket::SctpTransportInternal::SendData,
5178 sctp_transport_.get(), params, payload, result));
5179}
5180
5181bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5182 if (!rtp_data_channel_ && !sctp_transport_) {
5183 // Don't log an error here, because DataChannels are expected to call
5184 // ConnectDataChannel in this state. It's the only way to initially tell
5185 // whether or not the underlying transport is ready.
5186 return false;
5187 }
5188 if (rtp_data_channel_) {
5189 rtp_data_channel_->SignalReadyToSendData.connect(
5190 webrtc_data_channel, &DataChannel::OnChannelReady);
5191 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5192 &DataChannel::OnDataReceived);
5193 } else {
5194 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5195 &DataChannel::OnChannelReady);
5196 SignalSctpDataReceived.connect(webrtc_data_channel,
5197 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005198 SignalSctpClosingProcedureStartedRemotely.connect(
5199 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5200 SignalSctpClosingProcedureComplete.connect(
5201 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005202 }
5203 return true;
5204}
5205
5206void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5207 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005208 RTC_LOG(LS_ERROR)
5209 << "DisconnectDataChannel called when rtp_data_channel_ and "
5210 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005211 return;
5212 }
5213 if (rtp_data_channel_) {
5214 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5215 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5216 } else {
5217 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5218 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005219 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5220 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005221 }
5222}
5223
5224void PeerConnection::AddSctpDataStream(int sid) {
5225 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005226 RTC_LOG(LS_ERROR)
5227 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005228 return;
5229 }
5230 network_thread()->Invoke<void>(
5231 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5232 sctp_transport_.get(), sid));
5233}
5234
5235void PeerConnection::RemoveSctpDataStream(int sid) {
5236 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005237 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005238 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005239 return;
5240 }
5241 network_thread()->Invoke<void>(
5242 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5243 sctp_transport_.get(), sid));
5244}
5245
5246bool PeerConnection::ReadyToSendData() const {
5247 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5248 sctp_ready_to_send_data_;
5249}
5250
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005251absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005252 if (sctp_mid_ && transport_controller_) {
5253 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5254 if (dtls_transport) {
5255 return dtls_transport->transport_name();
5256 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005257 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005258 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005259 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005260}
5261
Qingsi Wang72a43a12018-02-20 16:03:18 -08005262cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5263 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005264 network_thread()->Invoke<void>(
5265 RTC_FROM_HERE,
5266 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5267 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005268 return candidate_states_list;
5269}
5270
Steve Anton5dfde182018-02-06 10:34:40 -08005271std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5272 const {
5273 std::map<std::string, std::string> transport_names_by_mid;
5274 for (auto transceiver : transceivers_) {
5275 cricket::BaseChannel* channel = transceiver->internal()->channel();
5276 if (channel) {
5277 transport_names_by_mid[channel->content_name()] =
5278 channel->transport_name();
5279 }
Steve Anton75737c02017-11-06 10:37:17 -08005280 }
Steve Anton5dfde182018-02-06 10:34:40 -08005281 if (rtp_data_channel_) {
5282 transport_names_by_mid[rtp_data_channel_->content_name()] =
5283 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005284 }
5285 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005286 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005287 RTC_DCHECK(transport_name);
5288 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005289 }
Steve Anton5dfde182018-02-06 10:34:40 -08005290 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005291}
5292
Steve Anton5dfde182018-02-06 10:34:40 -08005293std::map<std::string, cricket::TransportStats>
5294PeerConnection::GetTransportStatsByNames(
5295 const std::set<std::string>& transport_names) {
5296 if (!network_thread()->IsCurrent()) {
5297 return network_thread()
5298 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5299 RTC_FROM_HERE,
5300 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005301 }
Steve Anton5dfde182018-02-06 10:34:40 -08005302 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5303 for (const std::string& transport_name : transport_names) {
5304 cricket::TransportStats transport_stats;
5305 bool success =
5306 transport_controller_->GetStats(transport_name, &transport_stats);
5307 if (success) {
5308 transport_stats_by_name[transport_name] = std::move(transport_stats);
5309 } else {
5310 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5311 << transport_name;
5312 }
5313 }
5314 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005315}
5316
5317bool PeerConnection::GetLocalCertificate(
5318 const std::string& transport_name,
5319 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005320 if (!certificate) {
5321 return false;
5322 }
5323 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5324 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005325}
5326
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005327std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005328 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005329 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005330}
5331
5332cricket::DataChannelType PeerConnection::data_channel_type() const {
5333 return data_channel_type_;
5334}
5335
5336bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5337 return pending_ice_restarts_.find(content_name) !=
5338 pending_ice_restarts_.end();
5339}
5340
Steve Anton75737c02017-11-06 10:37:17 -08005341bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5342 return transport_controller_->NeedsIceRestart(content_name);
5343}
5344
5345void PeerConnection::OnCertificateReady(
5346 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5347 transport_controller_->SetLocalCertificate(certificate);
5348}
5349
5350void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005351 SetSessionError(SessionError::kTransport,
5352 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005353}
5354
5355void PeerConnection::OnTransportControllerConnectionState(
5356 cricket::IceConnectionState state) {
5357 switch (state) {
5358 case cricket::kIceConnectionConnecting:
5359 // If the current state is Connected or Completed, then there were
5360 // writable channels but now there are not, so the next state must
5361 // be Disconnected.
5362 // kIceConnectionConnecting is currently used as the default,
5363 // un-connected state by the TransportController, so its only use is
5364 // detecting disconnections.
5365 if (ice_connection_state_ ==
5366 PeerConnectionInterface::kIceConnectionConnected ||
5367 ice_connection_state_ ==
5368 PeerConnectionInterface::kIceConnectionCompleted) {
5369 SetIceConnectionState(
5370 PeerConnectionInterface::kIceConnectionDisconnected);
5371 }
5372 break;
5373 case cricket::kIceConnectionFailed:
5374 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5375 break;
5376 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005377 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005378 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005379 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005380 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005381 break;
5382 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005383 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005384 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005385 if (ice_connection_state_ !=
5386 PeerConnectionInterface::kIceConnectionConnected) {
5387 // If jumping directly from "checking" to "connected",
5388 // signal "connected" first.
5389 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5390 }
5391 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005392 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005393 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005394 break;
5395 default:
5396 RTC_NOTREACHED();
5397 }
5398}
5399
5400void PeerConnection::OnTransportControllerCandidatesGathered(
5401 const std::string& transport_name,
5402 const cricket::Candidates& candidates) {
5403 RTC_DCHECK(signaling_thread()->IsCurrent());
5404 int sdp_mline_index;
5405 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005406 RTC_LOG(LS_ERROR)
5407 << "OnTransportControllerCandidatesGathered: content name "
5408 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005409 return;
5410 }
5411
5412 for (cricket::Candidates::const_iterator citer = candidates.begin();
5413 citer != candidates.end(); ++citer) {
5414 // Use transport_name as the candidate media id.
5415 std::unique_ptr<JsepIceCandidate> candidate(
5416 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5417 if (local_description()) {
5418 mutable_local_description()->AddCandidate(candidate.get());
5419 }
5420 OnIceCandidate(std::move(candidate));
5421 }
5422}
5423
5424void PeerConnection::OnTransportControllerCandidatesRemoved(
5425 const std::vector<cricket::Candidate>& candidates) {
5426 RTC_DCHECK(signaling_thread()->IsCurrent());
5427 // Sanity check.
5428 for (const cricket::Candidate& candidate : candidates) {
5429 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005430 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005431 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005432 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005433 return;
5434 }
5435 }
5436
5437 if (local_description()) {
5438 mutable_local_description()->RemoveCandidates(candidates);
5439 }
5440 OnIceCandidatesRemoved(candidates);
5441}
5442
5443void PeerConnection::OnTransportControllerDtlsHandshakeError(
5444 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005445 RTC_HISTOGRAM_ENUMERATION(
5446 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5447 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005448}
5449
Steve Antoned10bd92017-12-05 10:52:59 -08005450void PeerConnection::EnableSending() {
5451 for (auto transceiver : transceivers_) {
5452 cricket::BaseChannel* channel = transceiver->internal()->channel();
5453 if (channel && !channel->enabled()) {
5454 channel->Enable(true);
5455 }
Steve Anton75737c02017-11-06 10:37:17 -08005456 }
5457
Steve Anton4171afb2017-11-20 10:20:22 -08005458 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005459 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005460 }
Steve Anton75737c02017-11-06 10:37:17 -08005461}
5462
5463// Returns the media index for a local ice candidate given the content name.
5464bool PeerConnection::GetLocalCandidateMediaIndex(
5465 const std::string& content_name,
5466 int* sdp_mline_index) {
5467 if (!local_description() || !sdp_mline_index) {
5468 return false;
5469 }
5470
5471 bool content_found = false;
5472 const ContentInfos& contents = local_description()->description()->contents();
5473 for (size_t index = 0; index < contents.size(); ++index) {
5474 if (contents[index].name == content_name) {
5475 *sdp_mline_index = static_cast<int>(index);
5476 content_found = true;
5477 break;
5478 }
5479 }
5480 return content_found;
5481}
5482
5483bool PeerConnection::UseCandidatesInSessionDescription(
5484 const SessionDescriptionInterface* remote_desc) {
5485 if (!remote_desc) {
5486 return true;
5487 }
5488 bool ret = true;
5489
5490 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5491 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5492 for (size_t n = 0; n < candidates->count(); ++n) {
5493 const IceCandidateInterface* candidate = candidates->at(n);
5494 bool valid = false;
5495 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5496 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005497 RTC_LOG(LS_INFO)
5498 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005499 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005500 }
5501 continue;
5502 }
5503 ret = UseCandidate(candidate);
5504 if (!ret) {
5505 break;
5506 }
5507 }
5508 }
5509 return ret;
5510}
5511
5512bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5513 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5514 size_t remote_content_size =
5515 remote_description()->description()->contents().size();
5516 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005517 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005518 return false;
5519 }
5520
5521 cricket::ContentInfo content =
5522 remote_description()->description()->contents()[mediacontent_index];
5523 std::vector<cricket::Candidate> candidates;
5524 candidates.push_back(candidate->candidate());
5525 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005526 RTCError error =
5527 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005528 if (error.ok()) {
5529 // Candidates successfully submitted for checking.
5530 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5531 ice_connection_state_ ==
5532 PeerConnectionInterface::kIceConnectionDisconnected) {
5533 // If state is New, then the session has just gotten its first remote ICE
5534 // candidates, so go to Checking.
5535 // If state is Disconnected, the session is re-using old candidates or
5536 // receiving additional ones, so go to Checking.
5537 // If state is Connected, stay Connected.
5538 // TODO(bemasc): If state is Connected, and the new candidates are for a
5539 // newly added transport, then the state actually _should_ move to
5540 // checking. Add a way to distinguish that case.
5541 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5542 }
5543 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005544 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005545 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005546 }
5547 return true;
5548}
5549
5550void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005551 // Destroy video channel first since it may have a pointer to the
5552 // voice channel.
5553 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005554 if (!video_info || video_info->rejected) {
5555 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005556 }
5557
Steve Anton6fec8802017-12-04 10:37:29 -08005558 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5559 if (!audio_info || audio_info->rejected) {
5560 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005561 }
5562
5563 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5564 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005565 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005566 }
5567}
5568
Steve Antondcc3c022017-12-22 16:02:54 -08005569RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5570 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005571 const cricket::ContentGroup* bundle_group = nullptr;
5572 if (configuration_.bundle_policy ==
5573 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005574 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005575 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005576 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5577 "max-bundle configured but session description "
5578 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005579 }
5580 }
Steve Antondcc3c022017-12-22 16:02:54 -08005581 return std::move(bundle_group);
5582}
5583
5584RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005585 // Creating the media channels. Transports should already have been created
5586 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005587 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005588 if (voice && !voice->rejected &&
5589 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005590 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005591 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005592 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5593 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005594 }
5595 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5596 }
5597
Steve Antondcc3c022017-12-22 16:02:54 -08005598 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005599 if (video && !video->rejected &&
5600 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005601 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005602 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005603 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5604 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005605 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005606 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005607 }
5608
Steve Antondcc3c022017-12-22 16:02:54 -08005609 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005610 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5611 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005612 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005613 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5614 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005615 }
5616 }
5617
Steve Anton8a006912017-12-04 15:25:56 -08005618 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005619}
5620
Steve Anton4171afb2017-11-20 10:20:22 -08005621// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005622cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005623 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005624 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005625 MediaTransportInterface* media_transport = nullptr;
5626 if (configuration_.use_media_transport) {
5627 media_transport = GetMediaTransport(mid);
5628 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005629
Steve Anton75737c02017-11-06 10:37:17 -08005630 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005631 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005632 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5633 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005634 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005635 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005636 }
Steve Anton75737c02017-11-06 10:37:17 -08005637 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5638 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005639 voice_channel->SignalSentPacket.connect(this,
5640 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005641 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005642
Steve Antoneda6ccd2017-12-04 10:21:55 -08005643 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005644}
5645
Steve Anton4171afb2017-11-20 10:20:22 -08005646// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005647cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005648 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005649 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5650
5651 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005652 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005653 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005654 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5655 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005656 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005657 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005658 }
Steve Anton75737c02017-11-06 10:37:17 -08005659 video_channel->SignalDtlsSrtpSetupFailure.connect(
5660 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005661 video_channel->SignalSentPacket.connect(this,
5662 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005663 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005664
Steve Antoneda6ccd2017-12-04 10:21:55 -08005665 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005666}
5667
Zhi Huange830e682018-03-30 10:48:35 -07005668bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005669 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5670 if (sctp) {
5671 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005672 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005673 << "Trying to create SCTP transport, but didn't compile with "
5674 "SCTP support (HAVE_SCTP)";
5675 return false;
5676 }
5677 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005678 RTC_FROM_HERE,
5679 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005680 return false;
5681 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005682 for (const auto& channel : sctp_data_channels_) {
5683 channel->OnTransportChannelCreated();
5684 }
Steve Anton75737c02017-11-06 10:37:17 -08005685 } else {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005686 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Steve Anton75737c02017-11-06 10:37:17 -08005687 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005688 configuration_.media_config, rtp_transport, signaling_thread(), mid,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005689 SrtpRequired(), GetCryptoOptions());
Steve Anton75737c02017-11-06 10:37:17 -08005690 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005691 return false;
5692 }
Steve Anton75737c02017-11-06 10:37:17 -08005693 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5694 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5695 rtp_data_channel_->SignalSentPacket.connect(
5696 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005697 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005698 }
5699
Steve Anton75737c02017-11-06 10:37:17 -08005700 return true;
5701}
5702
5703Call::Stats PeerConnection::GetCallStats() {
5704 if (!worker_thread()->IsCurrent()) {
5705 return worker_thread()->Invoke<Call::Stats>(
5706 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5707 }
5708 if (call_) {
5709 return call_->GetStats();
5710 } else {
5711 return Call::Stats();
5712 }
5713}
5714
Zhi Huange830e682018-03-30 10:48:35 -07005715bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005716 RTC_DCHECK(network_thread()->IsCurrent());
5717 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005718 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005719 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005720 RTC_DCHECK(dtls_transport);
5721 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005722 RTC_DCHECK(sctp_transport_);
5723 sctp_invoker_.reset(new rtc::AsyncInvoker());
5724 sctp_transport_->SignalReadyToSendData.connect(
5725 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5726 sctp_transport_->SignalDataReceived.connect(
5727 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005728 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5729 // another thread. Would be nice if there was a helper class similar to
5730 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5731 // code.
5732 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5733 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5734 sctp_transport_->SignalClosingProcedureComplete.connect(
5735 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005736 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005737 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005738 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005739}
5740
5741void PeerConnection::DestroySctpTransport_n() {
5742 RTC_DCHECK(network_thread()->IsCurrent());
5743 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005744 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005745 sctp_invoker_.reset(nullptr);
5746 sctp_ready_to_send_data_ = false;
5747}
5748
5749void PeerConnection::OnSctpTransportReadyToSendData_n() {
5750 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5751 RTC_DCHECK(network_thread()->IsCurrent());
5752 // Note: Cannot use rtc::Bind here because it will grab a reference to
5753 // PeerConnection and potentially cause PeerConnection to live longer than
5754 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5755 // be destroyed before PeerConnection is destroyed, and at that point all
5756 // pending tasks will be cleared.
5757 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5758 OnSctpTransportReadyToSendData_s(true);
5759 });
5760}
5761
5762void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5763 RTC_DCHECK(signaling_thread()->IsCurrent());
5764 sctp_ready_to_send_data_ = ready;
5765 SignalSctpReadyToSendData(ready);
5766}
5767
5768void PeerConnection::OnSctpTransportDataReceived_n(
5769 const cricket::ReceiveDataParams& params,
5770 const rtc::CopyOnWriteBuffer& payload) {
5771 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5772 RTC_DCHECK(network_thread()->IsCurrent());
5773 // Note: Cannot use rtc::Bind here because it will grab a reference to
5774 // PeerConnection and potentially cause PeerConnection to live longer than
5775 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5776 // be destroyed before PeerConnection is destroyed, and at that point all
5777 // pending tasks will be cleared.
5778 sctp_invoker_->AsyncInvoke<void>(
5779 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5780 OnSctpTransportDataReceived_s(params, payload);
5781 });
5782}
5783
5784void PeerConnection::OnSctpTransportDataReceived_s(
5785 const cricket::ReceiveDataParams& params,
5786 const rtc::CopyOnWriteBuffer& payload) {
5787 RTC_DCHECK(signaling_thread()->IsCurrent());
5788 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5789 // Received OPEN message; parse and signal that a new data channel should
5790 // be created.
5791 std::string label;
5792 InternalDataChannelInit config;
5793 config.id = params.ssrc;
5794 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005795 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5796 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005797 return;
5798 }
5799 config.open_handshake_role = InternalDataChannelInit::kAcker;
5800 OnDataChannelOpenMessage(label, config);
5801 } else {
5802 // Otherwise just forward the signal.
5803 SignalSctpDataReceived(params, payload);
5804 }
5805}
5806
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005807void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005808 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5809 RTC_DCHECK(network_thread()->IsCurrent());
5810 sctp_invoker_->AsyncInvoke<void>(
5811 RTC_FROM_HERE, signaling_thread(),
5812 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005813 &SignalSctpClosingProcedureStartedRemotely, sid));
5814}
5815
5816void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5817 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5818 RTC_DCHECK(network_thread()->IsCurrent());
5819 sctp_invoker_->AsyncInvoke<void>(
5820 RTC_FROM_HERE, signaling_thread(),
5821 rtc::Bind(&sigslot::signal1<int>::operator(),
5822 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005823}
5824
5825// Returns false if bundle is enabled and rtcp_mux is disabled.
5826bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5827 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5828 if (!bundle_enabled)
5829 return true;
5830
5831 const cricket::ContentGroup* bundle_group =
5832 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5833 RTC_DCHECK(bundle_group != NULL);
5834
5835 const cricket::ContentInfos& contents = desc->contents();
5836 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5837 citer != contents.end(); ++citer) {
5838 const cricket::ContentInfo* content = (&*citer);
5839 RTC_DCHECK(content != NULL);
5840 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005841 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005842 if (!HasRtcpMuxEnabled(content))
5843 return false;
5844 }
5845 }
5846 // RTCP-MUX is enabled in all the contents.
5847 return true;
5848}
5849
5850bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005851 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005852}
5853
Steve Anton8a006912017-12-04 15:25:56 -08005854RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005855 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005856 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005857 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005858 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005859 }
5860
5861 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005862 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005863 }
5864
Steve Anton3828c062017-12-06 10:34:51 -08005865 SdpType type = sdesc->GetType();
5866 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5867 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005868 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005869 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005870 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005871 }
5872
5873 // Verify crypto settings.
5874 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005875 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5876 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005877 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005878 if (!crypto_error.ok()) {
5879 return crypto_error;
5880 }
Steve Anton75737c02017-11-06 10:37:17 -08005881 }
5882
5883 // Verify ice-ufrag and ice-pwd.
5884 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005885 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5886 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005887 }
5888
5889 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005890 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5891 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005892 }
5893
5894 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5895 // m-lines that do not rtcp-mux enabled.
5896
5897 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005898 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005899 // With an answer we want to compare the new answer session description with
5900 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005901 const cricket::SessionDescription* offer_desc =
5902 (source == cricket::CS_LOCAL) ? remote_description()->description()
5903 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005904 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5905 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5906 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005907 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5908 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005909 }
5910 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005911 // The re-offers should respect the order of m= sections in current
5912 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005913 // With a re-offer, either the current local or current remote descriptions
5914 // could be the most up to date, so we would like to check against both of
5915 // them if they exist. It could be the case that one of them has a 0 port
5916 // for a media section, but the other does not. This is important to check
5917 // against in the case that we are recycling an m= section.
5918 const cricket::SessionDescription* current_desc = nullptr;
5919 const cricket::SessionDescription* secondary_current_desc = nullptr;
5920 if (local_description()) {
5921 current_desc = local_description()->description();
5922 if (remote_description()) {
5923 secondary_current_desc = remote_description()->description();
5924 }
5925 } else if (remote_description()) {
5926 current_desc = remote_description()->description();
5927 }
Steve Anton75737c02017-11-06 10:37:17 -08005928 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005929 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5930 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005931 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5932 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005933 }
5934 }
5935
Steve Antonba42e992018-04-09 14:10:01 -07005936 if (IsUnifiedPlan()) {
5937 // Ensure that each audio and video media section has at most one
5938 // "StreamParams". This will return an error if receiving a session
5939 // description from a "Plan B" endpoint which adds multiple tracks of the
5940 // same type. With Unified Plan, there can only be at most one track per
5941 // media section.
5942 for (const ContentInfo& content : sdesc->description()->contents()) {
5943 const MediaContentDescription& desc = *content.description;
5944 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5945 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5946 desc.streams().size() > 1u) {
5947 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5948 "Media section has more than one track specified "
5949 "with a=ssrc lines which is not supported with "
5950 "Unified Plan.");
5951 }
5952 }
5953 }
5954
Steve Anton8a006912017-12-04 15:25:56 -08005955 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005956}
5957
Steve Anton3828c062017-12-06 10:34:51 -08005958bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005959 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005960 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005961 return (state == PeerConnectionInterface::kStable) ||
5962 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005963 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005964 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005965 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5966 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5967 }
5968}
5969
Steve Anton3828c062017-12-06 10:34:51 -08005970bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005971 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005972 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005973 return (state == PeerConnectionInterface::kStable) ||
5974 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005975 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005976 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005977 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5978 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5979 }
5980}
5981
Steve Antonf8470812017-12-04 10:46:21 -08005982const char* PeerConnection::SessionErrorToString(SessionError error) const {
5983 switch (error) {
5984 case SessionError::kNone:
5985 return "ERROR_NONE";
5986 case SessionError::kContent:
5987 return "ERROR_CONTENT";
5988 case SessionError::kTransport:
5989 return "ERROR_TRANSPORT";
5990 }
5991 RTC_NOTREACHED();
5992 return "";
5993}
5994
Steve Anton75737c02017-11-06 10:37:17 -08005995std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02005996 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08005997 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5998 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02005999 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006000}
6001
Steve Anton8e20f172018-03-06 10:55:04 -08006002void PeerConnection::ReportSdpFormatReceived(
6003 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006004 int num_audio_mlines = 0;
6005 int num_video_mlines = 0;
6006 int num_audio_tracks = 0;
6007 int num_video_tracks = 0;
6008 for (const ContentInfo& content : remote_offer.description()->contents()) {
6009 cricket::MediaType media_type = content.media_description()->type();
6010 int num_tracks = std::max(
6011 1, static_cast<int>(content.media_description()->streams().size()));
6012 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6013 num_audio_mlines += 1;
6014 num_audio_tracks += num_tracks;
6015 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6016 num_video_mlines += 1;
6017 num_video_tracks += num_tracks;
6018 }
6019 }
6020 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6021 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6022 format = kSdpFormatReceivedComplexUnifiedPlan;
6023 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6024 format = kSdpFormatReceivedComplexPlanB;
6025 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6026 format = kSdpFormatReceivedSimple;
6027 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006028 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6029 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006030}
6031
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006032void PeerConnection::NoteUsageEvent(UsageEvent event) {
6033 RTC_DCHECK_RUN_ON(signaling_thread());
6034 usage_event_accumulator_ |= static_cast<int>(event);
6035}
6036
6037void PeerConnection::ReportUsagePattern() const {
6038 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006039 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6040 usage_event_accumulator_,
6041 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006042 const int bad_bits =
6043 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6044 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6045 const int good_bits =
6046 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6047 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6048 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6049 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6050 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006051 // If called after close(), we can't report, because observer may have
6052 // been deallocated, and therefore pointer is null. Write to log instead.
6053 if (observer_) {
6054 Observer()->OnInterestingUsage(usage_event_accumulator_);
6055 } else {
6056 RTC_LOG(LS_INFO) << "Interesting usage signature "
6057 << usage_event_accumulator_
6058 << " observed after observer shutdown";
6059 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006060 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006061}
6062
Steve Anton0ffaaa22018-02-23 10:31:30 -08006063void PeerConnection::ReportNegotiatedSdpSemantics(
6064 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006065 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006066 switch (answer.description()->msid_signaling()) {
6067 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006068 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006069 break;
6070 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006071 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006072 break;
6073 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006074 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006075 break;
6076 case cricket::kMsidSignalingMediaSection |
6077 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006078 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006079 break;
6080 default:
6081 RTC_NOTREACHED();
6082 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006083 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6084 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006085}
6086
Steve Anton75737c02017-11-06 10:37:17 -08006087// We need to check the local/remote description for the Transport instead of
6088// the session, because a new Transport added during renegotiation may have
6089// them unset while the session has them set from the previous negotiation.
6090// Not doing so may trigger the auto generation of transport description and
6091// mess up DTLS identity information, ICE credential, etc.
6092bool PeerConnection::ReadyToUseRemoteCandidate(
6093 const IceCandidateInterface* candidate,
6094 const SessionDescriptionInterface* remote_desc,
6095 bool* valid) {
6096 *valid = true;
6097
6098 const SessionDescriptionInterface* current_remote_desc =
6099 remote_desc ? remote_desc : remote_description();
6100
6101 if (!current_remote_desc) {
6102 return false;
6103 }
6104
6105 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6106 size_t remote_content_size =
6107 current_remote_desc->description()->contents().size();
6108 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006109 RTC_LOG(LS_ERROR)
6110 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6111 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006112
6113 *valid = false;
6114 return false;
6115 }
6116
6117 cricket::ContentInfo content =
6118 current_remote_desc->description()->contents()[mediacontent_index];
6119
6120 const std::string transport_name = GetTransportName(content.name);
6121 if (transport_name.empty()) {
6122 return false;
6123 }
Zhi Huange830e682018-03-30 10:48:35 -07006124 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006125}
6126
6127bool PeerConnection::SrtpRequired() const {
6128 return dtls_enabled_ ||
6129 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6130}
6131
6132void PeerConnection::OnTransportControllerGatheringState(
6133 cricket::IceGatheringState state) {
6134 RTC_DCHECK(signaling_thread()->IsCurrent());
6135 if (state == cricket::kIceGatheringGathering) {
6136 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6137 } else if (state == cricket::kIceGatheringComplete) {
6138 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6139 }
6140}
6141
6142void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006143 std::map<std::string, std::set<cricket::MediaType>>
6144 media_types_by_transport_name;
6145 for (auto transceiver : transceivers_) {
6146 if (transceiver->internal()->channel()) {
6147 const std::string& transport_name =
6148 transceiver->internal()->channel()->transport_name();
6149 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006150 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006151 }
Steve Anton75737c02017-11-06 10:37:17 -08006152 }
6153 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006154 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6155 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006156 }
Zhi Huange830e682018-03-30 10:48:35 -07006157
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006158 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006159 if (transport_name) {
6160 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006161 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006162 }
Zhi Huange830e682018-03-30 10:48:35 -07006163
Steve Antonc7b964c2018-02-01 14:39:45 -08006164 for (const auto& entry : media_types_by_transport_name) {
6165 const std::string& transport_name = entry.first;
6166 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006167 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006168 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006169 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006170 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006171 }
6172 }
6173}
6174// Walk through the ConnectionInfos to gather best connection usage
6175// for IPv4 and IPv6.
6176void PeerConnection::ReportBestConnectionState(
6177 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006178 for (const cricket::TransportChannelStats& channel_stats :
6179 stats.channel_stats) {
6180 for (const cricket::ConnectionInfo& connection_info :
6181 channel_stats.connection_infos) {
6182 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006183 continue;
6184 }
6185
Steve Antonc7b964c2018-02-01 14:39:45 -08006186 const cricket::Candidate& local = connection_info.local_candidate;
6187 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006188
6189 // Increment the counter for IceCandidatePairType.
6190 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6191 (local.type() == RELAY_PORT_TYPE &&
6192 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006193 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6194 GetIceCandidatePairCounter(local, remote),
6195 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006196 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006197 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6198 GetIceCandidatePairCounter(local, remote),
6199 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006200 } else {
6201 RTC_CHECK(0);
6202 }
Steve Anton75737c02017-11-06 10:37:17 -08006203
6204 // Increment the counter for IP type.
6205 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006206 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6207 kBestConnections_IPv4,
6208 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006209 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006210 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6211 kBestConnections_IPv6,
6212 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006213 } else {
6214 RTC_CHECK(0);
6215 }
6216
6217 return;
6218 }
6219 }
6220}
6221
6222void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006223 const cricket::TransportStats& stats,
6224 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006225 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6226 return;
6227 }
6228
6229 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6230 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6231 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6232 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6233 return;
6234 }
6235
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006236 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6237 for (cricket::MediaType media_type : media_types) {
6238 switch (media_type) {
6239 case cricket::MEDIA_TYPE_AUDIO:
6240 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6241 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6242 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6243 break;
6244 case cricket::MEDIA_TYPE_VIDEO:
6245 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6246 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6247 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6248 break;
6249 case cricket::MEDIA_TYPE_DATA:
6250 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6251 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6252 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6253 break;
6254 default:
6255 RTC_NOTREACHED();
6256 continue;
6257 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006258 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006259 }
6260
6261 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6262 for (cricket::MediaType media_type : media_types) {
6263 switch (media_type) {
6264 case cricket::MEDIA_TYPE_AUDIO:
6265 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6266 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6267 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6268 break;
6269 case cricket::MEDIA_TYPE_VIDEO:
6270 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6271 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6272 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6273 break;
6274 case cricket::MEDIA_TYPE_DATA:
6275 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6276 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6277 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6278 break;
6279 default:
6280 RTC_NOTREACHED();
6281 continue;
6282 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006283 }
Steve Anton75737c02017-11-06 10:37:17 -08006284 }
6285}
6286
6287void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6288 RTC_DCHECK(worker_thread()->IsCurrent());
6289 RTC_DCHECK(call_);
6290 call_->OnSentPacket(sent_packet);
6291}
6292
6293const std::string PeerConnection::GetTransportName(
6294 const std::string& content_name) {
6295 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006296 if (channel) {
6297 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006298 }
Steve Anton6fec8802017-12-04 10:37:29 -08006299 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006300 RTC_DCHECK(sctp_mid_);
6301 if (content_name == *sctp_mid_) {
6302 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006303 }
6304 }
6305 // Return an empty string if failed to retrieve the transport name.
6306 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006307}
6308
Steve Anton6fec8802017-12-04 10:37:29 -08006309void PeerConnection::DestroyTransceiverChannel(
6310 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6311 transceiver) {
6312 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006313
Steve Anton6fec8802017-12-04 10:37:29 -08006314 cricket::BaseChannel* channel = transceiver->internal()->channel();
6315 if (channel) {
6316 transceiver->internal()->SetChannel(nullptr);
6317 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006318 }
6319}
6320
6321void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006322 if (rtp_data_channel_) {
6323 OnDataChannelDestroyed();
6324 DestroyBaseChannel(rtp_data_channel_);
6325 rtp_data_channel_ = nullptr;
6326 }
6327
6328 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6329 // grab a reference to this PeerConnection. If this is called from the
6330 // PeerConnection destructor, the RefCountedObject vtable will have already
6331 // been destroyed (since it is a subclass of PeerConnection) and using
6332 // rtc::Bind will cause "Pure virtual function called" error to appear.
6333
6334 if (sctp_transport_) {
6335 OnDataChannelDestroyed();
6336 network_thread()->Invoke<void>(RTC_FROM_HERE,
6337 [this] { DestroySctpTransport_n(); });
6338 }
6339}
6340
6341void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6342 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006343 switch (channel->media_type()) {
6344 case cricket::MEDIA_TYPE_AUDIO:
6345 channel_manager()->DestroyVoiceChannel(
6346 static_cast<cricket::VoiceChannel*>(channel));
6347 break;
6348 case cricket::MEDIA_TYPE_VIDEO:
6349 channel_manager()->DestroyVideoChannel(
6350 static_cast<cricket::VideoChannel*>(channel));
6351 break;
6352 case cricket::MEDIA_TYPE_DATA:
6353 channel_manager()->DestroyRtpDataChannel(
6354 static_cast<cricket::RtpDataChannel*>(channel));
6355 break;
6356 default:
6357 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6358 break;
6359 }
Zhi Huange830e682018-03-30 10:48:35 -07006360}
Steve Anton6fec8802017-12-04 10:37:29 -08006361
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006362bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006363 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006364 RtpTransportInternal* rtp_transport,
6365 cricket::DtlsTransportInternal* dtls_transport) {
6366 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006367 auto base_channel = GetChannel(mid);
6368 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006369 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006370 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006371 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006372 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006373 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006374 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006375}
6376
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006377PeerConnectionObserver* PeerConnection::Observer() const {
6378 // In earlier production code, the pointer was not cleared on close,
6379 // which might have led to undefined behavior if the observer was not
6380 // deallocated, or strange crashes if it was.
6381 // We use CHECK in order to catch such behavior if it exists.
6382 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6383 RTC_CHECK(observer_);
6384 return observer_;
6385}
6386
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006387CryptoOptions PeerConnection::GetCryptoOptions() {
6388 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6389 // after it has been removed.
6390 return configuration_.crypto_options.has_value()
6391 ? *configuration_.crypto_options
6392 : factory_->options().crypto_options;
6393}
6394
Harald Alvestrand89061872018-01-02 14:08:34 +01006395void PeerConnection::ClearStatsCache() {
6396 if (stats_collector_) {
6397 stats_collector_->ClearCachedStatsReport();
6398 }
6399}
6400
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006401void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006402 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6403 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006404}
6405
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006406} // namespace webrtc