blob: 06fbae1aa33d216156dd2827910d11c8d2ba07ae [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"
Fredrik Solenberg41f3a432018-12-17 21:02:22 +010021#include "absl/strings/match.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020022#include "api/jsepicecandidate.h"
23#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020026#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080028#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020029#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "logging/rtc_event_log/rtc_event_log.h"
31#include "media/sctp/sctptransport.h"
32#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080033#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020034#include "pc/channelmanager.h"
35#include "pc/dtmfsender.h"
36#include "pc/mediastream.h"
37#include "pc/mediastreamobserver.h"
38#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080039#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020040#include "pc/rtpreceiver.h"
41#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080042#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080043#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020044#include "pc/streamcollection.h"
45#include "pc/videocapturertracksource.h"
46#include "pc/videotrack.h"
47#include "rtc_base/bind.h"
48#include "rtc_base/checks.h"
49#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010050#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020052#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020053#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) {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800280 bool local_hostname =
281 !local.address().hostname().empty() && local.address().IsUnresolvedIP();
282 bool remote_hostname = !remote.address().hostname().empty() &&
283 remote.address().IsUnresolvedIP();
Steve Anton75737c02017-11-06 10:37:17 -0800284 bool local_private = IPIsPrivate(local.address().ipaddr());
285 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 08:25:54 -0800286 if (local_hostname) {
287 if (remote_hostname) {
288 return kIceCandidatePairHostNameHostName;
289 } else if (remote_private) {
290 return kIceCandidatePairHostNameHostPrivate;
291 } else {
292 return kIceCandidatePairHostNameHostPublic;
293 }
294 } else if (local_private) {
295 if (remote_hostname) {
296 return kIceCandidatePairHostPrivateHostName;
297 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800298 return kIceCandidatePairHostPrivateHostPrivate;
299 } else {
300 return kIceCandidatePairHostPrivateHostPublic;
301 }
302 } else {
Jeroen de Borst833979f2018-12-13 08:25:54 -0800303 if (remote_hostname) {
304 return kIceCandidatePairHostPublicHostName;
305 } else if (remote_private) {
Steve Anton75737c02017-11-06 10:37:17 -0800306 return kIceCandidatePairHostPublicHostPrivate;
307 } else {
308 return kIceCandidatePairHostPublicHostPublic;
309 }
310 }
311 }
312 if (l == host && r == srflx)
313 return kIceCandidatePairHostSrflx;
314 if (l == host && r == relay)
315 return kIceCandidatePairHostRelay;
316 if (l == host && r == prflx)
317 return kIceCandidatePairHostPrflx;
318 if (l == srflx && r == host)
319 return kIceCandidatePairSrflxHost;
320 if (l == srflx && r == srflx)
321 return kIceCandidatePairSrflxSrflx;
322 if (l == srflx && r == relay)
323 return kIceCandidatePairSrflxRelay;
324 if (l == srflx && r == prflx)
325 return kIceCandidatePairSrflxPrflx;
326 if (l == relay && r == host)
327 return kIceCandidatePairRelayHost;
328 if (l == relay && r == srflx)
329 return kIceCandidatePairRelaySrflx;
330 if (l == relay && r == relay)
331 return kIceCandidatePairRelayRelay;
332 if (l == relay && r == prflx)
333 return kIceCandidatePairRelayPrflx;
334 if (l == prflx && r == host)
335 return kIceCandidatePairPrflxHost;
336 if (l == prflx && r == srflx)
337 return kIceCandidatePairPrflxSrflx;
338 if (l == prflx && r == relay)
339 return kIceCandidatePairPrflxRelay;
340 return kIceCandidatePairMax;
341}
342
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// Logic to decide if an m= section can be recycled. This means that the new
344// m= section is not rejected, but the old local or remote m= section is
345// rejected. |old_content_one| and |old_content_two| refer to the m= section
346// of the old remote and old local descriptions in no particular order.
347// We need to check both the old local and remote because either
348// could be the most current from the latest negotation.
349bool IsMediaSectionBeingRecycled(SdpType type,
350 const ContentInfo& content,
351 const ContentInfo* old_content_one,
352 const ContentInfo* old_content_two) {
353 return type == SdpType::kOffer && !content.rejected &&
354 ((old_content_one && old_content_one->rejected) ||
355 (old_content_two && old_content_two->rejected));
356}
357
Steve Anton75737c02017-11-06 10:37:17 -0800358// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359// |current_desc|. The number of m= sections in |new_desc| should be no
360// less than |current_desc|. In the case of checking an answer's
361// |new_desc|, the |current_desc| is the last offer that was set as the
362// local or remote. In the case of checking an offer's |new_desc| we
363// check against the local and remote descriptions stored from the last
364// negotiation, because either of these could be the most up to date for
365// possible rejected m sections. These are the |current_desc| and
366// |secondary_current_desc|.
367bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
368 const SessionDescription* secondary_current_desc,
369 const SessionDescription& new_desc,
370 const SdpType type) {
371 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 return false;
373 }
374
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800375 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
376 const cricket::ContentInfo* secondary_content_info = nullptr;
377 if (secondary_current_desc &&
378 i < secondary_current_desc->contents().size()) {
379 secondary_content_info = &secondary_current_desc->contents()[i];
380 }
381 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
382 &current_desc.contents()[i],
383 secondary_content_info)) {
384 // For new offer descriptions, if the media section can be recycled, it's
385 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800386 continue;
387 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800388 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800389 return false;
390 }
391 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800392 new_desc.contents()[i].media_description();
393 const MediaContentDescription* current_desc_mdesc =
394 current_desc.contents()[i].media_description();
395 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800396 return false;
397 }
398 }
399 return true;
400}
401
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800402bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
403 const SessionDescription& desc2) {
404 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800405}
406
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700407void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
408 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200409 // Array of structs needed to map {KeyExchangeProtocolType,
410 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
411 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
412 static constexpr struct {
413 KeyExchangeProtocolType protocol_type;
414 cricket::MediaType media_type;
415 KeyExchangeProtocolMedia protocol_media;
416 } kEnumCounterKeyProtocolMediaMap[] = {
417 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
418 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
419 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
420 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
421 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
422 kEnumCounterKeyProtocolMediaTypeDtlsData},
423 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
424 kEnumCounterKeyProtocolMediaTypeSdesAudio},
425 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
426 kEnumCounterKeyProtocolMediaTypeSdesVideo},
427 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
428 kEnumCounterKeyProtocolMediaTypeSdesData},
429 };
430
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700431 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
432 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100433
Mirko Bonadeiab499822018-09-11 10:43:20 +0200434 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
435 if (i.protocol_type == protocol_type && i.media_type == media_type) {
436 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
437 i.protocol_media,
438 kEnumCounterKeyProtocolMediaTypeMax);
439 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100440 }
441}
442
Harald Alvestrand76829d72018-07-18 23:24:36 +0200443void NoteAddIceCandidateResult(int result) {
444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
445 kAddIceCandidateMax);
446}
447
Steve Anton75737c02017-11-06 10:37:17 -0800448// Checks that each non-rejected content has SDES crypto keys or a DTLS
449// fingerprint, unless it's in a BUNDLE group, in which case only the
450// BUNDLE-tag section (first media section/description in the BUNDLE group)
451// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
452// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
453// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700454RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800455 const cricket::ContentGroup* bundle =
456 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800457 for (const cricket::ContentInfo& content_info : desc->contents()) {
458 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800459 continue;
460 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100461 // Note what media is used with each crypto protocol, for all sections.
462 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
463 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700464 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800465 const std::string& mid = content_info.name;
466 if (bundle && bundle->HasContentName(mid) &&
467 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800468 // This isn't the first media section in the BUNDLE group, so it's not
469 // required to have crypto attributes, since only the crypto attributes
470 // from the first section actually get used.
471 continue;
472 }
473
474 // If the content isn't rejected or bundled into another m= section, crypto
475 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800476 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800477 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800478 if (!media || !tinfo) {
479 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800480 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800481 }
482 if (dtls_enabled) {
483 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100484 RTC_LOG(LS_WARNING)
485 << "Session description must have DTLS fingerprint if "
486 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800487 return RTCError(RTCErrorType::INVALID_PARAMETER,
488 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800489 }
490 } else {
491 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100492 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800493 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800494 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800495 }
496 }
497 }
Steve Anton8a006912017-12-04 15:25:56 -0800498 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800499}
500
501// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
502// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
503// media section/description in the BUNDLE group) needs a ufrag and pwd.
504bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
505 const cricket::ContentGroup* bundle =
506 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800507 for (const cricket::ContentInfo& content_info : desc->contents()) {
508 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800509 continue;
510 }
Steve Anton8a006912017-12-04 15:25:56 -0800511 const std::string& mid = content_info.name;
512 if (bundle && bundle->HasContentName(mid) &&
513 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800514 // This isn't the first media section in the BUNDLE group, so it's not
515 // required to have ufrag/password, since only the ufrag/password from
516 // the first section actually get used.
517 continue;
518 }
519
520 // If the content isn't rejected or bundled into another m= section,
521 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800522 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800523 if (!tinfo) {
524 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100525 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800526 return false;
527 }
528 if (tinfo->description.ice_ufrag.empty() ||
529 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100530 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800531 return false;
532 }
533 }
534 return true;
535}
536
Steve Anton75737c02017-11-06 10:37:17 -0800537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800544 return -1;
545 }
Steve Anton75737c02017-11-06 10:37:17 -0800546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800550 if (!codec.Matches(match_pattern)) {
551 continue;
552 }
553 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
554 return rtc::FromString<int>(value);
555 }
556 }
557 return -1;
558}
559
Steve Anton75737c02017-11-06 10:37:17 -0800560// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
561bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
562 const SessionDescriptionInterface* new_desc,
563 const std::string& content_name) {
564 if (!old_desc) {
565 return false;
566 }
567 const SessionDescription* new_sd = new_desc->description();
568 const SessionDescription* old_sd = old_desc->description();
569 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
570 if (!cinfo || cinfo->rejected) {
571 return false;
572 }
573 // If the content isn't rejected, check if ufrag and password has changed.
574 const cricket::TransportDescription* new_transport_desc =
575 new_sd->GetTransportDescriptionByName(content_name);
576 const cricket::TransportDescription* old_transport_desc =
577 old_sd->GetTransportDescriptionByName(content_name);
578 if (!new_transport_desc || !old_transport_desc) {
579 // No transport description exists. This is not an ICE restart.
580 return false;
581 }
582 if (cricket::IceCredentialsChanged(
583 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
584 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-16 17:08:42 -0800592// Generates a string error message for SetLocalDescription/SetRemoteDescription
593// from an RTCError.
594std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
595 SdpType type,
596 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200597 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200600 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800601}
602
Seth Hampson5b4f0752018-04-02 16:31:36 -0700603std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
604 std::string output = "streams=[";
605 const char* separator = "";
606 for (const auto& stream_id : stream_ids) {
607 output.append(separator).append(stream_id);
608 separator = ", ";
609 }
610 output.append("]");
611 return output;
612}
613
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200614absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200618 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700619 }
620 return rtc_configuration_parameter;
621}
622
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800623cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
624 switch (type) {
625 case DataMessageType::kText:
626 return cricket::DMT_TEXT;
627 case DataMessageType::kBinary:
628 return cricket::DMT_BINARY;
629 case DataMessageType::kControl:
630 return cricket::DMT_CONTROL;
631 default:
632 return cricket::DMT_NONE;
633 }
634 return cricket::DMT_NONE;
635}
636
637DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
638 switch (type) {
639 case cricket::DMT_TEXT:
640 return DataMessageType::kText;
641 case cricket::DMT_BINARY:
642 return DataMessageType::kBinary;
643 case cricket::DMT_CONTROL:
644 return DataMessageType::kControl;
645 case cricket::DMT_NONE:
646 default:
647 RTC_NOTREACHED();
648 }
649 return DataMessageType::kControl;
650}
651
Steve Anton75737c02017-11-06 10:37:17 -0800652} // namespace
653
Henrik Boström31638672017-11-23 17:48:32 +0100654// Upon completion, posts a task to execute the callback of the
655// SetSessionDescriptionObserver asynchronously on the same thread. At this
656// point, the state of the peer connection might no longer reflect the effects
657// of the SetRemoteDescription operation, as the peer connection could have been
658// modified during the post.
659// TODO(hbos): Remove this class once we remove the version of
660// PeerConnectionInterface::SetRemoteDescription() that takes a
661// SetSessionDescriptionObserver as an argument.
662class PeerConnection::SetRemoteDescriptionObserverAdapter
663 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
664 public:
665 SetRemoteDescriptionObserverAdapter(
666 rtc::scoped_refptr<PeerConnection> pc,
667 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
668 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
669
670 // SetRemoteDescriptionObserverInterface implementation.
671 void OnSetRemoteDescriptionComplete(RTCError error) override {
672 if (error.ok())
673 pc_->PostSetSessionDescriptionSuccess(wrapper_);
674 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100675 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100676 }
677
678 private:
679 rtc::scoped_refptr<PeerConnection> pc_;
680 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
681};
682
deadbeef293e9262017-01-11 12:28:30 -0800683bool PeerConnectionInterface::RTCConfiguration::operator==(
684 const PeerConnectionInterface::RTCConfiguration& o) const {
685 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700686 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800687 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000688 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700689 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800690 BundlePolicy bundle_policy;
691 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700692 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
693 int ice_candidate_pool_size;
694 bool disable_ipv6;
695 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700696 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100697 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700698 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200699 absl::optional<int> screencast_min_bitrate;
700 absl::optional<bool> combined_audio_video_bwe;
701 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800702 TcpCandidatePolicy tcp_candidate_policy;
703 CandidateNetworkPolicy candidate_network_policy;
704 int audio_jitter_buffer_max_packets;
705 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100706 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800707 int ice_connection_receiving_timeout;
708 int ice_backup_candidate_pair_ping_interval;
709 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800710 bool prioritize_most_likely_ice_candidate_pairs;
711 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800712 bool prune_turn_ports;
713 bool presume_writable_when_fully_relayed;
714 bool enable_ice_renomination;
715 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200716 absl::optional<int> ice_check_interval_strong_connectivity;
717 absl::optional<int> ice_check_interval_weak_connectivity;
718 absl::optional<int> ice_check_min_interval;
719 absl::optional<int> ice_unwritable_timeout;
720 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800721 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200722 absl::optional<int> stun_candidate_keepalive_interval;
723 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200724 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800725 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200726 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700727 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700728 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700729 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700730 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100731 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800732 };
733 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
734 "Did you add something to RTCConfiguration and forget to "
735 "update operator==?");
736 return type == o.type && servers == o.servers &&
737 bundle_policy == o.bundle_policy &&
738 rtcp_mux_policy == o.rtcp_mux_policy &&
739 tcp_candidate_policy == o.tcp_candidate_policy &&
740 candidate_network_policy == o.candidate_network_policy &&
741 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
742 audio_jitter_buffer_fast_accelerate ==
743 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100744 audio_jitter_buffer_min_delay_ms ==
745 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800746 ice_connection_receiving_timeout ==
747 o.ice_connection_receiving_timeout &&
748 ice_backup_candidate_pair_ping_interval ==
749 o.ice_backup_candidate_pair_ping_interval &&
750 continual_gathering_policy == o.continual_gathering_policy &&
751 certificates == o.certificates &&
752 prioritize_most_likely_ice_candidate_pairs ==
753 o.prioritize_most_likely_ice_candidate_pairs &&
754 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800755 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700756 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100757 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800758 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800759 screencast_min_bitrate == o.screencast_min_bitrate &&
760 combined_audio_video_bwe == o.combined_audio_video_bwe &&
761 enable_dtls_srtp == o.enable_dtls_srtp &&
762 ice_candidate_pool_size == o.ice_candidate_pool_size &&
763 prune_turn_ports == o.prune_turn_ports &&
764 presume_writable_when_fully_relayed ==
765 o.presume_writable_when_fully_relayed &&
766 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800767 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800768 ice_check_interval_strong_connectivity ==
769 o.ice_check_interval_strong_connectivity &&
770 ice_check_interval_weak_connectivity ==
771 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700772 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700773 ice_unwritable_timeout == o.ice_unwritable_timeout &&
774 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800775 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800776 stun_candidate_keepalive_interval ==
777 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200778 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800779 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800780 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700781 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700782 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700783 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700784 use_media_transport_for_data_channels ==
785 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100786 crypto_options == o.crypto_options &&
787 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800788}
789
790bool PeerConnectionInterface::RTCConfiguration::operator!=(
791 const PeerConnectionInterface::RTCConfiguration& o) const {
792 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800793}
794
zhihuang8f65cdf2016-05-06 18:40:30 -0700795// Generate a RTCP CNAME when a PeerConnection is created.
796std::string GenerateRtcpCname() {
797 std::string cname;
798 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100799 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800800 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700801 }
802 return cname;
803}
804
zhihuang1c378ed2017-08-17 14:10:50 -0700805bool ValidateOfferAnswerOptions(
806 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
807 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
808 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700809}
810
zhihuang1c378ed2017-08-17 14:10:50 -0700811// From |rtc_options|, fill parts of |session_options| shared by all generated
812// m= sections (in other words, nothing that involves a map/array).
813void ExtractSharedMediaSessionOptions(
814 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
815 cricket::MediaSessionOptions* session_options) {
816 session_options->vad_enabled = rtc_options.voice_activity_detection;
817 session_options->bundle_enabled = rtc_options.use_rtp_mux;
818}
zhihuanga77e6bb2017-08-14 18:17:48 -0700819
zhihuang38ede132017-06-15 12:52:32 -0700820PeerConnection::PeerConnection(PeerConnectionFactory* factory,
821 std::unique_ptr<RtcEventLog> event_log,
822 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000823 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700824 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700825 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700826 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700827 remote_streams_(StreamCollection::Create()),
828 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829
830PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100831 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800832 RTC_DCHECK_RUN_ON(signaling_thread());
833
Steve Anton8af21862017-12-15 11:20:13 -0800834 // Need to stop transceivers before destroying the stats collector because
835 // AudioRtpSender has a reference to the StatsCollector it will update when
836 // stopping.
837 for (auto transceiver : transceivers_) {
838 transceiver->Stop();
839 }
Steve Anton4171afb2017-11-20 10:20:22 -0800840
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700841 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800842 if (stats_collector_) {
843 stats_collector_->WaitForPendingRequest();
844 stats_collector_ = nullptr;
845 }
Steve Anton75737c02017-11-06 10:37:17 -0800846
Steve Anton8af21862017-12-15 11:20:13 -0800847 // Don't destroy BaseChannels until after stats has been cleaned up so that
848 // the last stats request can still read from the channels.
849 DestroyAllChannels();
850
Mirko Bonadei675513b2017-11-09 11:09:25 +0100851 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800852
853 webrtc_session_desc_factory_.reset();
854 sctp_invoker_.reset();
855 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800856 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800857 transport_controller_.reset();
858
deadbeef91dd5672016-05-18 16:55:30 -0700859 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700860 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700861 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700862 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700863 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700864 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800865 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700866 event_log_.reset();
867 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868}
869
Steve Anton8af21862017-12-15 11:20:13 -0800870void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800871 // Destroy video channels first since they may have a pointer to a voice
872 // channel.
873 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800874 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800875 DestroyTransceiverChannel(transceiver);
876 }
877 }
878 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800879 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800880 DestroyTransceiverChannel(transceiver);
881 }
882 }
883 DestroyDataChannel();
884}
885
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000886bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000887 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700888 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100889 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700890
891 RTCError config_error = ValidateConfiguration(configuration);
892 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100893 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700894 return false;
895 }
896
Benjamin Wrightcab58882018-05-02 15:12:47 -0700897 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100898 RTC_LOG(LS_ERROR)
899 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100900 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800901 return false;
902 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200903
Benjamin Wrightcab58882018-05-02 15:12:47 -0700904 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800905 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100906 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100907 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800908 return false;
909 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700910
Benjamin Wrightcab58882018-05-02 15:12:47 -0700911 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700912 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700913 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700914 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800915
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200916 cricket::ServerAddresses stun_servers;
917 std::vector<cricket::RelayServerConfig> turn_servers;
918
919 RTCErrorType parse_error =
920 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
921 if (parse_error != RTCErrorType::NONE) {
922 return false;
923 }
924
deadbeef91dd5672016-05-18 16:55:30 -0700925 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700926 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700927 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200928 RTC_FROM_HERE,
929 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
930 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000931 return false;
932 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200933 // If initialization was successful, note if STUN or TURN servers
934 // were supplied.
935 if (!stun_servers.empty()) {
936 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
937 }
938 if (!turn_servers.empty()) {
939 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
940 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000941
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700942 // Send information about IPv4/IPv6 status.
943 PeerConnectionAddressFamilyCounter address_family;
944 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
945 address_family = kPeerConnection_IPv6;
946 } else {
947 address_family = kPeerConnection_IPv4;
948 }
949 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
950 kPeerConnectionAddressFamilyCounter_Max);
951
Zhi Huange830e682018-03-30 10:48:35 -0700952 const PeerConnectionFactoryInterface::Options& options = factory_->options();
953
Steve Anton75737c02017-11-06 10:37:17 -0800954 // RFC 3264: The numeric value of the session id and version in the
955 // o line MUST be representable with a "64 bit signed integer".
956 // Due to this constraint session id |session_id_| is max limited to
957 // LLONG_MAX.
958 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700959 JsepTransportController::Config config;
960 config.redetermine_role_on_ice_restart =
961 configuration.redetermine_role_on_ice_restart;
962 config.ssl_max_version = factory_->options().ssl_max_version;
963 config.disable_encryption = options.disable_encryption;
964 config.bundle_policy = configuration.bundle_policy;
965 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700966 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
967 // stub.
968 config.crypto_options = configuration.crypto_options.has_value()
969 ? *configuration.crypto_options
970 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700971 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700972 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700973#if defined(ENABLE_EXTERNAL_AUTH)
974 config.enable_external_auth = true;
975#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700976 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700977
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700978 if (configuration.use_media_transport ||
979 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700980 if (!factory_->media_transport_factory()) {
981 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700982 << "PeerConnecton is initialized with use_media_transport = true or "
983 << "use_media_transport_for_data_channels = true "
984 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700985 return false;
986 }
987
988 config.media_transport_factory = factory_->media_transport_factory();
989 }
990
Zhi Huange830e682018-03-30 10:48:35 -0700991 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700992 signaling_thread(), network_thread(), port_allocator_.get(),
993 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700994 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +0000995 this, &PeerConnection::OnTransportControllerConnectionState);
996 transport_controller_->SignalStandardizedIceConnectionState.connect(
997 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +0200998 transport_controller_->SignalConnectionState.connect(
999 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001000 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001001 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001002 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001003 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001004 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001005 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1006 transport_controller_->SignalDtlsHandshakeError.connect(
1007 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1008
1009 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001010
deadbeefab9b2d12015-10-14 11:33:11 -07001011 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001012 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013
Steve Antonba818672017-11-06 10:21:57 -08001014 configuration_ = configuration;
1015
Steve Anton75737c02017-11-06 10:37:17 -08001016 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1017 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1018 if (!configuration.certificates.empty()) {
1019 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1020 // just picking the first one. The decision should be made based on the DTLS
1021 // handshake. The DTLS negotiations need to know about all certificates.
1022 certificate = configuration.certificates[0];
1023 }
1024
Steve Antond25da372017-11-06 14:50:29 -08001025 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001026
1027 if (options.disable_encryption) {
1028 dtls_enabled_ = false;
1029 } else {
1030 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001031 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001032 // |configuration| can override the default |dtls_enabled_| value.
1033 if (configuration.enable_dtls_srtp) {
1034 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1035 }
1036 }
1037
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001038 if (configuration.use_media_transport_for_data_channels) {
1039 if (configuration.enable_rtp_data_channel) {
1040 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1041 "use_media_transport_for_data_channels are "
1042 "incompatible and cannot both be set to true";
1043 return false;
1044 }
1045 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1046 } else if (configuration.enable_rtp_data_channel) {
1047 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1048 // set. It takes precendence over the disable_sctp_data_channels
1049 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001050 data_channel_type_ = cricket::DCT_RTP;
1051 } else {
1052 // DTLS has to be enabled to use SCTP.
1053 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1054 data_channel_type_ = cricket::DCT_SCTP;
1055 }
1056 }
1057
1058 video_options_.screencast_min_bitrate_kbps =
1059 configuration.screencast_min_bitrate;
1060 audio_options_.combined_audio_video_bwe =
1061 configuration.combined_audio_video_bwe;
1062
1063 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001064 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001065
1066 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001067 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001068
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001069 audio_options_.audio_jitter_buffer_min_delay_ms =
1070 configuration.audio_jitter_buffer_min_delay_ms;
1071
Steve Anton75737c02017-11-06 10:37:17 -08001072 // Whether the certificate generator/certificate is null or not determines
1073 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1074 // the right instructions by clearing the variables if needed.
1075 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001076 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001077 certificate = nullptr;
1078 } else if (certificate) {
1079 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001080 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001081 }
1082
1083 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1084 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001085 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001086 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1087 this, &PeerConnection::OnCertificateReady);
1088
1089 if (options.disable_encryption) {
1090 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1091 }
1092
1093 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001094 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001095 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096
Steve Anton4171afb2017-11-20 10:20:22 -08001097 // Add default audio/video transceivers for Plan B SDP.
1098 if (!IsUnifiedPlan()) {
1099 transceivers_.push_back(
1100 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1101 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1102 transceivers_.push_back(
1103 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1104 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1105 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001106 int delay_ms =
1107 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001108 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1109 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 return true;
1111}
1112
Steve Anton038834f2017-07-14 15:59:59 -07001113RTCError PeerConnection::ValidateConfiguration(
1114 const RTCConfiguration& config) const {
1115 if (config.ice_regather_interval_range &&
1116 config.continual_gathering_policy == GATHER_ONCE) {
1117 return RTCError(RTCErrorType::INVALID_PARAMETER,
1118 "ice_regather_interval_range specified but continual "
1119 "gathering policy is GATHER_ONCE");
1120 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001121 auto result =
1122 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1123 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001124}
1125
Yves Gerey665174f2018-06-19 15:03:05 +02001126rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001127 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1128 "Plan SdpSemantics. Please use GetSenders "
1129 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001130 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001131}
1132
Yves Gerey665174f2018-06-19 15:03:05 +02001133rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001134 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1135 "Plan SdpSemantics. Please use GetReceivers "
1136 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001137 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001138}
1139
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001140bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001141 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1142 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001143 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001144 if (IsClosed()) {
1145 return false;
1146 }
deadbeefab9b2d12015-10-14 11:33:11 -07001147 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148 return false;
1149 }
deadbeefab9b2d12015-10-14 11:33:11 -07001150
1151 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001152 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1153 observer->SignalAudioTrackAdded.connect(this,
1154 &PeerConnection::OnAudioTrackAdded);
1155 observer->SignalAudioTrackRemoved.connect(
1156 this, &PeerConnection::OnAudioTrackRemoved);
1157 observer->SignalVideoTrackAdded.connect(this,
1158 &PeerConnection::OnVideoTrackAdded);
1159 observer->SignalVideoTrackRemoved.connect(
1160 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001161 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001162
deadbeefab9b2d12015-10-14 11:33:11 -07001163 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001164 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001165 }
1166 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001167 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001168 }
1169
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001170 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001171 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172 return true;
1173}
1174
1175void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001176 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1177 "Plan SdpSemantics. Please use RemoveTrack "
1178 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001179 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001180 if (!IsClosed()) {
1181 for (const auto& track : local_stream->GetAudioTracks()) {
1182 RemoveAudioTrack(track.get(), local_stream);
1183 }
1184 for (const auto& track : local_stream->GetVideoTracks()) {
1185 RemoveVideoTrack(track.get(), local_stream);
1186 }
deadbeefab9b2d12015-10-14 11:33:11 -07001187 }
deadbeefab9b2d12015-10-14 11:33:11 -07001188 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001189 stream_observers_.erase(
1190 std::remove_if(
1191 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001192 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001193 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001194 }),
1195 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 if (IsClosed()) {
1198 return;
1199 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001200 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201}
1202
Steve Anton2d6c76a2018-01-05 17:10:52 -08001203RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001204 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001205 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001206 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001207 if (!track) {
1208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1209 }
1210 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1211 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1213 "Track has invalid kind: " + track->kind());
1214 }
Steve Antonf9381f02017-12-14 10:23:57 -08001215 if (IsClosed()) {
1216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1217 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001218 }
Steve Anton4171afb2017-11-20 10:20:22 -08001219 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001220 LOG_AND_RETURN_ERROR(
1221 RTCErrorType::INVALID_PARAMETER,
1222 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Antonf9381f02017-12-14 10:23:57 -08001224 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001225 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1226 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001227 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001228 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001229 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001230 }
1231 return sender_or_error;
1232}
deadbeefe1f9d832016-01-14 15:35:42 -08001233
Steve Antonf9381f02017-12-14 10:23:57 -08001234RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1235PeerConnection::AddTrackPlanB(
1236 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001237 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001238 if (stream_ids.size() > 1u) {
1239 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1240 "AddTrack with more than one stream is not "
1241 "supported with Plan B semantics.");
1242 }
1243 std::vector<std::string> adjusted_stream_ids = stream_ids;
1244 if (adjusted_stream_ids.empty()) {
1245 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1246 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001247 cricket::MediaType media_type =
1248 (track->kind() == MediaStreamTrackInterface::kAudioKind
1249 ? cricket::MEDIA_TYPE_AUDIO
1250 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001251 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001252 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001253 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001254 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001255 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001256 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001257 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001258 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001259 if (sender_info) {
1260 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001261 }
Steve Antonf9381f02017-12-14 10:23:57 -08001262 } else {
1263 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001264 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001265 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001266 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001267 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001268 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001269 if (sender_info) {
1270 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001271 }
deadbeefe1f9d832016-01-14 15:35:42 -08001272 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001273 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001274}
deadbeefe1f9d832016-01-14 15:35:42 -08001275
Steve Antonf9381f02017-12-14 10:23:57 -08001276RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1277PeerConnection::AddTrackUnifiedPlan(
1278 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001279 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001280 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1281 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001282 RTC_LOG(LS_INFO) << "Reusing an existing "
1283 << cricket::MediaTypeToString(transceiver->media_type())
1284 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001285 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001286 transceiver->internal()->set_direction(
1287 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001288 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001289 transceiver->internal()->set_direction(
1290 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001291 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001292 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001293 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001294 } else {
1295 cricket::MediaType media_type =
1296 (track->kind() == MediaStreamTrackInterface::kAudioKind
1297 ? cricket::MEDIA_TYPE_AUDIO
1298 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001299 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1300 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001301 std::string sender_id = track->id();
1302 // Avoid creating a sender with an existing ID by generating a random ID.
1303 // This can happen if this is the second time AddTrack has created a sender
1304 // for this track.
1305 if (FindSenderById(sender_id)) {
1306 sender_id = rtc::CreateRandomUuid();
1307 }
Florent Castelli892acf02018-10-01 22:47:20 +02001308 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001309 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1310 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001312 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 }
Steve Antonf9381f02017-12-14 10:23:57 -08001314 return transceiver->sender();
1315}
1316
1317rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1318PeerConnection::FindFirstTransceiverForAddedTrack(
1319 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1320 RTC_DCHECK(track);
1321 for (auto transceiver : transceivers_) {
1322 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001323 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001324 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001325 !transceiver->internal()->has_ever_been_used_to_send() &&
1326 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001327 return transceiver;
1328 }
1329 }
1330 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001331}
1332
1333bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1334 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001335 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001336}
1337
Steve Anton24db5732018-07-23 10:27:33 -07001338RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001339 rtc::scoped_refptr<RtpSenderInterface> sender) {
1340 if (!sender) {
1341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1342 }
deadbeefe1f9d832016-01-14 15:35:42 -08001343 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1345 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001346 }
Steve Antonf9381f02017-12-14 10:23:57 -08001347 if (IsUnifiedPlan()) {
1348 auto transceiver = FindTransceiverBySender(sender);
1349 if (!transceiver || !sender->track()) {
1350 return RTCError::OK();
1351 }
1352 sender->SetTrack(nullptr);
1353 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001354 transceiver->internal()->set_direction(
1355 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001356 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001357 transceiver->internal()->set_direction(
1358 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001359 }
Steve Anton4171afb2017-11-20 10:20:22 -08001360 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001361 bool removed;
1362 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1363 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1364 } else {
1365 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1366 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1367 }
1368 if (!removed) {
1369 LOG_AND_RETURN_ERROR(
1370 RTCErrorType::INVALID_PARAMETER,
1371 "Couldn't find sender " + sender->id() + " to remove.");
1372 }
Steve Anton4171afb2017-11-20 10:20:22 -08001373 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001374 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001375 return RTCError::OK();
1376}
1377
1378rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1379PeerConnection::FindTransceiverBySender(
1380 rtc::scoped_refptr<RtpSenderInterface> sender) {
1381 for (auto transceiver : transceivers_) {
1382 if (transceiver->sender() == sender) {
1383 return transceiver;
1384 }
1385 }
1386 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001387}
1388
Steve Anton9158ef62017-11-27 13:01:52 -08001389RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1390PeerConnection::AddTransceiver(
1391 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1392 return AddTransceiver(track, RtpTransceiverInit());
1393}
1394
1395RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1396PeerConnection::AddTransceiver(
1397 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1398 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001399 RTC_CHECK(IsUnifiedPlan())
1400 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001401 if (!track) {
1402 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1403 }
1404 cricket::MediaType media_type;
1405 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1406 media_type = cricket::MEDIA_TYPE_AUDIO;
1407 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1408 media_type = cricket::MEDIA_TYPE_VIDEO;
1409 } else {
1410 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1411 "Track kind is not audio or video");
1412 }
1413 return AddTransceiver(media_type, track, init);
1414}
1415
1416RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1417PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1418 return AddTransceiver(media_type, RtpTransceiverInit());
1419}
1420
1421RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1422PeerConnection::AddTransceiver(cricket::MediaType media_type,
1423 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001424 RTC_CHECK(IsUnifiedPlan())
1425 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001426 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1427 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1429 "media type is not audio or video");
1430 }
1431 return AddTransceiver(media_type, nullptr, init);
1432}
1433
1434RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1435PeerConnection::AddTransceiver(
1436 cricket::MediaType media_type,
1437 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001438 const RtpTransceiverInit& init,
1439 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001440 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1441 media_type == cricket::MEDIA_TYPE_VIDEO));
1442 if (track) {
1443 RTC_DCHECK_EQ(media_type,
1444 (track->kind() == MediaStreamTrackInterface::kAudioKind
1445 ? cricket::MEDIA_TYPE_AUDIO
1446 : cricket::MEDIA_TYPE_VIDEO));
1447 }
1448
1449 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001450 if (init.send_encodings.size() > 1) {
1451 LOG_AND_RETURN_ERROR(
1452 RTCErrorType::UNSUPPORTED_PARAMETER,
1453 "Attempted to create an encoder with more than 1 encoding parameter.");
1454 }
1455
1456 for (const auto& encoding : init.send_encodings) {
1457 if (encoding.ssrc.has_value()) {
1458 LOG_AND_RETURN_ERROR(
1459 RTCErrorType::UNSUPPORTED_PARAMETER,
1460 "Attempted to set an unimplemented parameter of RtpParameters.");
1461 }
1462 }
1463
1464 RtpParameters parameters;
1465 parameters.encodings = init.send_encodings;
1466 if (UnimplementedRtpParameterHasValue(parameters)) {
1467 LOG_AND_RETURN_ERROR(
1468 RTCErrorType::UNSUPPORTED_PARAMETER,
1469 "Attempted to set an unimplemented parameter of RtpParameters.");
1470 }
Steve Anton9158ef62017-11-27 13:01:52 -08001471
Steve Anton3d954a62018-04-02 11:27:23 -07001472 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1473 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001474 // Set the sender ID equal to the track ID if the track is specified unless
1475 // that sender ID is already in use.
1476 std::string sender_id =
1477 (track && !FindSenderById(track->id()) ? track->id()
1478 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001479 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1480 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001481 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1482 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1483 transceiver->internal()->set_direction(init.direction);
1484
Steve Anton22da89f2018-01-25 13:58:07 -08001485 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001486 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001487 }
Steve Antonf9381f02017-12-14 10:23:57 -08001488
1489 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1490}
1491
Steve Anton02ee47c2018-01-10 16:26:06 -08001492rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1493PeerConnection::CreateSender(
1494 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001495 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001496 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001497 const std::vector<std::string>& stream_ids,
1498 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001499 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001500 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1501 RTC_DCHECK(!track ||
1502 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1503 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1504 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001505 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001506 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001507 } else {
1508 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1509 RTC_DCHECK(!track ||
1510 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1511 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001512 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001513 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001514 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001515 bool set_track_succeeded = sender->SetTrack(track);
1516 RTC_DCHECK(set_track_succeeded);
1517 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001518 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 return sender;
1520}
1521
1522rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1523PeerConnection::CreateReceiver(cricket::MediaType media_type,
1524 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001525 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1526 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001527 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001528 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001529 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1530 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001531 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001532 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001533 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001534 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001535 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1536 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001537 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001538 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001539 return receiver;
1540}
1541
1542rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1543PeerConnection::CreateAndAddTransceiver(
1544 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1545 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1546 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001547 // Ensure that the new sender does not have an ID that is already in use by
1548 // another sender.
1549 // Allow receiver IDs to conflict since those come from remote SDP (which
1550 // could be invalid, but should not cause a crash).
1551 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001552 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1553 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001554 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001555 transceiver->internal()->SignalNegotiationNeeded.connect(
1556 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001557 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001558}
1559
Steve Anton52d86772018-02-20 15:48:12 -08001560void PeerConnection::OnNegotiationNeeded() {
1561 RTC_DCHECK_RUN_ON(signaling_thread());
1562 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001563 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001564}
1565
deadbeeffac06552015-11-25 11:26:01 -08001566rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001567 const std::string& kind,
1568 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001569 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1570 "Plan SdpSemantics. Please use AddTransceiver "
1571 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001572 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001573 if (IsClosed()) {
1574 return nullptr;
1575 }
Steve Anton4171afb2017-11-20 10:20:22 -08001576
Seth Hampson5b4f0752018-04-02 16:31:36 -07001577 // Internally we need to have one stream with Plan B semantics, so we
1578 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001579 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001580 if (stream_id.empty()) {
1581 stream_ids.push_back(rtc::CreateRandomUuid());
1582 RTC_LOG(LS_INFO)
1583 << "No stream_id specified for sender. Generated stream ID: "
1584 << stream_ids[0];
1585 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001586 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001587 }
1588
Steve Anton4171afb2017-11-20 10:20:22 -08001589 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001590 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001591 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001592 auto* audio_sender = new AudioRtpSender(
1593 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001594 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001595 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001596 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001597 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001598 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001599 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001600 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001601 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001602 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001603 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001604 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001605 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001606 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001607 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001608 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001609 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001610
deadbeefe1f9d832016-01-14 15:35:42 -08001611 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001612}
1613
deadbeef70ab1a12015-09-28 16:53:55 -07001614std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1615 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001616 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001617 for (auto sender : GetSendersInternal()) {
1618 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001619 }
1620 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001621}
1622
Steve Anton4171afb2017-11-20 10:20:22 -08001623std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1624PeerConnection::GetSendersInternal() const {
1625 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1626 all_senders;
1627 for (auto transceiver : transceivers_) {
1628 auto senders = transceiver->internal()->senders();
1629 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1630 }
1631 return all_senders;
1632}
1633
deadbeef70ab1a12015-09-28 16:53:55 -07001634std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1635PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001636 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001637 for (const auto& receiver : GetReceiversInternal()) {
1638 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001639 }
1640 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001641}
1642
Steve Anton4171afb2017-11-20 10:20:22 -08001643std::vector<
1644 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1645PeerConnection::GetReceiversInternal() const {
1646 std::vector<
1647 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1648 all_receivers;
1649 for (auto transceiver : transceivers_) {
1650 auto receivers = transceiver->internal()->receivers();
1651 all_receivers.insert(all_receivers.end(), receivers.begin(),
1652 receivers.end());
1653 }
1654 return all_receivers;
1655}
1656
Steve Anton9158ef62017-11-27 13:01:52 -08001657std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1658PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001659 RTC_CHECK(IsUnifiedPlan())
1660 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001661 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1662 for (auto transceiver : transceivers_) {
1663 all_transceivers.push_back(transceiver);
1664 }
1665 return all_transceivers;
1666}
1667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001668bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001669 MediaStreamTrackInterface* track,
1670 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001671 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001672 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001673 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001674 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001675 return false;
1676 }
1677
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001678 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001679 // The StatsCollector is used to tell if a track is valid because it may
1680 // remember tracks that the PeerConnection previously removed.
1681 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001682 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1683 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001684 return false;
1685 }
Steve Antonad182762018-09-05 20:22:40 +00001686 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1687 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688 return true;
1689}
1690
hbos74e1a4f2016-09-15 23:33:01 -07001691void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001692 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001693 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001694 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001695 stats_collector_->GetStatsReport(callback);
1696}
1697
Henrik Boström1df1bf82018-03-20 13:24:20 +01001698void PeerConnection::GetStats(
1699 rtc::scoped_refptr<RtpSenderInterface> selector,
1700 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1701 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1702 RTC_DCHECK(callback);
1703 RTC_DCHECK(stats_collector_);
1704 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1705 if (selector) {
1706 for (const auto& proxy_transceiver : transceivers_) {
1707 for (const auto& proxy_sender :
1708 proxy_transceiver->internal()->senders()) {
1709 if (proxy_sender == selector) {
1710 internal_sender = proxy_sender->internal();
1711 break;
1712 }
1713 }
1714 if (internal_sender)
1715 break;
1716 }
1717 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001718 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001719 // belong to the PeerConnection (in Plan B, senders can be removed from the
1720 // PeerConnection). This means that "all the stats objects representing the
1721 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1722 // produces an empty stats report.
1723 stats_collector_->GetStatsReport(internal_sender, callback);
1724}
1725
1726void PeerConnection::GetStats(
1727 rtc::scoped_refptr<RtpReceiverInterface> selector,
1728 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1729 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1730 RTC_DCHECK(callback);
1731 RTC_DCHECK(stats_collector_);
1732 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1733 if (selector) {
1734 for (const auto& proxy_transceiver : transceivers_) {
1735 for (const auto& proxy_receiver :
1736 proxy_transceiver->internal()->receivers()) {
1737 if (proxy_receiver == selector) {
1738 internal_receiver = proxy_receiver->internal();
1739 break;
1740 }
1741 }
1742 if (internal_receiver)
1743 break;
1744 }
1745 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001746 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001747 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1748 // the PeerConnection). This means that "all the stats objects representing
1749 // the selector" is an empty set. Invoking GetStatsReport() with a null
1750 // selector produces an empty stats report.
1751 stats_collector_->GetStatsReport(internal_receiver, callback);
1752}
1753
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1755 return signaling_state_;
1756}
1757
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001758PeerConnectionInterface::IceConnectionState
1759PeerConnection::ice_connection_state() {
1760 return ice_connection_state_;
1761}
1762
Alex Loiko9289eda2018-11-23 16:18:59 +00001763PeerConnectionInterface::IceConnectionState
1764PeerConnection::standardized_ice_connection_state() {
1765 return standardized_ice_connection_state_;
1766}
1767
Jonas Olsson635474e2018-10-18 15:58:17 +02001768PeerConnectionInterface::PeerConnectionState
1769PeerConnection::peer_connection_state() {
1770 return connection_state_;
1771}
1772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773PeerConnectionInterface::IceGatheringState
1774PeerConnection::ice_gathering_state() {
1775 return ice_gathering_state_;
1776}
1777
Yves Gerey665174f2018-06-19 15:03:05 +02001778rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779 const std::string& label,
1780 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001781 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001782
deadbeefab9b2d12015-10-14 11:33:11 -07001783 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001784
kwibergd1fe2812016-04-27 06:47:29 -07001785 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001786 if (config) {
1787 internal_config.reset(new InternalDataChannelInit(*config));
1788 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001789 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001790 InternalCreateDataChannel(label, internal_config.get()));
1791 if (!channel.get()) {
1792 return nullptr;
1793 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001795 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1796 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001797 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001798 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001799 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001800 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801 return DataChannelProxy::Create(signaling_thread(), channel.get());
1802}
1803
1804void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001805 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001806 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001807
nisse7ce109a2017-01-31 00:57:56 -08001808 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001809 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001810 return;
1811 }
deadbeefab9b2d12015-10-14 11:33:11 -07001812
Steve Anton8d3444d2017-10-20 15:30:51 -07001813 if (IsClosed()) {
1814 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001815 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001816 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001817 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001818 return;
1819 }
1820
zhihuang1c378ed2017-08-17 14:10:50 -07001821 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001822 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001823 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001824 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001825 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001826 return;
1827 }
1828
Steve Anton22da89f2018-01-25 13:58:07 -08001829 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1830 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1831 if (IsUnifiedPlan()) {
1832 RTCError error = HandleLegacyOfferOptions(options);
1833 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001834 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001835 return;
1836 }
1837 }
1838
zhihuang1c378ed2017-08-17 14:10:50 -07001839 cricket::MediaSessionOptions session_options;
1840 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001841 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001842}
1843
Steve Anton22da89f2018-01-25 13:58:07 -08001844RTCError PeerConnection::HandleLegacyOfferOptions(
1845 const RTCOfferAnswerOptions& options) {
1846 RTC_DCHECK(IsUnifiedPlan());
1847
1848 if (options.offer_to_receive_audio == 0) {
1849 RemoveRecvDirectionFromReceivingTransceiversOfType(
1850 cricket::MEDIA_TYPE_AUDIO);
1851 } else if (options.offer_to_receive_audio == 1) {
1852 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1853 } else if (options.offer_to_receive_audio > 1) {
1854 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1855 "offer_to_receive_audio > 1 is not supported.");
1856 }
1857
1858 if (options.offer_to_receive_video == 0) {
1859 RemoveRecvDirectionFromReceivingTransceiversOfType(
1860 cricket::MEDIA_TYPE_VIDEO);
1861 } else if (options.offer_to_receive_video == 1) {
1862 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1863 } else if (options.offer_to_receive_video > 1) {
1864 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1865 "offer_to_receive_video > 1 is not supported.");
1866 }
1867
1868 return RTCError::OK();
1869}
1870
1871void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1872 cricket::MediaType media_type) {
1873 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001874 RtpTransceiverDirection new_direction =
1875 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1876 if (new_direction != transceiver->direction()) {
1877 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1878 << " transceiver (MID="
1879 << transceiver->mid().value_or("<not set>") << ") from "
1880 << RtpTransceiverDirectionToString(
1881 transceiver->direction())
1882 << " to "
1883 << RtpTransceiverDirectionToString(new_direction)
1884 << " since CreateOffer specified offer_to_receive=0";
1885 transceiver->internal()->set_direction(new_direction);
1886 }
Steve Anton22da89f2018-01-25 13:58:07 -08001887 }
1888}
1889
1890void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1891 cricket::MediaType media_type) {
1892 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001893 RTC_LOG(LS_INFO)
1894 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1895 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001896 RtpTransceiverInit init;
1897 init.direction = RtpTransceiverDirection::kRecvOnly;
1898 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1899 }
1900}
1901
1902std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1903PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1904 std::vector<
1905 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1906 receiving_transceivers;
1907 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001908 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001909 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1910 receiving_transceivers.push_back(transceiver);
1911 }
1912 }
1913 return receiving_transceivers;
1914}
1915
htaa2a49d92016-03-04 02:51:39 -08001916void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1917 const RTCOfferAnswerOptions& options) {
1918 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001919 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001920 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001921 return;
1922 }
1923
Steve Antondffead82018-02-06 10:31:29 -08001924 if (!(signaling_state_ == kHaveRemoteOffer ||
1925 signaling_state_ == kHaveLocalPrAnswer)) {
1926 std::string error =
1927 "PeerConnection cannot create an answer in a state other than "
1928 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001929 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001930 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001931 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001932 return;
1933 }
1934
Steve Antondffead82018-02-06 10:31:29 -08001935 // The remote description should be set if we're in the right state.
1936 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001937
Steve Anton22da89f2018-01-25 13:58:07 -08001938 if (IsUnifiedPlan()) {
1939 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1940 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1941 "supported with Unified Plan semantics. Use the "
1942 "RtpTransceiver API instead.";
1943 }
1944 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1945 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1946 "supported with Unified Plan semantics. Use the "
1947 "RtpTransceiver API instead.";
1948 }
1949 }
1950
htaa2a49d92016-03-04 02:51:39 -08001951 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001952 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001953
Steve Antond25da372017-11-06 14:50:29 -08001954 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955}
1956
1957void PeerConnection::SetLocalDescription(
1958 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001959 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001960 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001961
Steve Anton80dd7b52018-02-16 17:08:42 -08001962 // The SetLocalDescription contract is that we take ownership of the session
1963 // description regardless of the outcome, so wrap it in a unique_ptr right
1964 // away. Ideally, SetLocalDescription's signature will be changed to take the
1965 // description as a unique_ptr argument to formalize this agreement.
1966 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1967
nisse7ce109a2017-01-31 00:57:56 -08001968 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001969 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 return;
1971 }
Steve Anton8a006912017-12-04 15:25:56 -08001972
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001974 PostSetSessionDescriptionFailure(
1975 observer,
1976 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 return;
1978 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001979
Steve Anton80dd7b52018-02-16 17:08:42 -08001980 // If a session error has occurred the PeerConnection is in a possibly
1981 // inconsistent state so fail right away.
1982 if (session_error() != SessionError::kNone) {
1983 std::string error_message = GetSessionErrorMsg();
1984 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001985 PostSetSessionDescriptionFailure(
1986 observer,
1987 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001988 return;
1989 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001990
Steve Anton80dd7b52018-02-16 17:08:42 -08001991 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1992 if (!error.ok()) {
1993 std::string error_message = GetSetDescriptionErrorMessage(
1994 cricket::CS_LOCAL, desc->GetType(), error);
1995 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001996 PostSetSessionDescriptionFailure(
1997 observer,
1998 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001999 return;
2000 }
2001
2002 // Grab the description type before moving ownership to ApplyLocalDescription,
2003 // which may destroy it before returning.
2004 const SdpType type = desc->GetType();
2005
2006 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002007 // |desc| may be destroyed at this point.
2008
2009 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002010 // If ApplyLocalDescription fails, the PeerConnection could be in an
2011 // inconsistent state, so act conservatively here and set the session error
2012 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2013 SetSessionError(SessionError::kContent, error.message());
2014 std::string error_message =
2015 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2016 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002017 PostSetSessionDescriptionFailure(
2018 observer,
2019 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002020 return;
2021 }
Steve Anton8a006912017-12-04 15:25:56 -08002022 RTC_DCHECK(local_description());
2023
2024 PostSetSessionDescriptionSuccess(observer);
2025
Steve Antonad182762018-09-05 20:22:40 +00002026 // MaybeStartGathering needs to be called after posting
2027 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2028 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002029 transport_controller_->MaybeStartGathering();
2030
Steve Antona3a92c22017-12-07 10:27:41 -08002031 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002032 // TODO(deadbeef): We already had to hop to the network thread for
2033 // MaybeStartGathering...
2034 network_thread()->Invoke<void>(
2035 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2036 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002037 // Make UMA notes about what was agreed to.
2038 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002039 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002040 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002041}
2042
2043RTCError PeerConnection::ApplyLocalDescription(
2044 std::unique_ptr<SessionDescriptionInterface> desc) {
2045 RTC_DCHECK_RUN_ON(signaling_thread());
2046 RTC_DCHECK(desc);
2047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048 // Update stats here so that we have the most recent stats for tracks and
2049 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002050 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002051
Steve Antondcc3c022017-12-22 16:02:54 -08002052 // Take a reference to the old local description since it's used below to
2053 // compare against the new local description. When setting the new local
2054 // description, grab ownership of the replaced session description in case it
2055 // is the same as |old_local_description|, to keep it alive for the duration
2056 // of the method.
2057 const SessionDescriptionInterface* old_local_description =
2058 local_description();
2059 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002060 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002061 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002062 replaced_local_description = pending_local_description_
2063 ? std::move(pending_local_description_)
2064 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002065 current_local_description_ = std::move(desc);
2066 pending_local_description_ = nullptr;
2067 current_remote_description_ = std::move(pending_remote_description_);
2068 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002069 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002070 pending_local_description_ = std::move(desc);
2071 }
2072 // The session description to apply now must be accessed by
2073 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002074 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002075
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002076 if (!is_caller_) {
2077 if (remote_description()) {
2078 // Remote description was applied first, so this PC is the callee.
2079 is_caller_ = false;
2080 } else {
2081 // Local description is applied first, so this PC is the caller.
2082 is_caller_ = true;
2083 }
2084 }
2085
Zhi Huange830e682018-03-30 10:48:35 -07002086 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2087 if (!error.ok()) {
2088 return error;
2089 }
2090
Steve Antondcc3c022017-12-22 16:02:54 -08002091 if (IsUnifiedPlan()) {
2092 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002093 cricket::CS_LOCAL, *local_description(), old_local_description,
2094 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002095 if (!error.ok()) {
2096 return error;
2097 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002098 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2099 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002100 for (auto transceiver : transceivers_) {
2101 const ContentInfo* content =
2102 FindMediaSectionForTransceiver(transceiver, local_description());
2103 if (!content) {
2104 continue;
2105 }
2106 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002107 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2108 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002109 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002110 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2111 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2112 // "recvonly", process the removal of a remote track for the media
2113 // description, given transceiver, removeList, and muteTracks.
2114 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2115 (transceiver->internal()->fired_direction() &&
2116 RtpTransceiverDirectionHasRecv(
2117 *transceiver->internal()->fired_direction()))) {
2118 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2119 &removed_streams);
2120 }
2121 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2122 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002123 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002124 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002125 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002126 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002127 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002128 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002129 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002130 }
2131 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002132 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002133 }
2134 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002135 // Media channels will be created only when offer is set. These may use new
2136 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002137 if (type == SdpType::kOffer) {
2138 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2139 // description is applied. Restore back to old description.
2140 RTCError error = CreateChannels(*local_description()->description());
2141 if (!error.ok()) {
2142 return error;
2143 }
2144 }
Steve Antondcc3c022017-12-22 16:02:54 -08002145 // Remove unused channels if MediaContentDescription is rejected.
2146 RemoveUnusedChannels(local_description()->description());
2147 }
Steve Anton8a006912017-12-04 15:25:56 -08002148
Zhi Huange830e682018-03-30 10:48:35 -07002149 error = UpdateSessionState(type, cricket::CS_LOCAL,
2150 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002151 if (!error.ok()) {
2152 return error;
2153 }
Steve Antondcc3c022017-12-22 16:02:54 -08002154
Steve Anton8a006912017-12-04 15:25:56 -08002155 if (remote_description()) {
2156 // Now that we have a local description, we can push down remote candidates.
2157 UseCandidatesInSessionDescription(remote_description());
2158 }
2159
2160 pending_ice_restarts_.clear();
2161 if (session_error() != SessionError::kNone) {
2162 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2163 }
2164
deadbeefab9b2d12015-10-14 11:33:11 -07002165 // If setting the description decided our SSL role, allocate any necessary
2166 // SCTP sids.
2167 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002168 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002169 AllocateSctpSids(role);
2170 }
2171
Steve Antond3679212018-01-17 17:41:02 -08002172 if (IsUnifiedPlan()) {
2173 for (auto transceiver : transceivers_) {
2174 const ContentInfo* content =
2175 FindMediaSectionForTransceiver(transceiver, local_description());
2176 if (!content) {
2177 continue;
2178 }
Steve Anton74255ff2018-01-24 18:32:57 -08002179 const auto& streams = content->media_description()->streams();
2180 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002181 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002182 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002183 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002184 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002185 } else {
2186 // 0 is a special value meaning "this sender has no associated send
2187 // stream". Need to call this so the sender won't attempt to configure
2188 // a no longer existing stream and run into DCHECKs in the lower
2189 // layers.
2190 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002191 }
2192 }
2193 } else {
2194 // Plan B semantics.
2195
Steve Antondcc3c022017-12-22 16:02:54 -08002196 // Update state and SSRC of local MediaStreams and DataChannels based on the
2197 // local session description.
2198 const cricket::ContentInfo* audio_content =
2199 GetFirstAudioContent(local_description()->description());
2200 if (audio_content) {
2201 if (audio_content->rejected) {
2202 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2203 } else {
2204 const cricket::AudioContentDescription* audio_desc =
2205 audio_content->media_description()->as_audio();
2206 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2207 }
deadbeeffaac4972015-11-12 15:33:07 -08002208 }
deadbeefab9b2d12015-10-14 11:33:11 -07002209
Steve Antondcc3c022017-12-22 16:02:54 -08002210 const cricket::ContentInfo* video_content =
2211 GetFirstVideoContent(local_description()->description());
2212 if (video_content) {
2213 if (video_content->rejected) {
2214 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2215 } else {
2216 const cricket::VideoContentDescription* video_desc =
2217 video_content->media_description()->as_video();
2218 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2219 }
deadbeeffaac4972015-11-12 15:33:07 -08002220 }
deadbeefab9b2d12015-10-14 11:33:11 -07002221 }
2222
2223 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002224 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002225 if (data_content) {
2226 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002227 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002228 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002229 cricket::kMediaProtocolRtpPrefix)) {
2230 UpdateLocalRtpDataChannels(data_desc->streams());
2231 }
2232 }
2233
Steve Anton8a006912017-12-04 15:25:56 -08002234 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235}
2236
2237void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002238 SetSessionDescriptionObserver* observer,
2239 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002240 SetRemoteDescription(
2241 std::unique_ptr<SessionDescriptionInterface>(desc),
2242 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2243 new SetRemoteDescriptionObserverAdapter(this, observer)));
2244}
2245
2246void PeerConnection::SetRemoteDescription(
2247 std::unique_ptr<SessionDescriptionInterface> desc,
2248 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002249 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002250
nisse7ce109a2017-01-31 00:57:56 -08002251 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002252 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253 return;
2254 }
Steve Anton8a006912017-12-04 15:25:56 -08002255
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002257 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002258 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 return;
2260 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002261
Steve Anton80dd7b52018-02-16 17:08:42 -08002262 // If a session error has occurred the PeerConnection is in a possibly
2263 // inconsistent state so fail right away.
2264 if (session_error() != SessionError::kNone) {
2265 std::string error_message = GetSessionErrorMsg();
2266 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2267 observer->OnSetRemoteDescriptionComplete(
2268 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2269 return;
2270 }
Steve Anton71439a62018-02-15 11:53:06 -08002271
Steve Antonba42e992018-04-09 14:10:01 -07002272 if (desc->GetType() == SdpType::kOffer) {
2273 // Report to UMA the format of the received offer.
2274 ReportSdpFormatReceived(*desc);
2275 }
2276
Steve Anton80dd7b52018-02-16 17:08:42 -08002277 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002278 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002279 std::string error_message = GetSetDescriptionErrorMessage(
2280 cricket::CS_REMOTE, desc->GetType(), error);
2281 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002282 observer->OnSetRemoteDescriptionComplete(
2283 RTCError(error.type(), std::move(error_message)));
2284 return;
2285 }
Steve Anton71439a62018-02-15 11:53:06 -08002286
Steve Anton80dd7b52018-02-16 17:08:42 -08002287 // Grab the description type before moving ownership to
2288 // ApplyRemoteDescription, which may destroy it before returning.
2289 const SdpType type = desc->GetType();
2290
2291 error = ApplyRemoteDescription(std::move(desc));
2292 // |desc| may be destroyed at this point.
2293
2294 if (!error.ok()) {
2295 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2296 // inconsistent state, so act conservatively here and set the session error
2297 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2298 SetSessionError(SessionError::kContent, error.message());
2299 std::string error_message =
2300 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2301 RTC_LOG(LS_ERROR) << error_message;
2302 observer->OnSetRemoteDescriptionComplete(
2303 RTCError(error.type(), std::move(error_message)));
2304 return;
2305 }
2306 RTC_DCHECK(remote_description());
2307
2308 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002309 // TODO(deadbeef): We already had to hop to the network thread for
2310 // MaybeStartGathering...
2311 network_thread()->Invoke<void>(
2312 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2313 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002314 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002315 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002316 }
2317
2318 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002319 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002320}
2321
2322RTCError PeerConnection::ApplyRemoteDescription(
2323 std::unique_ptr<SessionDescriptionInterface> desc) {
2324 RTC_DCHECK_RUN_ON(signaling_thread());
2325 RTC_DCHECK(desc);
2326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327 // Update stats here so that we have the most recent stats for tracks and
2328 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002329 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002330
Steve Antondcc3c022017-12-22 16:02:54 -08002331 // Take a reference to the old remote description since it's used below to
2332 // compare against the new remote description. When setting the new remote
2333 // description, grab ownership of the replaced session description in case it
2334 // is the same as |old_remote_description|, to keep it alive for the duration
2335 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002336 const SessionDescriptionInterface* old_remote_description =
2337 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002338 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002339 SdpType type = desc->GetType();
2340 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002341 replaced_remote_description = pending_remote_description_
2342 ? std::move(pending_remote_description_)
2343 : std::move(current_remote_description_);
2344 current_remote_description_ = std::move(desc);
2345 pending_remote_description_ = nullptr;
2346 current_local_description_ = std::move(pending_local_description_);
2347 } else {
2348 replaced_remote_description = std::move(pending_remote_description_);
2349 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002350 }
Steve Anton8a006912017-12-04 15:25:56 -08002351 // The session description to apply now must be accessed by
2352 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002353 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002354
Zhi Huange830e682018-03-30 10:48:35 -07002355 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2356 if (!error.ok()) {
2357 return error;
2358 }
Steve Anton8a006912017-12-04 15:25:56 -08002359 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002360 if (IsUnifiedPlan()) {
2361 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002362 cricket::CS_REMOTE, *remote_description(), local_description(),
2363 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002364 if (!error.ok()) {
2365 return error;
2366 }
Steve Antondcc3c022017-12-22 16:02:54 -08002367 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002368 // Media channels will be created only when offer is set. These may use new
2369 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002370 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002371 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002372 // description is applied. Restore back to old description.
2373 RTCError error = CreateChannels(*remote_description()->description());
2374 if (!error.ok()) {
2375 return error;
2376 }
2377 }
Steve Antondcc3c022017-12-22 16:02:54 -08002378 // Remove unused channels if MediaContentDescription is rejected.
2379 RemoveUnusedChannels(remote_description()->description());
2380 }
Steve Anton8a006912017-12-04 15:25:56 -08002381
Zhi Huange830e682018-03-30 10:48:35 -07002382 // NOTE: Candidates allocation will be initiated only when
2383 // SetLocalDescription is called.
2384 error = UpdateSessionState(type, cricket::CS_REMOTE,
2385 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002386 if (!error.ok()) {
2387 return error;
2388 }
2389
2390 if (local_description() &&
2391 !UseCandidatesInSessionDescription(remote_description())) {
2392 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2393 }
2394
2395 if (old_remote_description) {
2396 for (const cricket::ContentInfo& content :
2397 old_remote_description->description()->contents()) {
2398 // Check if this new SessionDescription contains new ICE ufrag and
2399 // password that indicates the remote peer requests an ICE restart.
2400 // TODO(deadbeef): When we start storing both the current and pending
2401 // remote description, this should reset pending_ice_restarts and compare
2402 // against the current description.
2403 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2404 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002405 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002406 pending_ice_restarts_.insert(content.name);
2407 }
2408 } else {
2409 // We retain all received candidates only if ICE is not restarted.
2410 // When ICE is restarted, all previous candidates belong to an old
2411 // generation and should not be kept.
2412 // TODO(deadbeef): This goes against the W3C spec which says the remote
2413 // description should only contain candidates from the last set remote
2414 // description plus any candidates added since then. We should remove
2415 // this once we're sure it won't break anything.
2416 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2417 old_remote_description, content.name, mutable_remote_description());
2418 }
2419 }
2420 }
2421
2422 if (session_error() != SessionError::kNone) {
2423 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2424 }
2425
2426 // Set the the ICE connection state to connecting since the connection may
2427 // become writable with peer reflexive candidates before any remote candidate
2428 // is signaled.
2429 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2430 // is to have a new signal the indicates a change in checking state from the
2431 // transport and expose a new checking() member from transport that can be
2432 // read to determine the current checking state. The existing SignalConnecting
2433 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002434 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002435 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002436 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2437 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2438 }
2439
deadbeefab9b2d12015-10-14 11:33:11 -07002440 // If setting the description decided our SSL role, allocate any necessary
2441 // SCTP sids.
2442 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002443 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002444 AllocateSctpSids(role);
2445 }
2446
Steve Antondcc3c022017-12-22 16:02:54 -08002447 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002448 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002449 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002450 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002451 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002452 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002453 for (auto transceiver : transceivers_) {
2454 const ContentInfo* content =
2455 FindMediaSectionForTransceiver(transceiver, remote_description());
2456 if (!content) {
2457 continue;
2458 }
2459 const MediaContentDescription* media_desc = content->media_description();
2460 RtpTransceiverDirection local_direction =
2461 RtpTransceiverDirectionReversed(media_desc->direction());
2462 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2463 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2464 // transceiver's current direction is neither sendrecv nor recvonly,
2465 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002466 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002467 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002468 // The remote description has signaled the stream IDs.
2469 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002470 }
Steve Antondcc3c022017-12-22 16:02:54 -08002471 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002472 (!transceiver->fired_direction() ||
2473 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002474 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002475 << content->name << " (added to "
2476 << GetStreamIdsString(stream_ids) << ").";
2477
2478 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2479 for (const std::string& stream_id : stream_ids) {
2480 rtc::scoped_refptr<MediaStreamInterface> stream =
2481 remote_streams_->find(stream_id);
2482 if (!stream) {
2483 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2484 MediaStream::Create(stream_id));
2485 remote_streams_->AddStream(stream);
2486 added_streams.push_back(stream);
2487 }
2488 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002489 }
Henrik Boström5b147782018-12-04 11:25:05 +01002490 // Special case: "a=msid" missing, use random stream ID.
2491 if (media_streams.empty() &&
2492 !(remote_description()->description()->msid_signaling() &
2493 cricket::kMsidSignalingMediaSection)) {
2494 if (!missing_msid_default_stream_) {
2495 missing_msid_default_stream_ = MediaStreamProxy::Create(
2496 rtc::Thread::Current(),
2497 MediaStream::Create(rtc::CreateRandomUuid()));
2498 added_streams.push_back(missing_msid_default_stream_);
2499 }
2500 media_streams.push_back(missing_msid_default_stream_);
2501 }
Steve Anton3172c032018-05-03 15:30:18 -07002502 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002503 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2504 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002505 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002506 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002507 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002508 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2509 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2510 // removal of a remote track for the media description, given transceiver,
2511 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002512 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002513 (transceiver->fired_direction() &&
2514 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2515 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2516 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002517 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002518 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2519 transceiver->internal()->set_fired_direction(local_direction);
2520 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2521 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002522 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002523 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2524 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002525 transceiver->internal()->set_current_direction(local_direction);
2526 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002527 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2528 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002529 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002530 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2531 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002532 transceiver->Stop();
2533 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002534 if (!content->rejected &&
2535 RtpTransceiverDirectionHasRecv(local_direction)) {
2536 // Set ssrc to 0 in the case of an unsignalled ssrc.
2537 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002538 if (!media_desc->streams().empty() &&
2539 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002540 ssrc = media_desc->streams()[0].first_ssrc();
2541 }
2542 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002543 }
Steve Antondcc3c022017-12-22 16:02:54 -08002544 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002545 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002546 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002547 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002548 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002549 observer->OnTrack(transceiver);
2550 observer->OnAddTrack(transceiver->receiver(),
2551 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002552 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002553 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002554 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002555 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002556 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002557 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002558 }
2559 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002560 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002561 }
Steve Antondcc3c022017-12-22 16:02:54 -08002562 }
2563
Henrik Boströmfdb92012017-11-09 19:55:44 +01002564 const cricket::ContentInfo* audio_content =
2565 GetFirstAudioContent(remote_description()->description());
2566 const cricket::ContentInfo* video_content =
2567 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002568 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002569 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002570 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002571 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002572 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002573 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002574
2575 // Check if the descriptions include streams, just in case the peer supports
2576 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002577 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002578 (audio_desc && !audio_desc->streams().empty()) ||
2579 (video_desc && !video_desc->streams().empty())) {
2580 remote_peer_supports_msid_ = true;
2581 }
deadbeefab9b2d12015-10-14 11:33:11 -07002582
2583 // We wait to signal new streams until we finish processing the description,
2584 // since only at that point will new streams have all their tracks.
2585 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2586
Steve Antondcc3c022017-12-22 16:02:54 -08002587 if (!IsUnifiedPlan()) {
2588 // TODO(steveanton): When removing RTP senders/receivers in response to a
2589 // rejected media section, there is some cleanup logic that expects the
2590 // voice/ video channel to still be set. But in this method the voice/video
2591 // channel would have been destroyed by the SetRemoteDescription caller
2592 // above so the cleanup that relies on them fails to run. The RemoveSenders
2593 // calls should be moved to right before the DestroyChannel calls to fix
2594 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002595
Steve Antondcc3c022017-12-22 16:02:54 -08002596 // Find all audio rtp streams and create corresponding remote AudioTracks
2597 // and MediaStreams.
2598 if (audio_content) {
2599 if (audio_content->rejected) {
2600 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2601 } else {
2602 bool default_audio_track_needed =
2603 !remote_peer_supports_msid_ &&
2604 RtpTransceiverDirectionHasSend(audio_desc->direction());
2605 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2606 default_audio_track_needed, audio_desc->type(),
2607 new_streams);
2608 }
deadbeeffaac4972015-11-12 15:33:07 -08002609 }
deadbeefab9b2d12015-10-14 11:33:11 -07002610
Steve Antondcc3c022017-12-22 16:02:54 -08002611 // Find all video rtp streams and create corresponding remote VideoTracks
2612 // and MediaStreams.
2613 if (video_content) {
2614 if (video_content->rejected) {
2615 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2616 } else {
2617 bool default_video_track_needed =
2618 !remote_peer_supports_msid_ &&
2619 RtpTransceiverDirectionHasSend(video_desc->direction());
2620 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2621 default_video_track_needed, video_desc->type(),
2622 new_streams);
2623 }
deadbeeffaac4972015-11-12 15:33:07 -08002624 }
deadbeefab9b2d12015-10-14 11:33:11 -07002625
Steve Antondcc3c022017-12-22 16:02:54 -08002626 // Update the DataChannels with the information from the remote peer.
2627 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002628 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002629 cricket::kMediaProtocolRtpPrefix)) {
2630 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2631 }
deadbeefab9b2d12015-10-14 11:33:11 -07002632 }
deadbeefab9b2d12015-10-14 11:33:11 -07002633
Steve Antondcc3c022017-12-22 16:02:54 -08002634 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002635 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002636 for (size_t i = 0; i < new_streams->count(); ++i) {
2637 MediaStreamInterface* new_stream = new_streams->at(i);
2638 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002639 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002640 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2641 }
deadbeefab9b2d12015-10-14 11:33:11 -07002642
Steve Antondcc3c022017-12-22 16:02:54 -08002643 UpdateEndedRemoteMediaStreams();
2644 }
deadbeefab9b2d12015-10-14 11:33:11 -07002645
Steve Anton8a006912017-12-04 15:25:56 -08002646 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002647}
2648
Steve Anton0f5400a2018-07-17 14:25:36 -07002649void PeerConnection::ProcessRemovalOfRemoteTrack(
2650 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2651 transceiver,
2652 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2653 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2654 RTC_DCHECK(transceiver->mid());
2655 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2656 << *transceiver->mid();
2657 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2658 transceiver->internal()->receiver_internal()->streams();
2659 // This will remove the remote track from the streams.
2660 transceiver->internal()->receiver_internal()->set_stream_ids({});
2661 remove_list->push_back(transceiver);
2662 // Remove any streams that no longer have tracks.
2663 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2664 // of streams, see if the stream was removed by checking if this was the
2665 // last receiver with that stream ID.
2666 for (auto stream : media_streams) {
2667 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2668 remote_streams_->RemoveStream(stream);
2669 removed_streams->push_back(stream);
2670 }
2671 }
2672}
2673
Steve Antondcc3c022017-12-22 16:02:54 -08002674RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2675 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002676 const SessionDescriptionInterface& new_session,
2677 const SessionDescriptionInterface* old_local_description,
2678 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002679 RTC_DCHECK(IsUnifiedPlan());
2680
Steve Anton7464fca2018-01-19 11:10:37 -08002681 const cricket::ContentGroup* bundle_group = nullptr;
2682 if (new_session.GetType() == SdpType::kOffer) {
2683 auto bundle_group_or_error =
2684 GetEarlyBundleGroup(*new_session.description());
2685 if (!bundle_group_or_error.ok()) {
2686 return bundle_group_or_error.MoveError();
2687 }
2688 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002689 }
Steve Antondcc3c022017-12-22 16:02:54 -08002690
Steve Antondcc3c022017-12-22 16:02:54 -08002691 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002692 for (size_t i = 0; i < new_contents.size(); ++i) {
2693 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002694 cricket::MediaType media_type = new_content.media_description()->type();
2695 seen_mids_.insert(new_content.name);
2696 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2697 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002698 const cricket::ContentInfo* old_local_content = nullptr;
2699 if (old_local_description &&
2700 i < old_local_description->description()->contents().size()) {
2701 old_local_content =
2702 &old_local_description->description()->contents()[i];
2703 }
2704 const cricket::ContentInfo* old_remote_content = nullptr;
2705 if (old_remote_description &&
2706 i < old_remote_description->description()->contents().size()) {
2707 old_remote_content =
2708 &old_remote_description->description()->contents()[i];
2709 }
Steve Antondcc3c022017-12-22 16:02:54 -08002710 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002711 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2712 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002713 if (!transceiver_or_error.ok()) {
2714 return transceiver_or_error.MoveError();
2715 }
2716 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002717 RTCError error =
2718 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2719 if (!error.ok()) {
2720 return error;
2721 }
2722 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002723 if (GetDataMid() && new_content.name != *GetDataMid()) {
2724 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002725 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2726 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002727 continue;
2728 }
2729 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2730 if (!error.ok()) {
2731 return error;
2732 }
Steve Antondcc3c022017-12-22 16:02:54 -08002733 } else {
2734 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2735 "Unknown section type.");
2736 }
2737 }
2738
2739 return RTCError::OK();
2740}
2741
2742RTCError PeerConnection::UpdateTransceiverChannel(
2743 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2744 transceiver,
2745 const cricket::ContentInfo& content,
2746 const cricket::ContentGroup* bundle_group) {
2747 RTC_DCHECK(IsUnifiedPlan());
2748 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002749 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002750 if (content.rejected) {
2751 if (channel) {
2752 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002753 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002754 }
2755 } else {
2756 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002757 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002758 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002759 } else {
Steve Anton69470252018-02-09 11:43:08 -08002760 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002761 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002762 }
2763 if (!channel) {
2764 LOG_AND_RETURN_ERROR(
2765 RTCErrorType::INTERNAL_ERROR,
2766 "Failed to create channel for mid=" + content.name);
2767 }
2768 transceiver->internal()->SetChannel(channel);
2769 }
2770 }
2771 return RTCError::OK();
2772}
2773
Steve Antonfa2260d2017-12-28 16:38:23 -08002774RTCError PeerConnection::UpdateDataChannel(
2775 cricket::ContentSource source,
2776 const cricket::ContentInfo& content,
2777 const cricket::ContentGroup* bundle_group) {
2778 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002779 // If data channels are disabled, ignore this media section. CreateAnswer
2780 // will take care of rejecting it.
2781 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002782 }
2783 if (content.rejected) {
2784 DestroyDataChannel();
2785 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002786 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002787 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002788 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2789 "Failed to create data channel.");
2790 }
2791 }
2792 if (source == cricket::CS_REMOTE) {
2793 const MediaContentDescription* data_desc = content.media_description();
2794 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2795 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2796 }
2797 }
2798 }
2799 return RTCError::OK();
2800}
2801
Steve Antondcc3c022017-12-22 16:02:54 -08002802RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2803PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002804 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002805 size_t mline_index,
2806 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002807 const ContentInfo* old_local_content,
2808 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002809 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002810 // If this is an offer then the m= section might be recycled. If the m=
2811 // section is being recycled (defined as: rejected in the current local or
2812 // remote description and not rejected in new description), dissociate the
2813 // currently associated RtpTransceiver by setting its mid property to null,
2814 // and discard the mapping between the transceiver and its m= section index.
2815 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2816 old_remote_content)) {
2817 // We want to dissociate the transceiver that has the rejected mid.
2818 const std::string& old_mid =
2819 (old_local_content && old_local_content->rejected)
2820 ? old_local_content->name
2821 : old_remote_content->name;
2822 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002823 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002824 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2825 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002826 old_transceiver->internal()->set_mid(absl::nullopt);
2827 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002828 }
2829 }
2830 const MediaContentDescription* media_desc = content.media_description();
2831 auto transceiver = GetAssociatedTransceiver(content.name);
2832 if (source == cricket::CS_LOCAL) {
2833 // Find the RtpTransceiver that corresponds to this m= section, using the
2834 // mapping between transceivers and m= section indices established when
2835 // creating the offer.
2836 if (!transceiver) {
2837 transceiver = GetTransceiverByMLineIndex(mline_index);
2838 }
2839 if (!transceiver) {
2840 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2841 "Unknown transceiver");
2842 }
2843 } else {
2844 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2845 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2846 // of the same type...
2847 if (!transceiver &&
2848 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2849 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2850 }
2851 // If no RtpTransceiver was found in the previous step, create one with a
2852 // recvonly direction.
2853 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002854 RTC_LOG(LS_INFO) << "Adding "
2855 << cricket::MediaTypeToString(media_desc->type())
2856 << " transceiver for MID=" << content.name
2857 << " at i=" << mline_index
2858 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002859 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002860 auto sender =
2861 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002862 std::string receiver_id;
2863 if (!media_desc->streams().empty()) {
2864 receiver_id = media_desc->streams()[0].id;
2865 } else {
2866 receiver_id = rtc::CreateRandomUuid();
2867 }
2868 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002869 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002870 transceiver->internal()->set_direction(
2871 RtpTransceiverDirection::kRecvOnly);
2872 }
2873 }
2874 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002875 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002876 LOG_AND_RETURN_ERROR(
2877 RTCErrorType::INVALID_PARAMETER,
2878 "Transceiver type does not match media description type.");
2879 }
2880 // Associate the found or created RtpTransceiver with the m= section by
2881 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2882 // section, and establish a mapping between the transceiver and the index of
2883 // the m= section.
2884 transceiver->internal()->set_mid(content.name);
2885 transceiver->internal()->set_mline_index(mline_index);
2886 return std::move(transceiver);
2887}
2888
2889rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2890PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2891 RTC_DCHECK(IsUnifiedPlan());
2892 for (auto transceiver : transceivers_) {
2893 if (transceiver->mid() == mid) {
2894 return transceiver;
2895 }
2896 }
2897 return nullptr;
2898}
2899
2900rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2901PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2902 RTC_DCHECK(IsUnifiedPlan());
2903 for (auto transceiver : transceivers_) {
2904 if (transceiver->internal()->mline_index() == mline_index) {
2905 return transceiver;
2906 }
2907 }
2908 return nullptr;
2909}
2910
2911rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2912PeerConnection::FindAvailableTransceiverToReceive(
2913 cricket::MediaType media_type) const {
2914 RTC_DCHECK(IsUnifiedPlan());
2915 // From JSEP section 5.10 (Applying a Remote Description):
2916 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2917 // the same type that were added to the PeerConnection by addTrack and are not
2918 // associated with any m= section and are not stopped, find the first such
2919 // RtpTransceiver.
2920 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002921 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002922 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2923 !transceiver->stopped()) {
2924 return transceiver;
2925 }
2926 }
2927 return nullptr;
2928}
2929
Steve Antoned10bd92017-12-05 10:52:59 -08002930const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2931 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2932 transceiver,
2933 const SessionDescriptionInterface* sdesc) const {
2934 RTC_DCHECK(transceiver);
2935 RTC_DCHECK(sdesc);
2936 if (IsUnifiedPlan()) {
2937 if (!transceiver->internal()->mid()) {
2938 // This transceiver is not associated with a media section yet.
2939 return nullptr;
2940 }
2941 return sdesc->description()->GetContentByName(
2942 *transceiver->internal()->mid());
2943 } else {
2944 // Plan B only allows at most one audio and one video section, so use the
2945 // first media section of that type.
2946 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002947 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002948 }
2949}
2950
deadbeef46c73892016-11-16 19:42:04 -08002951PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2952 return configuration_;
2953}
2954
deadbeef293e9262017-01-11 12:28:30 -08002955bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2956 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002957 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002958 if (IsClosed()) {
2959 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2960 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2961 }
2962
Qingsi Wanga2d60672018-04-11 16:57:45 -07002963 // According to JSEP, after setLocalDescription, changing the candidate pool
2964 // size is not allowed, and changing the set of ICE servers will not result
2965 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002966 if (local_description() && configuration.ice_candidate_pool_size !=
2967 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002968 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2969 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002970 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002971 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002972
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002973 if (local_description() &&
2974 configuration.use_media_transport != configuration_.use_media_transport) {
2975 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2976 "SetLocalDescription.";
2977 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2978 }
2979
2980 if (remote_description() &&
2981 configuration.use_media_transport != configuration_.use_media_transport) {
2982 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2983 "SetRemoteDescription.";
2984 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2985 }
2986
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002987 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002988 configuration.use_media_transport_for_data_channels !=
2989 configuration_.use_media_transport_for_data_channels) {
2990 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2991 "after calling SetLocalDescription.";
2992 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2993 }
2994
2995 if (remote_description() &&
2996 configuration.use_media_transport_for_data_channels !=
2997 configuration_.use_media_transport_for_data_channels) {
2998 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2999 "after calling SetRemoteDescription.";
3000 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3001 }
3002
3003 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003004 configuration.crypto_options != configuration_.crypto_options) {
3005 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3006 "SetLocalDescription.";
3007 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3008 }
3009
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003010 if (configuration.use_media_transport_for_data_channels ||
3011 configuration.use_media_transport) {
3012 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3013 << "Media transport requires MaxBundle policy.";
3014 }
3015
deadbeef293e9262017-01-11 12:28:30 -08003016 // The simplest (and most future-compatible) way to tell if the config was
3017 // modified in an invalid way is to copy each property we do support
3018 // modifying, then use operator==. There are far more properties we don't
3019 // support modifying than those we do, and more could be added.
3020 RTCConfiguration modified_config = configuration_;
3021 modified_config.servers = configuration.servers;
3022 modified_config.type = configuration.type;
3023 modified_config.ice_candidate_pool_size =
3024 configuration.ice_candidate_pool_size;
3025 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003026 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003027 modified_config.ice_check_interval_strong_connectivity =
3028 configuration.ice_check_interval_strong_connectivity;
3029 modified_config.ice_check_interval_weak_connectivity =
3030 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003031 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3032 modified_config.ice_unwritable_min_checks =
3033 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003034 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003035 modified_config.stun_candidate_keepalive_interval =
3036 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003037 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003038 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003039 modified_config.active_reset_srtp_params =
3040 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003041 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003042 modified_config.use_media_transport_for_data_channels =
3043 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003044 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003045 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003046 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3047 }
3048
Steve Anton038834f2017-07-14 15:59:59 -07003049 // Validate the modified configuration.
3050 RTCError validate_error = ValidateConfiguration(modified_config);
3051 if (!validate_error.ok()) {
3052 return SafeSetError(std::move(validate_error), error);
3053 }
3054
deadbeef293e9262017-01-11 12:28:30 -08003055 // Note that this isn't possible through chromium, since it's an unsigned
3056 // short in WebIDL.
3057 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003058 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003059 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3060 }
3061
3062 // Parse ICE servers before hopping to network thread.
3063 cricket::ServerAddresses stun_servers;
3064 std::vector<cricket::RelayServerConfig> turn_servers;
3065 RTCErrorType parse_error =
3066 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3067 if (parse_error != RTCErrorType::NONE) {
3068 return SafeSetError(parse_error, error);
3069 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003070 // Note if STUN or TURN servers were supplied.
3071 if (!stun_servers.empty()) {
3072 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3073 }
3074 if (!turn_servers.empty()) {
3075 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3076 }
deadbeef293e9262017-01-11 12:28:30 -08003077
3078 // In theory this shouldn't fail.
3079 if (!network_thread()->Invoke<bool>(
3080 RTC_FROM_HERE,
3081 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3082 stun_servers, turn_servers, modified_config.type,
3083 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003084 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003085 modified_config.turn_customizer,
3086 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003087 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003088 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3089 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003090
deadbeefd1a38b52016-12-10 13:15:33 -08003091 // As described in JSEP, calling setConfiguration with new ICE servers or
3092 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3093 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003094 if (modified_config.servers != configuration_.servers ||
3095 modified_config.type != configuration_.type ||
3096 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003097 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003098 }
skvladd1f5fda2017-02-03 16:54:05 -08003099
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003100 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003101 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003102 modified_config.use_media_transport ||
3103 modified_config.use_media_transport_for_data_channels
3104 ? factory_->media_transport_factory()
3105 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003106
Zhi Huangb57e1692018-06-12 11:41:11 -07003107 if (configuration_.active_reset_srtp_params !=
3108 modified_config.active_reset_srtp_params) {
3109 transport_controller_->SetActiveResetSrtpParams(
3110 modified_config.active_reset_srtp_params);
3111 }
3112
deadbeef293e9262017-01-11 12:28:30 -08003113 configuration_ = modified_config;
3114 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003115}
3116
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003117bool PeerConnection::AddIceCandidate(
3118 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003119 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003120 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003121 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003122 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003123 return false;
3124 }
Steve Antond25da372017-11-06 14:50:29 -08003125
3126 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003127 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003128 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003129 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003130 return false;
3131 }
3132
3133 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003134 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003135 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003136 return false;
3137 }
3138
3139 bool valid = false;
3140 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3141 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003142 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003143 return false;
3144 }
3145
3146 // Add this candidate to the remote session description.
3147 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003148 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003149 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003150 return false;
3151 }
3152
3153 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003154 bool result = UseCandidate(ice_candidate);
3155 if (result) {
3156 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3157 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3158 } else {
3159 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3160 }
3161 return result;
Steve Antond25da372017-11-06 14:50:29 -08003162 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003163 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003164 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003165 return true;
3166 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003167}
3168
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003169bool PeerConnection::RemoveIceCandidates(
3170 const std::vector<cricket::Candidate>& candidates) {
3171 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003172 if (IsClosed()) {
3173 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3174 return false;
3175 }
3176
Steve Antond25da372017-11-06 14:50:29 -08003177 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003178 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3179 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003180 return false;
3181 }
3182
3183 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003184 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003185 return false;
3186 }
3187
3188 size_t number_removed =
3189 mutable_remote_description()->RemoveCandidates(candidates);
3190 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003191 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003192 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003193 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003194 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003195 }
3196
3197 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003198 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3199 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003200 RTC_LOG(LS_ERROR)
3201 << "RemoveIceCandidates: Error when removing remote candidates: "
3202 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003203 }
3204 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003205}
3206
Niels Möller0c4f7be2018-05-07 14:01:37 +02003207RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003208 if (!worker_thread()->IsCurrent()) {
3209 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003210 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003211 }
3212
Niels Möller0c4f7be2018-05-07 14:01:37 +02003213 const bool has_min = bitrate.min_bitrate_bps.has_value();
3214 const bool has_start = bitrate.start_bitrate_bps.has_value();
3215 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003216 if (has_min && *bitrate.min_bitrate_bps < 0) {
3217 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3218 "min_bitrate_bps <= 0");
3219 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003220 if (has_start) {
3221 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003222 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003223 "start_bitrate_bps < min_bitrate_bps");
3224 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3226 "curent_bitrate_bps < 0");
3227 }
3228 }
3229 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003230 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003232 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003233 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3234 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3235 "max_bitrate_bps < min_bitrate_bps");
3236 } else if (*bitrate.max_bitrate_bps < 0) {
3237 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3238 "max_bitrate_bps < 0");
3239 }
3240 }
3241
zstein4b979802017-06-02 14:37:37 -07003242 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003243 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003244
3245 return RTCError::OK();
3246}
3247
Alex Narest78609d52017-10-20 10:37:47 +02003248void PeerConnection::SetBitrateAllocationStrategy(
3249 std::unique_ptr<rtc::BitrateAllocationStrategy>
3250 bitrate_allocation_strategy) {
3251 rtc::Thread* worker_thread = factory_->worker_thread();
3252 if (!worker_thread->IsCurrent()) {
3253 rtc::BitrateAllocationStrategy* strategy_raw =
3254 bitrate_allocation_strategy.release();
3255 auto functor = [this, strategy_raw]() {
3256 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003257 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003258 };
3259 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3260 return;
3261 }
3262 RTC_DCHECK(call_.get());
3263 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3264}
3265
henrika5f6bf242017-11-01 11:06:56 +01003266void PeerConnection::SetAudioPlayout(bool playout) {
3267 if (!worker_thread()->IsCurrent()) {
3268 worker_thread()->Invoke<void>(
3269 RTC_FROM_HERE,
3270 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3271 return;
3272 }
3273 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003274 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003275 audio_state->SetPlayout(playout);
3276}
3277
3278void PeerConnection::SetAudioRecording(bool recording) {
3279 if (!worker_thread()->IsCurrent()) {
3280 worker_thread()->Invoke<void>(
3281 RTC_FROM_HERE,
3282 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3283 return;
3284 }
3285 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003286 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003287 audio_state->SetRecording(recording);
3288}
3289
Steve Anton8c0f7a72017-10-03 10:03:10 -07003290std::unique_ptr<rtc::SSLCertificate>
3291PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003292 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3293 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003294 return nullptr;
3295 }
Steve Antonf25303e2018-10-16 15:23:31 -07003296 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003297}
3298
Zhi Huang70b820f2018-01-27 14:16:15 -08003299std::unique_ptr<rtc::SSLCertChain>
3300PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003301 auto audio_transceiver = GetFirstAudioTransceiver();
3302 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003303 return nullptr;
3304 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003305 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003306 audio_transceiver->internal()->channel()->transport_name());
3307}
3308
3309rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3310PeerConnection::GetFirstAudioTransceiver() const {
3311 for (auto transceiver : transceivers_) {
3312 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3313 return transceiver;
3314 }
3315 }
3316 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003317}
3318
ivoc14d5dbe2016-07-04 07:06:55 -07003319bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3320 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003321 // TODO(eladalon): It would be better to not allow negative values into PC.
3322 const size_t max_size = (max_size_bytes < 0)
3323 ? RtcEventLog::kUnlimitedOutput
3324 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003325 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3326 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3327 output_period_ms = 5000;
3328 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003329 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003330 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003331 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003332}
3333
Bjorn Tereliusde939432017-11-20 17:38:14 +01003334bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3335 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003336 // TODO(eladalon): In C++14, this can be done with a lambda.
3337 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003338 bool operator()() {
3339 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3340 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003341 PeerConnection* const pc;
3342 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003343 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003344 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003345 return worker_thread()->Invoke<bool>(
3346 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003347}
3348
3349void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003350 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003351 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3352}
3353
Harald Alvestrandad88c882018-11-28 16:47:46 +01003354rtc::scoped_refptr<DtlsTransportInterface>
3355PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3356 return transport_controller_->LookupDtlsTransportByMid(mid);
3357}
3358
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003359const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003360 return pending_local_description_ ? pending_local_description_.get()
3361 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003362}
3363
3364const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003365 return pending_remote_description_ ? pending_remote_description_.get()
3366 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003367}
3368
deadbeeffe4a8a42016-12-20 17:56:17 -08003369const SessionDescriptionInterface* PeerConnection::current_local_description()
3370 const {
Steve Anton75737c02017-11-06 10:37:17 -08003371 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003372}
3373
3374const SessionDescriptionInterface* PeerConnection::current_remote_description()
3375 const {
Steve Anton75737c02017-11-06 10:37:17 -08003376 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003377}
3378
3379const SessionDescriptionInterface* PeerConnection::pending_local_description()
3380 const {
Steve Anton75737c02017-11-06 10:37:17 -08003381 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003382}
3383
3384const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3385 const {
Steve Anton75737c02017-11-06 10:37:17 -08003386 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003387}
3388
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003389void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003390 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003391 // Update stats here so that we have the most recent stats for tracks and
3392 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003393 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003394
Steve Anton75737c02017-11-06 10:37:17 -08003395 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003396 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003397
Steve Anton8af21862017-12-15 11:20:13 -08003398 for (auto transceiver : transceivers_) {
3399 transceiver->Stop();
3400 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003401
3402 // Ensure that all asynchronous stats requests are completed before destroying
3403 // the transport controller below.
3404 if (stats_collector_) {
3405 stats_collector_->WaitForPendingRequest();
3406 }
3407
3408 // Don't destroy BaseChannels until after stats has been cleaned up so that
3409 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003410 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003411
Qingsi Wang93a84392018-01-30 17:13:09 -08003412 // The event log is used in the transport controller, which must be outlived
3413 // by the former. CreateOffer by the peer connection is implemented
3414 // asynchronously and if the peer connection is closed without resetting the
3415 // WebRTC session description factory, the session description factory would
3416 // call the transport controller.
3417 webrtc_session_desc_factory_.reset();
3418 transport_controller_.reset();
3419
deadbeef42a42632017-03-10 15:18:00 -08003420 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003421 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3422 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003423
Steve Anton978b8762017-09-29 12:15:02 -07003424 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003425 call_.reset();
3426 // The event log must outlive call (and any other object that uses it).
3427 event_log_.reset();
3428 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003429 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003430 // The .h file says that observer can be discarded after close() returns.
3431 // Make sure this is true.
3432 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003433}
3434
Steve Antonad182762018-09-05 20:22:40 +00003435void PeerConnection::OnMessage(rtc::Message* msg) {
3436 switch (msg->message_id) {
3437 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3438 SetSessionDescriptionMsg* param =
3439 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3440 param->observer->OnSuccess();
3441 delete param;
3442 break;
3443 }
3444 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3445 SetSessionDescriptionMsg* param =
3446 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3447 param->observer->OnFailure(std::move(param->error));
3448 delete param;
3449 break;
3450 }
3451 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3452 CreateSessionDescriptionMsg* param =
3453 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3454 param->observer->OnFailure(std::move(param->error));
3455 delete param;
3456 break;
3457 }
3458 case MSG_GETSTATS: {
3459 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3460 StatsReports reports;
3461 stats_->GetStats(param->track, &reports);
3462 param->observer->OnComplete(reports);
3463 delete param;
3464 break;
3465 }
3466 case MSG_FREE_DATACHANNELS: {
3467 sctp_data_channels_to_free_.clear();
3468 break;
3469 }
3470 case MSG_REPORT_USAGE_PATTERN: {
3471 ReportUsagePattern();
3472 break;
3473 }
3474 default:
3475 RTC_NOTREACHED() << "Not implemented";
3476 break;
3477 }
3478}
3479
Steve Antonafb0bb72018-02-20 11:35:37 -08003480cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3481 RTC_DCHECK(!IsUnifiedPlan());
3482 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3483 GetAudioTransceiver()->internal()->channel());
3484 if (voice_channel) {
3485 return voice_channel->media_channel();
3486 } else {
3487 return nullptr;
3488 }
3489}
3490
3491cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3492 RTC_DCHECK(!IsUnifiedPlan());
3493 auto* video_channel = static_cast<cricket::VideoChannel*>(
3494 GetVideoTransceiver()->internal()->channel());
3495 if (video_channel) {
3496 return video_channel->media_channel();
3497 } else {
3498 return nullptr;
3499 }
3500}
3501
Steve Anton4171afb2017-11-20 10:20:22 -08003502void PeerConnection::CreateAudioReceiver(
3503 MediaStreamInterface* stream,
3504 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003505 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3506 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003507 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3508 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003509 auto* audio_receiver = new AudioRtpReceiver(
3510 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003511 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003512 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3513 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3514 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003515 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003516 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003517 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003518}
3519
Steve Anton4171afb2017-11-20 10:20:22 -08003520void PeerConnection::CreateVideoReceiver(
3521 MediaStreamInterface* stream,
3522 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003523 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3524 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003525 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3526 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003527 auto* video_receiver = new VideoRtpReceiver(
3528 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003529 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003530 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3531 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3532 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003533 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003534 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003535 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003536}
3537
deadbeef70ab1a12015-09-28 16:53:55 -07003538// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3539// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003540rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003541 const RtpSenderInfo& remote_sender_info) {
3542 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3543 if (!receiver) {
3544 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3545 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003546 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003547 }
Steve Anton4171afb2017-11-20 10:20:22 -08003548 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3549 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3550 } else {
3551 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3552 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003553 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003554}
3555
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003556void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3557 MediaStreamInterface* stream) {
3558 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003559 RTC_DCHECK(track);
3560 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003561 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003562 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003563 // We already have a sender for this track, so just change the stream_id
3564 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003565 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003566 return;
3567 }
3568
3569 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003570 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003571 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003572 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003573 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003574 // If the sender has already been configured in SDP, we call SetSsrc,
3575 // which will connect the sender to the underlying transport. This can
3576 // occur if a local session description that contains the ID of the sender
3577 // is set before AddStream is called. It can also occur if the local
3578 // session description is not changed and RemoveStream is called, and
3579 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003580 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003581 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003582 if (sender_info) {
3583 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003584 }
3585}
3586
3587// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3588// indefinitely, when we have unified plan SDP.
3589void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3590 MediaStreamInterface* stream) {
3591 RTC_DCHECK(!IsClosed());
3592 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003593 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003594 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3595 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003596 return;
3597 }
Steve Anton4171afb2017-11-20 10:20:22 -08003598 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003599}
3600
3601void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3602 MediaStreamInterface* stream) {
3603 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003604 RTC_DCHECK(track);
3605 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003606 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003607 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003608 // We already have a sender for this track, so just change the stream_id
3609 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003610 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003611 return;
3612 }
3613
3614 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003615 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003616 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003617 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003618 GetVideoTransceiver()->internal()->AddSender(new_sender);
3619 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003620 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003621 if (sender_info) {
3622 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003623 }
3624}
3625
3626void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3627 MediaStreamInterface* stream) {
3628 RTC_DCHECK(!IsClosed());
3629 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003630 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003631 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3632 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003633 return;
3634 }
Steve Anton4171afb2017-11-20 10:20:22 -08003635 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003636}
3637
Steve Antonba818672017-11-06 10:21:57 -08003638void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003639 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003640 if (ice_connection_state_ == new_state) {
3641 return;
3642 }
3643
deadbeefcbecd352015-09-23 11:50:27 -07003644 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003645 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003646 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003647 return;
3648 }
Steve Antonba818672017-11-06 10:21:57 -08003649
Mirko Bonadei675513b2017-11-09 11:09:25 +01003650 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3651 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003652 RTC_DCHECK(ice_connection_state_ !=
3653 PeerConnectionInterface::kIceConnectionClosed);
3654
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003655 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003656 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003657}
3658
Alex Loiko9289eda2018-11-23 16:18:59 +00003659void PeerConnection::SetStandardizedIceConnectionState(
3660 PeerConnectionInterface::IceConnectionState new_state) {
3661 RTC_DCHECK(signaling_thread()->IsCurrent());
3662 if (standardized_ice_connection_state_ == new_state)
3663 return;
3664 if (IsClosed())
3665 return;
3666 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003667 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003668}
3669
Jonas Olsson635474e2018-10-18 15:58:17 +02003670void PeerConnection::SetConnectionState(
3671 PeerConnectionInterface::PeerConnectionState new_state) {
3672 RTC_DCHECK(signaling_thread()->IsCurrent());
3673 if (connection_state_ == new_state)
3674 return;
3675 if (IsClosed())
3676 return;
3677 connection_state_ = new_state;
3678 Observer()->OnConnectionChange(new_state);
3679}
3680
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003681void PeerConnection::OnIceGatheringChange(
3682 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003683 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003684 if (IsClosed()) {
3685 return;
3686 }
3687 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003688 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003689}
3690
jbauch81bf7b02017-03-25 08:31:12 -07003691void PeerConnection::OnIceCandidate(
3692 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003693 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003694 if (IsClosed()) {
3695 return;
3696 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003697 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003698 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3699 candidate->candidate().address().IsPrivateIP()) {
3700 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3701 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003702 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003703}
3704
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003705void PeerConnection::OnIceCandidatesRemoved(
3706 const std::vector<cricket::Candidate>& candidates) {
3707 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003708 if (IsClosed()) {
3709 return;
3710 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003711 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003712}
3713
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003714void PeerConnection::ChangeSignalingState(
3715 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003716 RTC_DCHECK(signaling_thread()->IsCurrent());
3717 if (signaling_state_ == signaling_state) {
3718 return;
3719 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003720 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3721 << GetSignalingStateString(signaling_state_)
3722 << " New state: "
3723 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003724 signaling_state_ = signaling_state;
3725 if (signaling_state == kClosed) {
3726 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003727 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003728 standardized_ice_connection_state_ =
3729 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003730 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3731 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003732 if (ice_gathering_state_ != kIceGatheringComplete) {
3733 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003734 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003735 }
3736 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003737 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003738}
3739
deadbeefeb459812015-12-15 19:24:43 -08003740void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3741 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003742 if (IsClosed()) {
3743 return;
3744 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003745 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003746 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003747}
3748
deadbeefeb459812015-12-15 19:24:43 -08003749void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3750 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003751 if (IsClosed()) {
3752 return;
3753 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003754 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003755 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003756}
3757
3758void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3759 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003760 if (IsClosed()) {
3761 return;
3762 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003763 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003764 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003765}
3766
3767void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3768 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003769 if (IsClosed()) {
3770 return;
3771 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003772 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003773 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003774}
3775
Henrik Boström31638672017-11-23 17:48:32 +01003776void PeerConnection::PostSetSessionDescriptionSuccess(
3777 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003778 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3779 signaling_thread()->Post(RTC_FROM_HERE, this,
3780 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003781}
3782
deadbeefab9b2d12015-10-14 11:33:11 -07003783void PeerConnection::PostSetSessionDescriptionFailure(
3784 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003785 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003786 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003787 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3788 msg->error = std::move(error);
3789 signaling_thread()->Post(RTC_FROM_HERE, this,
3790 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003791}
3792
3793void PeerConnection::PostCreateSessionDescriptionFailure(
3794 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003795 RTCError error) {
3796 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003797 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3798 msg->error = std::move(error);
3799 signaling_thread()->Post(RTC_FROM_HERE, this,
3800 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003801}
3802
zhihuang1c378ed2017-08-17 14:10:50 -07003803void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003804 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003805 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003806 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003807
Steve Antondcc3c022017-12-22 16:02:54 -08003808 if (IsUnifiedPlan()) {
3809 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3810 } else {
3811 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3812 }
3813
Steve Antonfa2260d2017-12-28 16:38:23 -08003814 // Intentionally unset the data channel type for RTP data channel with the
3815 // second condition. Otherwise the RTP data channels would be successfully
3816 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3817 // when building with chromium. We want to leave RTP data channels broken, so
3818 // people won't try to use them.
3819 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3820 session_options->data_channel_type = data_channel_type();
3821 }
3822
Steve Antondcc3c022017-12-22 16:02:54 -08003823 // Apply ICE restart flag and renomination flag.
3824 for (auto& options : session_options->media_description_options) {
3825 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3826 options.transport_options.enable_ice_renomination =
3827 configuration_.enable_ice_renomination;
3828 }
3829
3830 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003831 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003832 session_options->pooled_ice_credentials =
3833 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3834 RTC_FROM_HERE,
3835 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3836 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003837 session_options->offer_extmap_allow_mixed =
3838 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003839}
3840
3841void PeerConnection::GetOptionsForPlanBOffer(
3842 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3843 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003844 // Figure out transceiver directional preferences.
3845 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3846 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3847
3848 // By default, generate sendrecv/recvonly m= sections.
3849 bool recv_audio = true;
3850 bool recv_video = true;
3851
3852 // By default, only offer a new m= section if we have media to send with it.
3853 bool offer_new_audio_description = send_audio;
3854 bool offer_new_video_description = send_video;
3855 bool offer_new_data_description = HasDataChannels();
3856
3857 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003858 if (offer_answer_options.offer_to_receive_audio !=
3859 RTCOfferAnswerOptions::kUndefined) {
3860 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003861 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003862 offer_new_audio_description ||
3863 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003864 }
Steve Antondcc3c022017-12-22 16:02:54 -08003865 if (offer_answer_options.offer_to_receive_video !=
3866 RTCOfferAnswerOptions::kUndefined) {
3867 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003868 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003869 offer_new_video_description ||
3870 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003871 }
3872
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003873 absl::optional<size_t> audio_index;
3874 absl::optional<size_t> video_index;
3875 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003876 // If a current description exists, generate m= sections in the same order,
3877 // using the first audio/video/data section that appears and rejecting
3878 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003879 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003880 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003881 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003882 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3883 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3884 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003885 }
3886
zhihuang1c378ed2017-08-17 14:10:50 -07003887 // Add audio/video/data m= sections to the end if needed.
3888 if (!audio_index && offer_new_audio_description) {
3889 session_options->media_description_options.push_back(
3890 cricket::MediaDescriptionOptions(
3891 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003892 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3893 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003894 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003895 }
zhihuang1c378ed2017-08-17 14:10:50 -07003896 if (!video_index && offer_new_video_description) {
3897 session_options->media_description_options.push_back(
3898 cricket::MediaDescriptionOptions(
3899 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003900 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3901 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003902 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003903 }
zhihuang1c378ed2017-08-17 14:10:50 -07003904 if (!data_index && offer_new_data_description) {
3905 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003906 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003907 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003908 }
3909
3910 cricket::MediaDescriptionOptions* audio_media_description_options =
3911 !audio_index ? nullptr
3912 : &session_options->media_description_options[*audio_index];
3913 cricket::MediaDescriptionOptions* video_media_description_options =
3914 !video_index ? nullptr
3915 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003916
Steve Anton4171afb2017-11-20 10:20:22 -08003917 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003918 video_media_description_options,
3919 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003920}
3921
3922// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3923// and return a reference to it.
3924// Generated MIDs should be no more than 3 bytes long to take up less space in
3925// the RTP packet.
3926static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3927 RTC_DCHECK(used_mids);
3928 // We're boring: just generate MIDs 0, 1, 2, ...
3929 size_t i = 0;
3930 std::set<std::string>::iterator it;
3931 bool inserted;
3932 do {
3933 std::string mid = rtc::ToString(i++);
3934 auto insert_result = used_mids->insert(mid);
3935 it = insert_result.first;
3936 inserted = insert_result.second;
3937 } while (!inserted);
3938 return *it;
3939}
3940
3941static cricket::MediaDescriptionOptions
3942GetMediaDescriptionOptionsForTransceiver(
3943 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3944 transceiver,
3945 const std::string& mid) {
3946 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003947 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003948 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003949 // This behavior is specified in JSEP. The gist is that:
3950 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3951 // sendrecv.
3952 // 2. If the MSID is included, then it must be included in any subsequent
3953 // offer/answer exactly the same until the RtpTransceiver is stopped.
3954 if (!transceiver->stopped() &&
3955 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3956 transceiver->internal()->has_ever_been_used_to_send())) {
3957 cricket::SenderOptions sender_options;
3958 sender_options.track_id = transceiver->sender()->id();
3959 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003960 int num_send_encoding_layers =
3961 transceiver->sender()->init_send_encodings().size();
3962 sender_options.num_sim_layers =
3963 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003964 media_description_options.sender_options.push_back(sender_options);
3965 }
Steve Antondcc3c022017-12-22 16:02:54 -08003966 return media_description_options;
3967}
3968
Steve Anton5c72e712018-12-10 14:25:30 -08003969// Returns the ContentInfo at mline index |i|, or null if none exists.
3970static const ContentInfo* GetContentByIndex(
3971 const SessionDescriptionInterface* sdesc,
3972 size_t i) {
3973 if (!sdesc) {
3974 return nullptr;
3975 }
3976 const ContentInfos& contents = sdesc->description()->contents();
3977 return (i < contents.size() ? &contents[i] : nullptr);
3978}
3979
Steve Antondcc3c022017-12-22 16:02:54 -08003980void PeerConnection::GetOptionsForUnifiedPlanOffer(
3981 const RTCOfferAnswerOptions& offer_answer_options,
3982 cricket::MediaSessionOptions* session_options) {
3983 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3984 // Offers) and 5.2.2 (Subsequent Offers).
3985 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3986 const ContentInfos& local_contents =
3987 (local_description() ? local_description()->description()->contents()
3988 : ContentInfos());
3989 const ContentInfos& remote_contents =
3990 (remote_description() ? remote_description()->description()->contents()
3991 : ContentInfos());
3992 // The mline indices that can be recycled. New transceivers should reuse these
3993 // slots first.
3994 std::queue<size_t> recycleable_mline_indices;
3995 // Track the MIDs used in previous offer/answer exchanges and the current
3996 // offer so that new, unique MIDs are generated.
3997 std::set<std::string> used_mids = seen_mids_;
3998 // First, go through each media section that exists in either the local or
3999 // remote description and generate a media section in this offer for the
4000 // associated transceiver. If a media section can be recycled, generate a
4001 // default, rejected media section here that can be later overwritten.
4002 for (size_t i = 0;
4003 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4004 // Either |local_content| or |remote_content| is non-null.
4005 const ContentInfo* local_content =
4006 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004007 const ContentInfo* current_local_content =
4008 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004009 const ContentInfo* remote_content =
4010 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004011 const ContentInfo* current_remote_content =
4012 GetContentByIndex(current_remote_description(), i);
4013 bool had_been_rejected =
4014 (current_local_content && current_local_content->rejected) ||
4015 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004016 const std::string& mid =
4017 (local_content ? local_content->name : remote_content->name);
4018 cricket::MediaType media_type =
4019 (local_content ? local_content->media_description()->type()
4020 : remote_content->media_description()->type());
4021 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4022 media_type == cricket::MEDIA_TYPE_VIDEO) {
4023 auto transceiver = GetAssociatedTransceiver(mid);
4024 RTC_CHECK(transceiver);
4025 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004026 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004027 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004028 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004029 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4030 RtpTransceiverDirection::kInactive,
4031 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004032 recycleable_mline_indices.push(i);
4033 } else {
4034 session_options->media_description_options.push_back(
4035 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4036 // CreateOffer shouldn't really cause any state changes in
4037 // PeerConnection, but we need a way to match new transceivers to new
4038 // media sections in SetLocalDescription and JSEP specifies this is done
4039 // by recording the index of the media section generated for the
4040 // transceiver in the offer.
4041 transceiver->internal()->set_mline_index(i);
4042 }
4043 } else {
4044 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004045 RTC_CHECK(GetDataMid());
4046 if (had_been_rejected || mid != *GetDataMid()) {
4047 session_options->media_description_options.push_back(
4048 GetMediaDescriptionOptionsForRejectedData(mid));
4049 } else {
4050 session_options->media_description_options.push_back(
4051 GetMediaDescriptionOptionsForActiveData(mid));
4052 }
Steve Antondcc3c022017-12-22 16:02:54 -08004053 }
4054 }
4055 // Next, look for transceivers that are newly added (that is, are not stopped
4056 // and not associated). Reuse media sections marked as recyclable first,
4057 // otherwise append to the end of the offer. New media sections should be
4058 // added in the order they were added to the PeerConnection.
4059 for (auto transceiver : transceivers_) {
4060 if (transceiver->mid() || transceiver->stopped()) {
4061 continue;
4062 }
4063 size_t mline_index;
4064 if (!recycleable_mline_indices.empty()) {
4065 mline_index = recycleable_mline_indices.front();
4066 recycleable_mline_indices.pop();
4067 session_options->media_description_options[mline_index] =
4068 GetMediaDescriptionOptionsForTransceiver(transceiver,
4069 AllocateMid(&used_mids));
4070 } else {
4071 mline_index = session_options->media_description_options.size();
4072 session_options->media_description_options.push_back(
4073 GetMediaDescriptionOptionsForTransceiver(transceiver,
4074 AllocateMid(&used_mids)));
4075 }
4076 // See comment above for why CreateOffer changes the transceiver's state.
4077 transceiver->internal()->set_mline_index(mline_index);
4078 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004079 // Lastly, add a m-section if we have local data channels and an m section
4080 // does not already exist.
4081 if (!GetDataMid() && HasDataChannels()) {
4082 session_options->media_description_options.push_back(
4083 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4084 }
Steve Antondcc3c022017-12-22 16:02:54 -08004085}
4086
4087void PeerConnection::GetOptionsForAnswer(
4088 const RTCOfferAnswerOptions& offer_answer_options,
4089 cricket::MediaSessionOptions* session_options) {
4090 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4091
4092 if (IsUnifiedPlan()) {
4093 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4094 } else {
4095 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4096 }
4097
Steve Antonfa2260d2017-12-28 16:38:23 -08004098 // Intentionally unset the data channel type for RTP data channel. Otherwise
4099 // the RTP data channels would be successfully negotiated by default and the
4100 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4101 // We want to leave RTP data channels broken, so people won't try to use them.
4102 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4103 session_options->data_channel_type = data_channel_type();
4104 }
4105
Steve Antondcc3c022017-12-22 16:02:54 -08004106 // Apply ICE renomination flag.
4107 for (auto& options : session_options->media_description_options) {
4108 options.transport_options.enable_ice_renomination =
4109 configuration_.enable_ice_renomination;
4110 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004111
4112 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004113 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004114 session_options->pooled_ice_credentials =
4115 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4116 RTC_FROM_HERE,
4117 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4118 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004119}
4120
Steve Antondcc3c022017-12-22 16:02:54 -08004121void PeerConnection::GetOptionsForPlanBAnswer(
4122 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004123 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004124 // Figure out transceiver directional preferences.
4125 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4126 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4127
4128 // By default, generate sendrecv/recvonly m= sections. The direction is also
4129 // restricted by the direction in the offer.
4130 bool recv_audio = true;
4131 bool recv_video = true;
4132
4133 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004134 if (offer_answer_options.offer_to_receive_audio !=
4135 RTCOfferAnswerOptions::kUndefined) {
4136 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004137 }
Steve Antondcc3c022017-12-22 16:02:54 -08004138 if (offer_answer_options.offer_to_receive_video !=
4139 RTCOfferAnswerOptions::kUndefined) {
4140 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004141 }
4142
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004143 absl::optional<size_t> audio_index;
4144 absl::optional<size_t> video_index;
4145 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004146
4147 // Generate m= sections that match those in the offer.
4148 // Note that mediasession.cc will handle intersection our preferred
4149 // direction with the offered direction.
4150 GenerateMediaDescriptionOptions(
4151 remote_description(),
4152 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4153 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4154 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004155
4156 cricket::MediaDescriptionOptions* audio_media_description_options =
4157 !audio_index ? nullptr
4158 : &session_options->media_description_options[*audio_index];
4159 cricket::MediaDescriptionOptions* video_media_description_options =
4160 !video_index ? nullptr
4161 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004162
Steve Anton4171afb2017-11-20 10:20:22 -08004163 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004164 video_media_description_options,
4165 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004166}
zhihuangaf388472016-11-02 16:49:48 -07004167
Steve Antondcc3c022017-12-22 16:02:54 -08004168void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4169 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4170 cricket::MediaSessionOptions* session_options) {
4171 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4172 // Answers) and 5.3.2 (Subsequent Answers).
4173 RTC_DCHECK(remote_description());
4174 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4175 for (const ContentInfo& content :
4176 remote_description()->description()->contents()) {
4177 cricket::MediaType media_type = content.media_description()->type();
4178 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4179 media_type == cricket::MEDIA_TYPE_VIDEO) {
4180 auto transceiver = GetAssociatedTransceiver(content.name);
4181 RTC_CHECK(transceiver);
4182 session_options->media_description_options.push_back(
4183 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4184 } else {
4185 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004186 // Reject all data sections if data channels are disabled.
4187 // Reject a data section if it has already been rejected.
4188 // Reject all data sections except for the first one.
4189 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4190 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004191 session_options->media_description_options.push_back(
4192 GetMediaDescriptionOptionsForRejectedData(content.name));
4193 } else {
4194 session_options->media_description_options.push_back(
4195 GetMediaDescriptionOptionsForActiveData(content.name));
4196 }
Steve Antondcc3c022017-12-22 16:02:54 -08004197 }
4198 }
htaa2a49d92016-03-04 02:51:39 -08004199}
4200
zhihuang1c378ed2017-08-17 14:10:50 -07004201void PeerConnection::GenerateMediaDescriptionOptions(
4202 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004203 RtpTransceiverDirection audio_direction,
4204 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004205 absl::optional<size_t>* audio_index,
4206 absl::optional<size_t>* video_index,
4207 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004208 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004209 for (const cricket::ContentInfo& content :
4210 session_desc->description()->contents()) {
4211 if (IsAudioContent(&content)) {
4212 // If we already have an audio m= section, reject this extra one.
4213 if (*audio_index) {
4214 session_options->media_description_options.push_back(
4215 cricket::MediaDescriptionOptions(
4216 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004217 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004218 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004219 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004220 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004221 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4222 content.name, audio_direction,
4223 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004224 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004225 }
4226 } else if (IsVideoContent(&content)) {
4227 // If we already have an video m= section, reject this extra one.
4228 if (*video_index) {
4229 session_options->media_description_options.push_back(
4230 cricket::MediaDescriptionOptions(
4231 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004232 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004233 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004234 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004235 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004236 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4237 content.name, video_direction,
4238 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004239 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004240 }
4241 } else {
4242 RTC_DCHECK(IsDataContent(&content));
4243 // If we already have an data m= section, reject this extra one.
4244 if (*data_index) {
4245 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004246 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004247 } else {
4248 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004249 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004250 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004251 }
4252 }
htaa2a49d92016-03-04 02:51:39 -08004253 }
deadbeefab9b2d12015-10-14 11:33:11 -07004254}
4255
Steve Antonfa2260d2017-12-28 16:38:23 -08004256cricket::MediaDescriptionOptions
4257PeerConnection::GetMediaDescriptionOptionsForActiveData(
4258 const std::string& mid) const {
4259 // Direction for data sections is meaningless, but legacy endpoints might
4260 // expect sendrecv.
4261 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4262 RtpTransceiverDirection::kSendRecv,
4263 /*stopped=*/false);
4264 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4265 return options;
4266}
4267
4268cricket::MediaDescriptionOptions
4269PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4270 const std::string& mid) const {
4271 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4272 RtpTransceiverDirection::kInactive,
4273 /*stopped=*/true);
4274 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4275 return options;
4276}
4277
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004278absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004279 switch (data_channel_type_) {
4280 case cricket::DCT_RTP:
4281 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004282 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004283 }
4284 return rtp_data_channel_->content_name();
4285 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004286 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004287 case cricket::DCT_MEDIA_TRANSPORT:
4288 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004289 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004290 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004291 }
4292}
4293
Steve Anton4171afb2017-11-20 10:20:22 -08004294void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4295 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4296 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004297 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004298}
4299
Steve Anton4171afb2017-11-20 10:20:22 -08004300void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004301 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004302 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004303 cricket::MediaType media_type,
4304 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004305 RTC_DCHECK(!IsUnifiedPlan());
4306
Steve Anton4171afb2017-11-20 10:20:22 -08004307 std::vector<RtpSenderInfo>* current_senders =
4308 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004309
Steve Anton4171afb2017-11-20 10:20:22 -08004310 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004311 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004312 for (auto sender_it = current_senders->begin();
4313 sender_it != current_senders->end();
4314 /* incremented manually */) {
4315 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004316 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004317 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004318 std::string params_stream_id;
4319 if (params) {
4320 params_stream_id =
4321 (!params->first_stream_id().empty() ? params->first_stream_id()
4322 : kDefaultStreamId);
4323 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004324 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004325 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004326 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004327 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004328 sender_exists) {
4329 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004330 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004331 OnRemoteSenderRemoved(info, media_type);
4332 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004333 }
4334 }
4335
Steve Anton4171afb2017-11-20 10:20:22 -08004336 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004337 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004338 if (!params.has_ssrcs()) {
4339 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4340 // sender, this means it is coming from a Unified Plan endpoint,so we just
4341 // create a default.
4342 default_sender_needed = true;
4343 break;
4344 }
4345
Seth Hampson845e8782018-03-02 11:34:10 -08004346 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004347 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004348 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4349 // not supported in Plan B, we just take the first here and create the
4350 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004351 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004352 (!params.first_stream_id().empty() ? params.first_stream_id()
4353 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004354 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004355 uint32_t ssrc = params.first_ssrc();
4356
4357 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004358 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004359 if (!stream) {
4360 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004361 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004362 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004363 remote_streams_->AddStream(stream);
4364 new_streams->AddStream(stream);
4365 }
4366
Steve Anton4171afb2017-11-20 10:20:22 -08004367 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004368 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004369 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004370 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004371 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004372 }
4373 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004374
Steve Anton4171afb2017-11-20 10:20:22 -08004375 // Add default sender if necessary.
4376 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004377 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004378 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004379 if (!default_stream) {
4380 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004381 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004382 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004383 remote_streams_->AddStream(default_stream);
4384 new_streams->AddStream(default_stream);
4385 }
Steve Anton4171afb2017-11-20 10:20:22 -08004386 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4387 ? kDefaultAudioSenderId
4388 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004389 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004390 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004391 if (!default_sender_info) {
4392 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004393 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004394 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004395 }
4396 }
deadbeefab9b2d12015-10-14 11:33:11 -07004397}
4398
Steve Anton4171afb2017-11-20 10:20:22 -08004399void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4400 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004401 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4402 << " receiver for track_id=" << sender_info.sender_id
4403 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004404
Steve Anton3d954a62018-04-02 11:27:23 -07004405 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004406 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004407 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004408 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004409 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004410 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004411 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004412 }
4413}
4414
Steve Anton4171afb2017-11-20 10:20:22 -08004415void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4416 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004417 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4418 << " receiver for track_id=" << sender_info.sender_id
4419 << " and stream_id=" << sender_info.stream_id;
4420
Seth Hampson845e8782018-03-02 11:34:10 -08004421 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004422
Henrik Boström933d8b02017-10-10 10:05:16 -07004423 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004424 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004425 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4426 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004427 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004428 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004429 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004430 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004431 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004432 }
4433 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004434 // Stopping or destroying a VideoRtpReceiver will end the
4435 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004436 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004437 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004438 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004439 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004440 // There's no guarantee the track is still available, e.g. the track may
4441 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004442 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004443 }
4444 } else {
nisseede5da42017-01-12 05:15:36 -08004445 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004446 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004447 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004448 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004449 }
deadbeefab9b2d12015-10-14 11:33:11 -07004450}
4451
4452void PeerConnection::UpdateEndedRemoteMediaStreams() {
4453 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4454 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4455 MediaStreamInterface* stream = remote_streams_->at(i);
4456 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4457 streams_to_remove.push_back(stream);
4458 }
4459 }
4460
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004461 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004462 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004463 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004464 }
4465}
4466
Steve Anton4171afb2017-11-20 10:20:22 -08004467void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004468 const std::vector<cricket::StreamParams>& streams,
4469 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004470 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004471
Seth Hampson845e8782018-03-02 11:34:10 -08004472 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004473 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004474 for (auto sender_it = current_senders->begin();
4475 sender_it != current_senders->end();
4476 /* incremented manually */) {
4477 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004478 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004479 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4480 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004481 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004482 OnLocalSenderRemoved(info, media_type);
4483 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004484 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004485 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004486 }
4487 }
4488
Steve Anton4171afb2017-11-20 10:20:22 -08004489 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004490 for (const cricket::StreamParams& params : streams) {
4491 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004492 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004493 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004494 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004495 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004496 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004497 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004498 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004499 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004500 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004501 }
4502 }
4503}
4504
Steve Anton4171afb2017-11-20 10:20:22 -08004505void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4506 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004507 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004508 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004509 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004510 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4511 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004512 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004513 return;
4514 }
4515
deadbeeffac06552015-11-25 11:26:01 -08004516 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004517 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004518 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004519 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004520 }
deadbeeffac06552015-11-25 11:26:01 -08004521
Seth Hampson5b4f0752018-04-02 16:31:36 -07004522 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004523 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004524}
4525
Steve Anton4171afb2017-11-20 10:20:22 -08004526void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4527 cricket::MediaType media_type) {
4528 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004529 if (!sender) {
4530 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004531 // SessionDescriptions has been renegotiated.
4532 return;
4533 }
deadbeeffac06552015-11-25 11:26:01 -08004534
4535 // A sender has been removed from the SessionDescription but it's still
4536 // associated with the PeerConnection. This only occurs if the SDP doesn't
4537 // match with the calls to CreateSender, AddStream and RemoveStream.
4538 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004539 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004540 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004541 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004542 }
deadbeeffac06552015-11-25 11:26:01 -08004543
Steve Anton4171afb2017-11-20 10:20:22 -08004544 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004545}
4546
4547void PeerConnection::UpdateLocalRtpDataChannels(
4548 const cricket::StreamParamsVec& streams) {
4549 std::vector<std::string> existing_channels;
4550
4551 // Find new and active data channels.
4552 for (const cricket::StreamParams& params : streams) {
4553 // |it->sync_label| is actually the data channel label. The reason is that
4554 // we use the same naming of data channels as we do for
4555 // MediaStreams and Tracks.
4556 // For MediaStreams, the sync_label is the MediaStream label and the
4557 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004558 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004559 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004560 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004561 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004562 continue;
4563 }
4564 // Set the SSRC the data channel should use for sending.
4565 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4566 existing_channels.push_back(data_channel_it->first);
4567 }
4568
4569 UpdateClosingRtpDataChannels(existing_channels, true);
4570}
4571
4572void PeerConnection::UpdateRemoteRtpDataChannels(
4573 const cricket::StreamParamsVec& streams) {
4574 std::vector<std::string> existing_channels;
4575
4576 // Find new and active data channels.
4577 for (const cricket::StreamParams& params : streams) {
4578 // The data channel label is either the mslabel or the SSRC if the mslabel
4579 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004580 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004581 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004582 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004583 auto data_channel_it = rtp_data_channels_.find(label);
4584 if (data_channel_it == rtp_data_channels_.end()) {
4585 // This is a new data channel.
4586 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4587 } else {
4588 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4589 }
4590 existing_channels.push_back(label);
4591 }
4592
4593 UpdateClosingRtpDataChannels(existing_channels, false);
4594}
4595
4596void PeerConnection::UpdateClosingRtpDataChannels(
4597 const std::vector<std::string>& active_channels,
4598 bool is_local_update) {
4599 auto it = rtp_data_channels_.begin();
4600 while (it != rtp_data_channels_.end()) {
4601 DataChannel* data_channel = it->second;
4602 if (std::find(active_channels.begin(), active_channels.end(),
4603 data_channel->label()) != active_channels.end()) {
4604 ++it;
4605 continue;
4606 }
4607
4608 if (is_local_update) {
4609 data_channel->SetSendSsrc(0);
4610 } else {
4611 data_channel->RemotePeerRequestClose();
4612 }
4613
4614 if (data_channel->state() == DataChannel::kClosed) {
4615 rtp_data_channels_.erase(it);
4616 it = rtp_data_channels_.begin();
4617 } else {
4618 ++it;
4619 }
4620 }
4621}
4622
4623void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4624 uint32_t remote_ssrc) {
4625 rtc::scoped_refptr<DataChannel> channel(
4626 InternalCreateDataChannel(label, nullptr));
4627 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004628 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004629 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004630 return;
4631 }
4632 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004633 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4634 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004635 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004636}
4637
4638rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4639 const std::string& label,
4640 const InternalDataChannelInit* config) {
4641 if (IsClosed()) {
4642 return nullptr;
4643 }
Steve Anton75737c02017-11-06 10:37:17 -08004644 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004645 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004646 << "InternalCreateDataChannel: Data is not supported in this call.";
4647 return nullptr;
4648 }
4649 InternalDataChannelInit new_config =
4650 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004651 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004652 if (new_config.id < 0) {
4653 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004654 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004655 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004656 RTC_LOG(LS_ERROR)
4657 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004658 return nullptr;
4659 }
4660 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004661 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004662 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004663 return nullptr;
4664 }
4665 }
4666
Steve Anton75737c02017-11-06 10:37:17 -08004667 rtc::scoped_refptr<DataChannel> channel(
4668 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004669 if (!channel) {
4670 sid_allocator_.ReleaseSid(new_config.id);
4671 return nullptr;
4672 }
4673
4674 if (channel->data_channel_type() == cricket::DCT_RTP) {
4675 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004676 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4677 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004678 return nullptr;
4679 }
4680 rtp_data_channels_[channel->label()] = channel;
4681 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004682 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004683 sctp_data_channels_.push_back(channel);
4684 channel->SignalClosed.connect(this,
4685 &PeerConnection::OnSctpDataChannelClosed);
4686 }
4687
Steve Anton2d8609c2018-01-23 16:38:46 -08004688 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004689 return channel;
4690}
4691
4692bool PeerConnection::HasDataChannels() const {
4693 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4694}
4695
4696void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4697 for (const auto& channel : sctp_data_channels_) {
4698 if (channel->id() < 0) {
4699 int sid;
4700 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004701 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004702 continue;
4703 }
4704 channel->SetSctpSid(sid);
4705 }
4706 }
4707}
4708
4709void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004710 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004711 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4712 ++it) {
4713 if (it->get() == channel) {
4714 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004715 // After the closing procedure is done, it's safe to use this ID for
4716 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004717 sid_allocator_.ReleaseSid(channel->id());
4718 }
deadbeefbd292462015-12-14 18:15:29 -08004719 // Since this method is triggered by a signal from the DataChannel,
4720 // we can't free it directly here; we need to free it asynchronously.
4721 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004722 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004723 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4724 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004725 return;
4726 }
4727 }
4728}
4729
deadbeefab9b2d12015-10-14 11:33:11 -07004730void PeerConnection::OnDataChannelDestroyed() {
4731 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4732 // DataChannel may callback to us and try to modify the list.
4733 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4734 temp_rtp_dcs.swap(rtp_data_channels_);
4735 for (const auto& kv : temp_rtp_dcs) {
4736 kv.second->OnTransportChannelDestroyed();
4737 }
4738
4739 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4740 temp_sctp_dcs.swap(sctp_data_channels_);
4741 for (const auto& channel : temp_sctp_dcs) {
4742 channel->OnTransportChannelDestroyed();
4743 }
4744}
4745
4746void PeerConnection::OnDataChannelOpenMessage(
4747 const std::string& label,
4748 const InternalDataChannelInit& config) {
4749 rtc::scoped_refptr<DataChannel> channel(
4750 InternalCreateDataChannel(label, &config));
4751 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004752 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004753 return;
4754 }
4755
deadbeefa601f5c2016-06-06 14:27:39 -07004756 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4757 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004758 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004759 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004760}
4761
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004762bool PeerConnection::HandleOpenMessage_s(
4763 const cricket::ReceiveDataParams& params,
4764 const rtc::CopyOnWriteBuffer& buffer) {
4765 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4766 // Received OPEN message; parse and signal that a new data channel should
4767 // be created.
4768 std::string label;
4769 InternalDataChannelInit config;
4770 config.id = params.ssrc;
4771 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4772 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4773 << params.ssrc;
4774 return true;
4775 }
4776 config.open_handshake_role = InternalDataChannelInit::kAcker;
4777 OnDataChannelOpenMessage(label, config);
4778 return true;
4779 }
4780 return false;
4781}
4782
Steve Anton4171afb2017-11-20 10:20:22 -08004783rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4784PeerConnection::GetAudioTransceiver() const {
4785 // This method only works with Plan B SDP, where there is a single
4786 // audio/video transceiver.
4787 RTC_DCHECK(!IsUnifiedPlan());
4788 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004789 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004790 return transceiver;
4791 }
4792 }
4793 RTC_NOTREACHED();
4794 return nullptr;
4795}
4796
4797rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4798PeerConnection::GetVideoTransceiver() const {
4799 // This method only works with Plan B SDP, where there is a single
4800 // audio/video transceiver.
4801 RTC_DCHECK(!IsUnifiedPlan());
4802 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004803 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004804 return transceiver;
4805 }
4806 }
4807 RTC_NOTREACHED();
4808 return nullptr;
4809}
4810
4811// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4812// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004813bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004814 switch (type) {
4815 case cricket::MEDIA_TYPE_AUDIO:
4816 return !GetAudioTransceiver()->internal()->senders().empty();
4817 case cricket::MEDIA_TYPE_VIDEO:
4818 return !GetVideoTransceiver()->internal()->senders().empty();
4819 case cricket::MEDIA_TYPE_DATA:
4820 return false;
4821 }
4822 RTC_NOTREACHED();
4823 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004824}
4825
Steve Anton4171afb2017-11-20 10:20:22 -08004826rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4827PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4828 for (auto transceiver : transceivers_) {
4829 for (auto sender : transceiver->internal()->senders()) {
4830 if (sender->track() == track) {
4831 return sender;
4832 }
4833 }
4834 }
4835 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004836}
4837
Steve Anton4171afb2017-11-20 10:20:22 -08004838rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4839PeerConnection::FindSenderById(const std::string& sender_id) const {
4840 for (auto transceiver : transceivers_) {
4841 for (auto sender : transceiver->internal()->senders()) {
4842 if (sender->id() == sender_id) {
4843 return sender;
4844 }
4845 }
4846 }
4847 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004848}
4849
Steve Anton4171afb2017-11-20 10:20:22 -08004850rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4851PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4852 for (auto transceiver : transceivers_) {
4853 for (auto receiver : transceiver->internal()->receivers()) {
4854 if (receiver->id() == receiver_id) {
4855 return receiver;
4856 }
4857 }
4858 }
4859 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004860}
4861
Steve Anton4171afb2017-11-20 10:20:22 -08004862std::vector<PeerConnection::RtpSenderInfo>*
4863PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4864 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4865 media_type == cricket::MEDIA_TYPE_VIDEO);
4866 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4867 ? &remote_audio_sender_infos_
4868 : &remote_video_sender_infos_;
4869}
4870
4871std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004872 cricket::MediaType media_type) {
4873 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4874 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004875 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4876 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004877}
4878
Steve Anton4171afb2017-11-20 10:20:22 -08004879const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4880 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004881 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004882 const std::string sender_id) const {
4883 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004884 if (sender_info.stream_id == stream_id &&
4885 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004886 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004887 }
4888 }
4889 return nullptr;
4890}
4891
4892DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4893 for (const auto& channel : sctp_data_channels_) {
4894 if (channel->id() == sid) {
4895 return channel;
4896 }
4897 }
4898 return nullptr;
4899}
4900
deadbeef91dd5672016-05-18 16:55:30 -07004901bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004902 const cricket::ServerAddresses& stun_servers,
4903 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004904 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004905 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004906 // To handle both internal and externally created port allocator, we will
4907 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004908 port_allocator_flags_ = port_allocator_->flags();
4909 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4910 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4911 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004912 // If the disable-IPv6 flag was specified, we'll not override it
4913 // by experiment.
4914 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004915 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004916 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4917 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004918 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004919 }
4920
zhihuangb09b3f92017-03-07 14:40:51 -08004921 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004922 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004923 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004924 }
4925
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004926 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004927 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004928 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004929 }
4930
honghaiz60347052016-05-31 18:29:12 -07004931 if (configuration.candidate_network_policy ==
4932 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004933 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004934 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004935 }
4936
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004937 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004938 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004939 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4940 }
4941
Qingsi Wanga2d60672018-04-11 16:57:45 -07004942 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004943 // No step delay is used while allocating ports.
4944 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4945 port_allocator_->set_candidate_filter(
4946 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004947 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004948
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004949 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004950 for (auto& turn_server : turn_servers_copy) {
4951 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004952 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004953 // Call this last since it may create pooled allocator sessions using the
4954 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004955 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004956 stun_servers, std::move(turn_servers_copy),
4957 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4958 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004959 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004960 return true;
4961}
4962
deadbeef91dd5672016-05-18 16:55:30 -07004963bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004964 const cricket::ServerAddresses& stun_servers,
4965 const std::vector<cricket::RelayServerConfig>& turn_servers,
4966 IceTransportsType type,
4967 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004968 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004969 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004970 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004971 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004972 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004973 // According to JSEP, after setLocalDescription, changing the candidate pool
4974 // size is not allowed, and changing the set of ICE servers will not result
4975 // in new candidates being gathered.
4976 if (local_description()) {
4977 port_allocator_->FreezeCandidatePool();
4978 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004979 // Add the custom tls turn servers if they exist.
4980 auto turn_servers_copy = turn_servers;
4981 for (auto& turn_server : turn_servers_copy) {
4982 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4983 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004984 // Call this last since it may create pooled allocator sessions using the
4985 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004986 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004987 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4988 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004989}
4990
Steve Antonba818672017-11-06 10:21:57 -08004991cricket::ChannelManager* PeerConnection::channel_manager() const {
4992 return factory_->channel_manager();
4993}
4994
Elad Alon99c3fe52017-10-13 16:29:40 +02004995bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004996 std::unique_ptr<RtcEventLogOutput> output,
4997 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004998 if (!event_log_) {
4999 return false;
5000 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005001 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005002}
5003
5004void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005005 if (event_log_) {
5006 event_log_->StopLogging();
5007 }
ivoc14d5dbe2016-07-04 07:06:55 -07005008}
nisseeaabdf62017-05-05 02:23:02 -07005009
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005010cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005011 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005012 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005013 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005014 if (channel && channel->content_name() == content_name) {
5015 return channel;
5016 }
Steve Anton75737c02017-11-06 10:37:17 -08005017 }
5018 if (rtp_data_channel() &&
5019 rtp_data_channel()->content_name() == content_name) {
5020 return rtp_data_channel();
5021 }
5022 return nullptr;
5023}
5024
5025bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005026 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005027 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005028 RTC_LOG(LS_INFO)
5029 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005030 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005031 return false;
5032 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005033 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005034 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005035 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005036 return false;
5037 }
5038
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005039 absl::optional<rtc::SSLRole> dtls_role;
5040 if (sctp_mid_) {
5041 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5042 } else if (is_caller_) {
5043 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5044 }
Zhi Huange830e682018-03-30 10:48:35 -07005045 if (dtls_role) {
5046 *role = *dtls_role;
5047 return true;
5048 }
5049 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005050}
5051
5052bool PeerConnection::GetSslRole(const std::string& content_name,
5053 rtc::SSLRole* role) {
5054 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005055 RTC_LOG(LS_INFO)
5056 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005057 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005058 return false;
5059 }
5060
Zhi Huange830e682018-03-30 10:48:35 -07005061 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5062 if (dtls_role) {
5063 *role = *dtls_role;
5064 return true;
5065 }
5066 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005067}
5068
Steve Antonf8470812017-12-04 10:46:21 -08005069void PeerConnection::SetSessionError(SessionError error,
5070 const std::string& error_desc) {
5071 RTC_DCHECK_RUN_ON(signaling_thread());
5072 if (error != session_error_) {
5073 session_error_ = error;
5074 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005075 }
5076}
5077
Zhi Huange830e682018-03-30 10:48:35 -07005078RTCError PeerConnection::UpdateSessionState(
5079 SdpType type,
5080 cricket::ContentSource source,
5081 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005082 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005083
5084 // If there's already a pending error then no state transition should happen.
5085 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005086 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005087
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005088 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005089 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005090 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005091 }
5092
5093 // Update the signaling state according to the specified state machine (see
5094 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005095 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005096 ChangeSignalingState(source == cricket::CS_LOCAL
5097 ? PeerConnectionInterface::kHaveLocalOffer
5098 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005099 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005100 ChangeSignalingState(source == cricket::CS_LOCAL
5101 ? PeerConnectionInterface::kHaveLocalPrAnswer
5102 : PeerConnectionInterface::kHaveRemotePrAnswer);
5103 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005104 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005105 ChangeSignalingState(PeerConnectionInterface::kStable);
5106 }
5107
5108 // Update internal objects according to the session description's media
5109 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005110 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005111 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005112 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005113 }
5114
Steve Anton8a006912017-12-04 15:25:56 -08005115 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005116}
5117
Steve Anton8a006912017-12-04 15:25:56 -08005118RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005119 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005120 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005121 const SessionDescriptionInterface* sdesc =
5122 (source == cricket::CS_LOCAL ? local_description()
5123 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005124 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005125
5126 // Push down the new SDP media section for each audio/video transceiver.
5127 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005128 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005129 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005130 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005131 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005132 continue;
5133 }
5134 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005135 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005136 if (!content_desc) {
5137 continue;
5138 }
5139 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005140 bool success = (source == cricket::CS_LOCAL)
5141 ? channel->SetLocalContent(content_desc, type, &error)
5142 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005143 if (!success) {
5144 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5145 }
5146 }
5147
5148 // If using the RtpDataChannel, push down the new SDP section for it too.
5149 if (rtp_data_channel_) {
5150 const ContentInfo* data_content =
5151 cricket::GetFirstDataContent(sdesc->description());
5152 if (data_content && !data_content->rejected) {
5153 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005154 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005155 if (data_desc) {
5156 std::string error;
5157 bool success =
5158 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005159 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005160 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005161 if (!success) {
5162 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5163 std::move(error));
5164 }
Steve Anton75737c02017-11-06 10:37:17 -08005165 }
5166 }
5167 }
Steve Antoned10bd92017-12-05 10:52:59 -08005168
Steve Anton75737c02017-11-06 10:37:17 -08005169 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5170 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5171 if (sctp_transport_ && local_description() && remote_description() &&
5172 cricket::GetFirstDataContent(local_description()->description()) &&
5173 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005174 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005175 RTC_FROM_HERE,
5176 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005177 if (!success) {
5178 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5179 "Failed to push down SCTP parameters.");
5180 }
Steve Anton75737c02017-11-06 10:37:17 -08005181 }
Steve Antoned10bd92017-12-05 10:52:59 -08005182
Steve Anton8a006912017-12-04 15:25:56 -08005183 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005184}
5185
5186bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5187 RTC_DCHECK(network_thread()->IsCurrent());
5188 RTC_DCHECK(local_description());
5189 RTC_DCHECK(remote_description());
5190 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5191 // When we support "max-message-size", that would also be pushed down here.
5192 return sctp_transport_->Start(
5193 GetSctpPort(local_description()->description()),
5194 GetSctpPort(remote_description()->description()));
5195}
5196
Steve Anton8a006912017-12-04 15:25:56 -08005197RTCError PeerConnection::PushdownTransportDescription(
5198 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005199 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005200 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005201
Zhi Huange830e682018-03-30 10:48:35 -07005202 if (source == cricket::CS_LOCAL) {
5203 const SessionDescriptionInterface* sdesc = local_description();
5204 RTC_DCHECK(sdesc);
5205 return transport_controller_->SetLocalDescription(type,
5206 sdesc->description());
5207 } else {
5208 const SessionDescriptionInterface* sdesc = remote_description();
5209 RTC_DCHECK(sdesc);
5210 return transport_controller_->SetRemoteDescription(type,
5211 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005212 }
Steve Anton75737c02017-11-06 10:37:17 -08005213}
5214
5215bool PeerConnection::GetTransportDescription(
5216 const SessionDescription* description,
5217 const std::string& content_name,
5218 cricket::TransportDescription* tdesc) {
5219 if (!description || !tdesc) {
5220 return false;
5221 }
5222 const TransportInfo* transport_info =
5223 description->GetTransportInfoByName(content_name);
5224 if (!transport_info) {
5225 return false;
5226 }
5227 *tdesc = transport_info->description;
5228 return true;
5229}
5230
Steve Anton75737c02017-11-06 10:37:17 -08005231cricket::IceConfig PeerConnection::ParseIceConfig(
5232 const PeerConnectionInterface::RTCConfiguration& config) const {
5233 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005234 switch (config.continual_gathering_policy) {
5235 case PeerConnectionInterface::GATHER_ONCE:
5236 gathering_policy = cricket::GATHER_ONCE;
5237 break;
5238 case PeerConnectionInterface::GATHER_CONTINUALLY:
5239 gathering_policy = cricket::GATHER_CONTINUALLY;
5240 break;
5241 default:
5242 RTC_NOTREACHED();
5243 gathering_policy = cricket::GATHER_ONCE;
5244 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005245
Steve Anton75737c02017-11-06 10:37:17 -08005246 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005247 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5248 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005249 ice_config.prioritize_most_likely_candidate_pairs =
5250 config.prioritize_most_likely_ice_candidate_pairs;
5251 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005252 RTCConfigurationToIceConfigOptionalInt(
5253 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005254 ice_config.continual_gathering_policy = gathering_policy;
5255 ice_config.presume_writable_when_fully_relayed =
5256 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005257 ice_config.ice_check_interval_strong_connectivity =
5258 config.ice_check_interval_strong_connectivity;
5259 ice_config.ice_check_interval_weak_connectivity =
5260 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005261 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005262 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5263 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005264 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005265 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005266 ice_config.regather_all_networks_interval_range =
5267 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005268 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005269 return ice_config;
5270}
5271
Steve Antona41959e2018-11-28 11:15:33 -08005272static absl::string_view GetTrackIdBySsrc(
5273 const SessionDescriptionInterface* session_description,
5274 uint32_t ssrc) {
5275 if (!session_description) {
5276 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005277 }
Steve Antona41959e2018-11-28 11:15:33 -08005278 for (const cricket::ContentInfo& content :
5279 session_description->description()->contents()) {
5280 const cricket::MediaContentDescription& media =
5281 *content.media_description();
5282 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5283 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5284 const cricket::StreamParams* stream_params =
5285 cricket::GetStreamBySsrc(media.streams(), ssrc);
5286 if (stream_params) {
5287 return stream_params->id;
5288 }
5289 }
5290 }
5291 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005292}
5293
Steve Antona41959e2018-11-28 11:15:33 -08005294absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5295 return GetTrackIdBySsrc(local_description(), ssrc);
5296}
5297
5298absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5299 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005300}
5301
5302bool PeerConnection::SendData(const cricket::SendDataParams& params,
5303 const rtc::CopyOnWriteBuffer& payload,
5304 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005305 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5306 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5307 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005308 return false;
5309 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005310 if (media_transport_) {
5311 SendDataParams send_params;
5312 send_params.type = ToWebrtcDataMessageType(params.type);
5313 send_params.ordered = params.ordered;
5314 if (params.max_rtx_count >= 0) {
5315 send_params.max_rtx_count = params.max_rtx_count;
5316 } else if (params.max_rtx_ms >= 0) {
5317 send_params.max_rtx_ms = params.max_rtx_ms;
5318 }
5319 return media_transport_->SendData(params.sid, send_params, payload).ok();
5320 }
Steve Anton75737c02017-11-06 10:37:17 -08005321 return rtp_data_channel_
5322 ? rtp_data_channel_->SendData(params, payload, result)
5323 : network_thread()->Invoke<bool>(
5324 RTC_FROM_HERE,
5325 Bind(&cricket::SctpTransportInternal::SendData,
5326 sctp_transport_.get(), params, payload, result));
5327}
5328
5329bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005330 RTC_DCHECK_RUN_ON(signaling_thread());
5331 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005332 // Don't log an error here, because DataChannels are expected to call
5333 // ConnectDataChannel in this state. It's the only way to initially tell
5334 // whether or not the underlying transport is ready.
5335 return false;
5336 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005337 if (media_transport_) {
5338 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5339 &DataChannel::OnChannelReady);
5340 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5341 &DataChannel::OnDataReceived);
5342 SignalMediaTransportChannelClosing_s.connect(
5343 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5344 SignalMediaTransportChannelClosed_s.connect(
5345 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5346 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005347 rtp_data_channel_->SignalReadyToSendData.connect(
5348 webrtc_data_channel, &DataChannel::OnChannelReady);
5349 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5350 &DataChannel::OnDataReceived);
5351 } else {
5352 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5353 &DataChannel::OnChannelReady);
5354 SignalSctpDataReceived.connect(webrtc_data_channel,
5355 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005356 SignalSctpClosingProcedureStartedRemotely.connect(
5357 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5358 SignalSctpClosingProcedureComplete.connect(
5359 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005360 }
5361 return true;
5362}
5363
5364void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005365 RTC_DCHECK_RUN_ON(signaling_thread());
5366 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005367 RTC_LOG(LS_ERROR)
5368 << "DisconnectDataChannel called when rtp_data_channel_ and "
5369 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005370 return;
5371 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005372 if (media_transport_) {
5373 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5374 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5375 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5376 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5377 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005378 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5379 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5380 } else {
5381 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5382 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005383 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5384 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005385 }
5386}
5387
5388void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005389 if (media_transport_) {
5390 // No-op. Media transport does not need to add streams.
5391 return;
5392 }
Steve Anton75737c02017-11-06 10:37:17 -08005393 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005394 RTC_LOG(LS_ERROR)
5395 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005396 return;
5397 }
5398 network_thread()->Invoke<void>(
5399 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5400 sctp_transport_.get(), sid));
5401}
5402
5403void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005404 if (media_transport_) {
5405 media_transport_->CloseChannel(sid);
5406 return;
5407 }
Steve Anton75737c02017-11-06 10:37:17 -08005408 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005409 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005410 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005411 return;
5412 }
5413 network_thread()->Invoke<void>(
5414 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5415 sctp_transport_.get(), sid));
5416}
5417
5418bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005419 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005420 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005421 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005422 sctp_ready_to_send_data_;
5423}
5424
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005425void PeerConnection::OnDataReceived(int channel_id,
5426 DataMessageType type,
5427 const rtc::CopyOnWriteBuffer& buffer) {
5428 cricket::ReceiveDataParams params;
5429 params.sid = channel_id;
5430 params.type = ToCricketDataMessageType(type);
5431 media_transport_invoker_->AsyncInvoke<void>(
5432 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5433 RTC_DCHECK_RUN_ON(signaling_thread());
5434 if (!HandleOpenMessage_s(params, buffer)) {
5435 SignalMediaTransportReceivedData_s(params, buffer);
5436 }
5437 });
5438}
5439
5440void PeerConnection::OnChannelClosing(int channel_id) {
5441 media_transport_invoker_->AsyncInvoke<void>(
5442 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5443 RTC_DCHECK_RUN_ON(signaling_thread());
5444 SignalMediaTransportChannelClosing_s(channel_id);
5445 });
5446}
5447
5448void PeerConnection::OnChannelClosed(int channel_id) {
5449 media_transport_invoker_->AsyncInvoke<void>(
5450 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5451 RTC_DCHECK_RUN_ON(signaling_thread());
5452 SignalMediaTransportChannelClosed_s(channel_id);
5453 });
5454}
5455
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005456absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005457 if (sctp_mid_ && transport_controller_) {
5458 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5459 if (dtls_transport) {
5460 return dtls_transport->transport_name();
5461 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005462 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005463 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005464 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005465}
5466
Qingsi Wang72a43a12018-02-20 16:03:18 -08005467cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5468 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005469 network_thread()->Invoke<void>(
5470 RTC_FROM_HERE,
5471 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5472 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005473 return candidate_states_list;
5474}
5475
Steve Anton5dfde182018-02-06 10:34:40 -08005476std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5477 const {
5478 std::map<std::string, std::string> transport_names_by_mid;
5479 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005480 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005481 if (channel) {
5482 transport_names_by_mid[channel->content_name()] =
5483 channel->transport_name();
5484 }
Steve Anton75737c02017-11-06 10:37:17 -08005485 }
Steve Anton5dfde182018-02-06 10:34:40 -08005486 if (rtp_data_channel_) {
5487 transport_names_by_mid[rtp_data_channel_->content_name()] =
5488 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005489 }
5490 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005491 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005492 RTC_DCHECK(transport_name);
5493 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005494 }
Steve Anton5dfde182018-02-06 10:34:40 -08005495 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005496}
5497
Steve Anton5dfde182018-02-06 10:34:40 -08005498std::map<std::string, cricket::TransportStats>
5499PeerConnection::GetTransportStatsByNames(
5500 const std::set<std::string>& transport_names) {
5501 if (!network_thread()->IsCurrent()) {
5502 return network_thread()
5503 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5504 RTC_FROM_HERE,
5505 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005506 }
Steve Anton5dfde182018-02-06 10:34:40 -08005507 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5508 for (const std::string& transport_name : transport_names) {
5509 cricket::TransportStats transport_stats;
5510 bool success =
5511 transport_controller_->GetStats(transport_name, &transport_stats);
5512 if (success) {
5513 transport_stats_by_name[transport_name] = std::move(transport_stats);
5514 } else {
5515 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5516 << transport_name;
5517 }
5518 }
5519 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005520}
5521
5522bool PeerConnection::GetLocalCertificate(
5523 const std::string& transport_name,
5524 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005525 if (!certificate) {
5526 return false;
5527 }
5528 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5529 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005530}
5531
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005532std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005533 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005534 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005535}
5536
5537cricket::DataChannelType PeerConnection::data_channel_type() const {
5538 return data_channel_type_;
5539}
5540
5541bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5542 return pending_ice_restarts_.find(content_name) !=
5543 pending_ice_restarts_.end();
5544}
5545
Steve Anton75737c02017-11-06 10:37:17 -08005546bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5547 return transport_controller_->NeedsIceRestart(content_name);
5548}
5549
5550void PeerConnection::OnCertificateReady(
5551 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5552 transport_controller_->SetLocalCertificate(certificate);
5553}
5554
5555void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005556 SetSessionError(SessionError::kTransport,
5557 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005558}
5559
Alex Loiko9289eda2018-11-23 16:18:59 +00005560void PeerConnection::OnTransportControllerConnectionState(
5561 cricket::IceConnectionState state) {
5562 switch (state) {
5563 case cricket::kIceConnectionConnecting:
5564 // If the current state is Connected or Completed, then there were
5565 // writable channels but now there are not, so the next state must
5566 // be Disconnected.
5567 // kIceConnectionConnecting is currently used as the default,
5568 // un-connected state by the TransportController, so its only use is
5569 // detecting disconnections.
5570 if (ice_connection_state_ ==
5571 PeerConnectionInterface::kIceConnectionConnected ||
5572 ice_connection_state_ ==
5573 PeerConnectionInterface::kIceConnectionCompleted) {
5574 SetIceConnectionState(
5575 PeerConnectionInterface::kIceConnectionDisconnected);
5576 }
5577 break;
5578 case cricket::kIceConnectionFailed:
5579 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5580 break;
5581 case cricket::kIceConnectionConnected:
5582 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5583 "all transports are writable.";
5584 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5585 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5586 break;
5587 case cricket::kIceConnectionCompleted:
5588 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5589 "all transports are complete.";
5590 if (ice_connection_state_ !=
5591 PeerConnectionInterface::kIceConnectionConnected) {
5592 // If jumping directly from "checking" to "connected",
5593 // signal "connected" first.
5594 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5595 }
5596 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5597 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5598 ReportTransportStats();
5599 break;
5600 default:
5601 RTC_NOTREACHED();
5602 }
5603}
5604
Steve Anton75737c02017-11-06 10:37:17 -08005605void PeerConnection::OnTransportControllerCandidatesGathered(
5606 const std::string& transport_name,
5607 const cricket::Candidates& candidates) {
5608 RTC_DCHECK(signaling_thread()->IsCurrent());
5609 int sdp_mline_index;
5610 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005611 RTC_LOG(LS_ERROR)
5612 << "OnTransportControllerCandidatesGathered: content name "
5613 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005614 return;
5615 }
5616
5617 for (cricket::Candidates::const_iterator citer = candidates.begin();
5618 citer != candidates.end(); ++citer) {
5619 // Use transport_name as the candidate media id.
5620 std::unique_ptr<JsepIceCandidate> candidate(
5621 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5622 if (local_description()) {
5623 mutable_local_description()->AddCandidate(candidate.get());
5624 }
5625 OnIceCandidate(std::move(candidate));
5626 }
5627}
5628
5629void PeerConnection::OnTransportControllerCandidatesRemoved(
5630 const std::vector<cricket::Candidate>& candidates) {
5631 RTC_DCHECK(signaling_thread()->IsCurrent());
5632 // Sanity check.
5633 for (const cricket::Candidate& candidate : candidates) {
5634 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005635 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005636 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005637 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005638 return;
5639 }
5640 }
5641
5642 if (local_description()) {
5643 mutable_local_description()->RemoveCandidates(candidates);
5644 }
5645 OnIceCandidatesRemoved(candidates);
5646}
5647
5648void PeerConnection::OnTransportControllerDtlsHandshakeError(
5649 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005650 RTC_HISTOGRAM_ENUMERATION(
5651 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5652 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005653}
5654
Steve Antoned10bd92017-12-05 10:52:59 -08005655void PeerConnection::EnableSending() {
5656 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005657 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005658 if (channel && !channel->enabled()) {
5659 channel->Enable(true);
5660 }
Steve Anton75737c02017-11-06 10:37:17 -08005661 }
5662
Steve Anton4171afb2017-11-20 10:20:22 -08005663 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005664 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005665 }
Steve Anton75737c02017-11-06 10:37:17 -08005666}
5667
5668// Returns the media index for a local ice candidate given the content name.
5669bool PeerConnection::GetLocalCandidateMediaIndex(
5670 const std::string& content_name,
5671 int* sdp_mline_index) {
5672 if (!local_description() || !sdp_mline_index) {
5673 return false;
5674 }
5675
5676 bool content_found = false;
5677 const ContentInfos& contents = local_description()->description()->contents();
5678 for (size_t index = 0; index < contents.size(); ++index) {
5679 if (contents[index].name == content_name) {
5680 *sdp_mline_index = static_cast<int>(index);
5681 content_found = true;
5682 break;
5683 }
5684 }
5685 return content_found;
5686}
5687
5688bool PeerConnection::UseCandidatesInSessionDescription(
5689 const SessionDescriptionInterface* remote_desc) {
5690 if (!remote_desc) {
5691 return true;
5692 }
5693 bool ret = true;
5694
5695 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5696 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5697 for (size_t n = 0; n < candidates->count(); ++n) {
5698 const IceCandidateInterface* candidate = candidates->at(n);
5699 bool valid = false;
5700 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5701 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005702 RTC_LOG(LS_INFO)
5703 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005704 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005705 }
5706 continue;
5707 }
5708 ret = UseCandidate(candidate);
5709 if (!ret) {
5710 break;
5711 }
5712 }
5713 }
5714 return ret;
5715}
5716
5717bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5718 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5719 size_t remote_content_size =
5720 remote_description()->description()->contents().size();
5721 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005722 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005723 return false;
5724 }
5725
5726 cricket::ContentInfo content =
5727 remote_description()->description()->contents()[mediacontent_index];
5728 std::vector<cricket::Candidate> candidates;
5729 candidates.push_back(candidate->candidate());
5730 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005731 RTCError error =
5732 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005733 if (error.ok()) {
5734 // Candidates successfully submitted for checking.
5735 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5736 ice_connection_state_ ==
5737 PeerConnectionInterface::kIceConnectionDisconnected) {
5738 // If state is New, then the session has just gotten its first remote ICE
5739 // candidates, so go to Checking.
5740 // If state is Disconnected, the session is re-using old candidates or
5741 // receiving additional ones, so go to Checking.
5742 // If state is Connected, stay Connected.
5743 // TODO(bemasc): If state is Connected, and the new candidates are for a
5744 // newly added transport, then the state actually _should_ move to
5745 // checking. Add a way to distinguish that case.
5746 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5747 }
5748 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005749 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005750 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005751 }
5752 return true;
5753}
5754
5755void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005756 // Destroy video channel first since it may have a pointer to the
5757 // voice channel.
5758 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005759 if (!video_info || video_info->rejected) {
5760 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005761 }
5762
Steve Anton6fec8802017-12-04 10:37:29 -08005763 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5764 if (!audio_info || audio_info->rejected) {
5765 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005766 }
5767
5768 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5769 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005770 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005771 }
5772}
5773
Steve Antondcc3c022017-12-22 16:02:54 -08005774RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5775 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005776 const cricket::ContentGroup* bundle_group = nullptr;
5777 if (configuration_.bundle_policy ==
5778 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005779 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005780 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005781 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5782 "max-bundle configured but session description "
5783 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005784 }
5785 }
Steve Antondcc3c022017-12-22 16:02:54 -08005786 return std::move(bundle_group);
5787}
5788
5789RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005790 // Creating the media channels. Transports should already have been created
5791 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005792 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005793 if (voice && !voice->rejected &&
5794 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005795 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005796 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005797 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5798 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005799 }
5800 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5801 }
5802
Steve Antondcc3c022017-12-22 16:02:54 -08005803 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005804 if (video && !video->rejected &&
5805 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005806 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005807 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005808 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5809 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005810 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005811 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005812 }
5813
Steve Antondcc3c022017-12-22 16:02:54 -08005814 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005815 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005816 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005817 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005818 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5819 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005820 }
5821 }
5822
Steve Anton8a006912017-12-04 15:25:56 -08005823 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005824}
5825
Steve Anton4171afb2017-11-20 10:20:22 -08005826// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005827cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005828 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005829 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005830 MediaTransportInterface* media_transport = nullptr;
5831 if (configuration_.use_media_transport) {
5832 media_transport = GetMediaTransport(mid);
5833 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005834
Steve Anton75737c02017-11-06 10:37:17 -08005835 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005836 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005837 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5838 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005839 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005840 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005841 }
Steve Anton75737c02017-11-06 10:37:17 -08005842 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5843 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005844 voice_channel->SignalSentPacket.connect(this,
5845 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005846 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005847
Steve Antoneda6ccd2017-12-04 10:21:55 -08005848 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005849}
5850
Steve Anton4171afb2017-11-20 10:20:22 -08005851// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005852cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005853 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005854 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5855
5856 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005857 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005858 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005859 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5860 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005861 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005862 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005863 }
Steve Anton75737c02017-11-06 10:37:17 -08005864 video_channel->SignalDtlsSrtpSetupFailure.connect(
5865 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005866 video_channel->SignalSentPacket.connect(this,
5867 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005868 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005869
Steve Antoneda6ccd2017-12-04 10:21:55 -08005870 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005871}
5872
Zhi Huange830e682018-03-30 10:48:35 -07005873bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005874 switch (data_channel_type_) {
5875 case cricket::DCT_MEDIA_TRANSPORT:
5876 if (network_thread()->Invoke<bool>(
5877 RTC_FROM_HERE,
5878 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5879 this, mid))) {
5880 for (const auto& channel : sctp_data_channels_) {
5881 channel->OnTransportChannelCreated();
5882 }
5883 return true;
5884 }
Steve Anton75737c02017-11-06 10:37:17 -08005885 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005886 case cricket::DCT_SCTP:
5887 if (!sctp_factory_) {
5888 RTC_LOG(LS_ERROR)
5889 << "Trying to create SCTP transport, but didn't compile with "
5890 "SCTP support (HAVE_SCTP)";
5891 return false;
5892 }
5893 if (!network_thread()->Invoke<bool>(
5894 RTC_FROM_HERE,
5895 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5896 return false;
5897 }
5898 for (const auto& channel : sctp_data_channels_) {
5899 channel->OnTransportChannelCreated();
5900 }
5901 return true;
5902 case cricket::DCT_RTP:
5903 default:
5904 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5905 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5906 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5907 SrtpRequired(), GetCryptoOptions());
5908 if (!rtp_data_channel_) {
5909 return false;
5910 }
5911 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5912 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5913 rtp_data_channel_->SignalSentPacket.connect(
5914 this, &PeerConnection::OnSentPacket_w);
5915 rtp_data_channel_->SetRtpTransport(rtp_transport);
5916 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005917 }
5918
Steve Anton75737c02017-11-06 10:37:17 -08005919 return true;
5920}
5921
5922Call::Stats PeerConnection::GetCallStats() {
5923 if (!worker_thread()->IsCurrent()) {
5924 return worker_thread()->Invoke<Call::Stats>(
5925 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5926 }
5927 if (call_) {
5928 return call_->GetStats();
5929 } else {
5930 return Call::Stats();
5931 }
5932}
5933
Zhi Huange830e682018-03-30 10:48:35 -07005934bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005935 RTC_DCHECK(network_thread()->IsCurrent());
5936 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005937 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005938 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005939 RTC_DCHECK(dtls_transport);
5940 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005941 RTC_DCHECK(sctp_transport_);
5942 sctp_invoker_.reset(new rtc::AsyncInvoker());
5943 sctp_transport_->SignalReadyToSendData.connect(
5944 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5945 sctp_transport_->SignalDataReceived.connect(
5946 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005947 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5948 // another thread. Would be nice if there was a helper class similar to
5949 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5950 // code.
5951 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5952 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5953 sctp_transport_->SignalClosingProcedureComplete.connect(
5954 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005955 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005956 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005957 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005958}
5959
5960void PeerConnection::DestroySctpTransport_n() {
5961 RTC_DCHECK(network_thread()->IsCurrent());
5962 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005963 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005964 sctp_invoker_.reset(nullptr);
5965 sctp_ready_to_send_data_ = false;
5966}
5967
5968void PeerConnection::OnSctpTransportReadyToSendData_n() {
5969 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5970 RTC_DCHECK(network_thread()->IsCurrent());
5971 // Note: Cannot use rtc::Bind here because it will grab a reference to
5972 // PeerConnection and potentially cause PeerConnection to live longer than
5973 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5974 // be destroyed before PeerConnection is destroyed, and at that point all
5975 // pending tasks will be cleared.
5976 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5977 OnSctpTransportReadyToSendData_s(true);
5978 });
5979}
5980
5981void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5982 RTC_DCHECK(signaling_thread()->IsCurrent());
5983 sctp_ready_to_send_data_ = ready;
5984 SignalSctpReadyToSendData(ready);
5985}
5986
5987void PeerConnection::OnSctpTransportDataReceived_n(
5988 const cricket::ReceiveDataParams& params,
5989 const rtc::CopyOnWriteBuffer& payload) {
5990 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5991 RTC_DCHECK(network_thread()->IsCurrent());
5992 // Note: Cannot use rtc::Bind here because it will grab a reference to
5993 // PeerConnection and potentially cause PeerConnection to live longer than
5994 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5995 // be destroyed before PeerConnection is destroyed, and at that point all
5996 // pending tasks will be cleared.
5997 sctp_invoker_->AsyncInvoke<void>(
5998 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5999 OnSctpTransportDataReceived_s(params, payload);
6000 });
6001}
6002
6003void PeerConnection::OnSctpTransportDataReceived_s(
6004 const cricket::ReceiveDataParams& params,
6005 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006006 RTC_DCHECK_RUN_ON(signaling_thread());
6007 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006008 SignalSctpDataReceived(params, payload);
6009 }
6010}
6011
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006012void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006013 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6014 RTC_DCHECK(network_thread()->IsCurrent());
6015 sctp_invoker_->AsyncInvoke<void>(
6016 RTC_FROM_HERE, signaling_thread(),
6017 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006018 &SignalSctpClosingProcedureStartedRemotely, sid));
6019}
6020
6021void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6022 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6023 RTC_DCHECK(network_thread()->IsCurrent());
6024 sctp_invoker_->AsyncInvoke<void>(
6025 RTC_FROM_HERE, signaling_thread(),
6026 rtc::Bind(&sigslot::signal1<int>::operator(),
6027 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006028}
6029
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006030bool PeerConnection::SetupMediaTransportForDataChannels_n(
6031 const std::string& mid) {
6032 media_transport_ = transport_controller_->GetMediaTransport(mid);
6033 if (!media_transport_) {
6034 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6035 return false;
6036 }
6037
6038 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6039 media_transport_->SetDataSink(this);
6040 media_transport_data_mid_ = mid;
6041 transport_controller_->SignalMediaTransportStateChanged.connect(
6042 this, &PeerConnection::OnMediaTransportStateChanged_n);
6043 // Check the initial state right away, in case transport is already writable.
6044 OnMediaTransportStateChanged_n();
6045 return true;
6046}
6047
6048void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6049 if (!media_transport_) {
6050 return;
6051 }
6052 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6053 media_transport_data_mid_.reset();
6054 media_transport_->SetDataSink(nullptr);
6055 media_transport_invoker_ = nullptr;
6056 media_transport_ = nullptr;
6057}
6058
6059void PeerConnection::OnMediaTransportStateChanged_n() {
6060 if (!media_transport_data_mid_ ||
6061 transport_controller_->GetMediaTransportState(
6062 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6063 return;
6064 }
6065 media_transport_invoker_->AsyncInvoke<void>(
6066 RTC_FROM_HERE, signaling_thread(), [this] {
6067 RTC_DCHECK_RUN_ON(signaling_thread());
6068 media_transport_ready_to_send_data_ = true;
6069 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6070 });
6071}
6072
Steve Anton75737c02017-11-06 10:37:17 -08006073// Returns false if bundle is enabled and rtcp_mux is disabled.
6074bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6075 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6076 if (!bundle_enabled)
6077 return true;
6078
6079 const cricket::ContentGroup* bundle_group =
6080 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6081 RTC_DCHECK(bundle_group != NULL);
6082
6083 const cricket::ContentInfos& contents = desc->contents();
6084 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6085 citer != contents.end(); ++citer) {
6086 const cricket::ContentInfo* content = (&*citer);
6087 RTC_DCHECK(content != NULL);
6088 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006089 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006090 if (!HasRtcpMuxEnabled(content))
6091 return false;
6092 }
6093 }
6094 // RTCP-MUX is enabled in all the contents.
6095 return true;
6096}
6097
6098bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006099 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006100}
6101
Steve Anton8a006912017-12-04 15:25:56 -08006102RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006103 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006104 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006105 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006106 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006107 }
6108
6109 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006110 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006111 }
6112
Steve Anton3828c062017-12-06 10:34:51 -08006113 SdpType type = sdesc->GetType();
6114 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6115 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006116 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006117 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006118 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006119 }
6120
6121 // Verify crypto settings.
6122 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006123 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6124 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006125 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006126 if (!crypto_error.ok()) {
6127 return crypto_error;
6128 }
Steve Anton75737c02017-11-06 10:37:17 -08006129 }
6130
6131 // Verify ice-ufrag and ice-pwd.
6132 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006133 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6134 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006135 }
6136
6137 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006138 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6139 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006140 }
6141
6142 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6143 // m-lines that do not rtcp-mux enabled.
6144
6145 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006146 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006147 // With an answer we want to compare the new answer session description with
6148 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006149 const cricket::SessionDescription* offer_desc =
6150 (source == cricket::CS_LOCAL) ? remote_description()->description()
6151 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006152 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6153 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6154 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006155 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6156 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006157 }
6158 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006159 // The re-offers should respect the order of m= sections in current
6160 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006161 // With a re-offer, either the current local or current remote descriptions
6162 // could be the most up to date, so we would like to check against both of
6163 // them if they exist. It could be the case that one of them has a 0 port
6164 // for a media section, but the other does not. This is important to check
6165 // against in the case that we are recycling an m= section.
6166 const cricket::SessionDescription* current_desc = nullptr;
6167 const cricket::SessionDescription* secondary_current_desc = nullptr;
6168 if (local_description()) {
6169 current_desc = local_description()->description();
6170 if (remote_description()) {
6171 secondary_current_desc = remote_description()->description();
6172 }
6173 } else if (remote_description()) {
6174 current_desc = remote_description()->description();
6175 }
Steve Anton75737c02017-11-06 10:37:17 -08006176 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006177 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6178 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006179 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6180 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006181 }
6182 }
6183
Steve Antonba42e992018-04-09 14:10:01 -07006184 if (IsUnifiedPlan()) {
6185 // Ensure that each audio and video media section has at most one
6186 // "StreamParams". This will return an error if receiving a session
6187 // description from a "Plan B" endpoint which adds multiple tracks of the
6188 // same type. With Unified Plan, there can only be at most one track per
6189 // media section.
6190 for (const ContentInfo& content : sdesc->description()->contents()) {
6191 const MediaContentDescription& desc = *content.description;
6192 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6193 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6194 desc.streams().size() > 1u) {
6195 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6196 "Media section has more than one track specified "
6197 "with a=ssrc lines which is not supported with "
6198 "Unified Plan.");
6199 }
6200 }
6201 }
6202
Steve Anton8a006912017-12-04 15:25:56 -08006203 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006204}
6205
Steve Anton3828c062017-12-06 10:34:51 -08006206bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006207 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006208 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006209 return (state == PeerConnectionInterface::kStable) ||
6210 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006211 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006212 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006213 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6214 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6215 }
6216}
6217
Steve Anton3828c062017-12-06 10:34:51 -08006218bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006219 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006220 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006221 return (state == PeerConnectionInterface::kStable) ||
6222 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006223 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006224 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006225 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6226 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6227 }
6228}
6229
Steve Antonf8470812017-12-04 10:46:21 -08006230const char* PeerConnection::SessionErrorToString(SessionError error) const {
6231 switch (error) {
6232 case SessionError::kNone:
6233 return "ERROR_NONE";
6234 case SessionError::kContent:
6235 return "ERROR_CONTENT";
6236 case SessionError::kTransport:
6237 return "ERROR_TRANSPORT";
6238 }
6239 RTC_NOTREACHED();
6240 return "";
6241}
6242
Steve Anton75737c02017-11-06 10:37:17 -08006243std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006244 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006245 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6246 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006247 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006248}
6249
Steve Anton8e20f172018-03-06 10:55:04 -08006250void PeerConnection::ReportSdpFormatReceived(
6251 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006252 int num_audio_mlines = 0;
6253 int num_video_mlines = 0;
6254 int num_audio_tracks = 0;
6255 int num_video_tracks = 0;
6256 for (const ContentInfo& content : remote_offer.description()->contents()) {
6257 cricket::MediaType media_type = content.media_description()->type();
6258 int num_tracks = std::max(
6259 1, static_cast<int>(content.media_description()->streams().size()));
6260 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6261 num_audio_mlines += 1;
6262 num_audio_tracks += num_tracks;
6263 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6264 num_video_mlines += 1;
6265 num_video_tracks += num_tracks;
6266 }
6267 }
6268 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6269 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6270 format = kSdpFormatReceivedComplexUnifiedPlan;
6271 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6272 format = kSdpFormatReceivedComplexPlanB;
6273 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6274 format = kSdpFormatReceivedSimple;
6275 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006276 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6277 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006278}
6279
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006280void PeerConnection::NoteUsageEvent(UsageEvent event) {
6281 RTC_DCHECK_RUN_ON(signaling_thread());
6282 usage_event_accumulator_ |= static_cast<int>(event);
6283}
6284
6285void PeerConnection::ReportUsagePattern() const {
6286 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006287 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6288 usage_event_accumulator_,
6289 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006290 const int bad_bits =
6291 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6292 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6293 const int good_bits =
6294 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6295 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6296 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6297 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6298 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006299 // If called after close(), we can't report, because observer may have
6300 // been deallocated, and therefore pointer is null. Write to log instead.
6301 if (observer_) {
6302 Observer()->OnInterestingUsage(usage_event_accumulator_);
6303 } else {
6304 RTC_LOG(LS_INFO) << "Interesting usage signature "
6305 << usage_event_accumulator_
6306 << " observed after observer shutdown";
6307 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006308 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006309}
6310
Steve Anton0ffaaa22018-02-23 10:31:30 -08006311void PeerConnection::ReportNegotiatedSdpSemantics(
6312 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006313 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006314 switch (answer.description()->msid_signaling()) {
6315 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006316 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006317 break;
6318 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006319 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006320 break;
6321 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006322 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006323 break;
6324 case cricket::kMsidSignalingMediaSection |
6325 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006326 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006327 break;
6328 default:
6329 RTC_NOTREACHED();
6330 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006331 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6332 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006333}
6334
Steve Anton75737c02017-11-06 10:37:17 -08006335// We need to check the local/remote description for the Transport instead of
6336// the session, because a new Transport added during renegotiation may have
6337// them unset while the session has them set from the previous negotiation.
6338// Not doing so may trigger the auto generation of transport description and
6339// mess up DTLS identity information, ICE credential, etc.
6340bool PeerConnection::ReadyToUseRemoteCandidate(
6341 const IceCandidateInterface* candidate,
6342 const SessionDescriptionInterface* remote_desc,
6343 bool* valid) {
6344 *valid = true;
6345
6346 const SessionDescriptionInterface* current_remote_desc =
6347 remote_desc ? remote_desc : remote_description();
6348
6349 if (!current_remote_desc) {
6350 return false;
6351 }
6352
6353 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6354 size_t remote_content_size =
6355 current_remote_desc->description()->contents().size();
6356 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006357 RTC_LOG(LS_ERROR)
6358 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6359 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006360
6361 *valid = false;
6362 return false;
6363 }
6364
6365 cricket::ContentInfo content =
6366 current_remote_desc->description()->contents()[mediacontent_index];
6367
6368 const std::string transport_name = GetTransportName(content.name);
6369 if (transport_name.empty()) {
6370 return false;
6371 }
Zhi Huange830e682018-03-30 10:48:35 -07006372 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006373}
6374
6375bool PeerConnection::SrtpRequired() const {
6376 return dtls_enabled_ ||
6377 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6378}
6379
6380void PeerConnection::OnTransportControllerGatheringState(
6381 cricket::IceGatheringState state) {
6382 RTC_DCHECK(signaling_thread()->IsCurrent());
6383 if (state == cricket::kIceGatheringGathering) {
6384 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6385 } else if (state == cricket::kIceGatheringComplete) {
6386 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6387 }
6388}
6389
6390void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006391 std::map<std::string, std::set<cricket::MediaType>>
6392 media_types_by_transport_name;
6393 for (auto transceiver : transceivers_) {
6394 if (transceiver->internal()->channel()) {
6395 const std::string& transport_name =
6396 transceiver->internal()->channel()->transport_name();
6397 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006398 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006399 }
Steve Anton75737c02017-11-06 10:37:17 -08006400 }
6401 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006402 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6403 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006404 }
Zhi Huange830e682018-03-30 10:48:35 -07006405
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006406 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006407 if (transport_name) {
6408 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006409 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006410 }
Zhi Huange830e682018-03-30 10:48:35 -07006411
Steve Antonc7b964c2018-02-01 14:39:45 -08006412 for (const auto& entry : media_types_by_transport_name) {
6413 const std::string& transport_name = entry.first;
6414 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006415 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006416 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006417 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006418 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006419 }
6420 }
6421}
6422// Walk through the ConnectionInfos to gather best connection usage
6423// for IPv4 and IPv6.
6424void PeerConnection::ReportBestConnectionState(
6425 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006426 for (const cricket::TransportChannelStats& channel_stats :
6427 stats.channel_stats) {
6428 for (const cricket::ConnectionInfo& connection_info :
6429 channel_stats.connection_infos) {
6430 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006431 continue;
6432 }
6433
Steve Antonc7b964c2018-02-01 14:39:45 -08006434 const cricket::Candidate& local = connection_info.local_candidate;
6435 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006436
6437 // Increment the counter for IceCandidatePairType.
6438 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6439 (local.type() == RELAY_PORT_TYPE &&
6440 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006441 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6442 GetIceCandidatePairCounter(local, remote),
6443 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006444 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006445 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6446 GetIceCandidatePairCounter(local, remote),
6447 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006448 } else {
6449 RTC_CHECK(0);
6450 }
Steve Anton75737c02017-11-06 10:37:17 -08006451
6452 // Increment the counter for IP type.
6453 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006454 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6455 kBestConnections_IPv4,
6456 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006457 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006458 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6459 kBestConnections_IPv6,
6460 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006461 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006462 RTC_CHECK(!local.address().hostname().empty() &&
6463 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006464 }
6465
6466 return;
6467 }
6468 }
6469}
6470
6471void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006472 const cricket::TransportStats& stats,
6473 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006474 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6475 return;
6476 }
6477
6478 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6479 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6480 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6481 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6482 return;
6483 }
6484
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006485 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6486 for (cricket::MediaType media_type : media_types) {
6487 switch (media_type) {
6488 case cricket::MEDIA_TYPE_AUDIO:
6489 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6490 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6491 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6492 break;
6493 case cricket::MEDIA_TYPE_VIDEO:
6494 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6495 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6496 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6497 break;
6498 case cricket::MEDIA_TYPE_DATA:
6499 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6500 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6501 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6502 break;
6503 default:
6504 RTC_NOTREACHED();
6505 continue;
6506 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006507 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006508 }
6509
6510 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6511 for (cricket::MediaType media_type : media_types) {
6512 switch (media_type) {
6513 case cricket::MEDIA_TYPE_AUDIO:
6514 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6515 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6516 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6517 break;
6518 case cricket::MEDIA_TYPE_VIDEO:
6519 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6520 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6521 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6522 break;
6523 case cricket::MEDIA_TYPE_DATA:
6524 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6525 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6526 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6527 break;
6528 default:
6529 RTC_NOTREACHED();
6530 continue;
6531 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006532 }
Steve Anton75737c02017-11-06 10:37:17 -08006533 }
6534}
6535
6536void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6537 RTC_DCHECK(worker_thread()->IsCurrent());
6538 RTC_DCHECK(call_);
6539 call_->OnSentPacket(sent_packet);
6540}
6541
6542const std::string PeerConnection::GetTransportName(
6543 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006544 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006545 if (channel) {
6546 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006547 }
Steve Anton6fec8802017-12-04 10:37:29 -08006548 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006549 RTC_DCHECK(sctp_mid_);
6550 if (content_name == *sctp_mid_) {
6551 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006552 }
6553 }
6554 // Return an empty string if failed to retrieve the transport name.
6555 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006556}
6557
Steve Anton6fec8802017-12-04 10:37:29 -08006558void PeerConnection::DestroyTransceiverChannel(
6559 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6560 transceiver) {
6561 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006562
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006563 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006564 if (channel) {
6565 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006566 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006567 }
6568}
6569
6570void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006571 if (rtp_data_channel_) {
6572 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006573 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006574 rtp_data_channel_ = nullptr;
6575 }
6576
6577 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6578 // grab a reference to this PeerConnection. If this is called from the
6579 // PeerConnection destructor, the RefCountedObject vtable will have already
6580 // been destroyed (since it is a subclass of PeerConnection) and using
6581 // rtc::Bind will cause "Pure virtual function called" error to appear.
6582
6583 if (sctp_transport_) {
6584 OnDataChannelDestroyed();
6585 network_thread()->Invoke<void>(RTC_FROM_HERE,
6586 [this] { DestroySctpTransport_n(); });
6587 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006588
6589 if (media_transport_) {
6590 OnDataChannelDestroyed();
6591 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6592 RTC_DCHECK_RUN_ON(network_thread());
6593 TeardownMediaTransportForDataChannels_n();
6594 });
6595 }
Steve Anton6fec8802017-12-04 10:37:29 -08006596}
6597
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006598void PeerConnection::DestroyChannelInterface(
6599 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006600 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006601 switch (channel->media_type()) {
6602 case cricket::MEDIA_TYPE_AUDIO:
6603 channel_manager()->DestroyVoiceChannel(
6604 static_cast<cricket::VoiceChannel*>(channel));
6605 break;
6606 case cricket::MEDIA_TYPE_VIDEO:
6607 channel_manager()->DestroyVideoChannel(
6608 static_cast<cricket::VideoChannel*>(channel));
6609 break;
6610 case cricket::MEDIA_TYPE_DATA:
6611 channel_manager()->DestroyRtpDataChannel(
6612 static_cast<cricket::RtpDataChannel*>(channel));
6613 break;
6614 default:
6615 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6616 break;
6617 }
Zhi Huange830e682018-03-30 10:48:35 -07006618}
Steve Anton6fec8802017-12-04 10:37:29 -08006619
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006620bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006621 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006622 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006623 cricket::DtlsTransportInternal* dtls_transport,
6624 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006625 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006626 auto base_channel = GetChannel(mid);
6627 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006628 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006629 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006630 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006631 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006632 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006633
6634 call_->MediaTransportChange(media_transport);
6635
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006636 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006637}
6638
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006639PeerConnectionObserver* PeerConnection::Observer() const {
6640 // In earlier production code, the pointer was not cleared on close,
6641 // which might have led to undefined behavior if the observer was not
6642 // deallocated, or strange crashes if it was.
6643 // We use CHECK in order to catch such behavior if it exists.
6644 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6645 RTC_CHECK(observer_);
6646 return observer_;
6647}
6648
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006649CryptoOptions PeerConnection::GetCryptoOptions() {
6650 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6651 // after it has been removed.
6652 return configuration_.crypto_options.has_value()
6653 ? *configuration_.crypto_options
6654 : factory_->options().crypto_options;
6655}
6656
Harald Alvestrand89061872018-01-02 14:08:34 +01006657void PeerConnection::ClearStatsCache() {
6658 if (stats_collector_) {
6659 stats_collector_->ClearCachedStatsReport();
6660 }
6661}
6662
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006663void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006664 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6665 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006666}
6667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006668} // namespace webrtc