blob: a70ab2e95ab2540bd08b29d405f264356e467fa8 [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 Anton06817cd2018-12-18 15:55:30 -0800652// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
653// and return a reference to it.
654// Generated MIDs should be no more than 3 bytes long to take up less space in
655// the RTP packet.
656const std::string& AllocateMid(std::set<std::string>* used_mids) {
657 RTC_DCHECK(used_mids);
658 // We're boring: just generate MIDs 0, 1, 2, ...
659 size_t i = 0;
660 std::set<std::string>::iterator it;
661 bool inserted;
662 do {
663 std::string mid = rtc::ToString(i++);
664 auto insert_result = used_mids->insert(mid);
665 it = insert_result.first;
666 inserted = insert_result.second;
667 } while (!inserted);
668 return *it;
669}
670
Steve Anton75737c02017-11-06 10:37:17 -0800671} // namespace
672
Henrik Boström31638672017-11-23 17:48:32 +0100673// Upon completion, posts a task to execute the callback of the
674// SetSessionDescriptionObserver asynchronously on the same thread. At this
675// point, the state of the peer connection might no longer reflect the effects
676// of the SetRemoteDescription operation, as the peer connection could have been
677// modified during the post.
678// TODO(hbos): Remove this class once we remove the version of
679// PeerConnectionInterface::SetRemoteDescription() that takes a
680// SetSessionDescriptionObserver as an argument.
681class PeerConnection::SetRemoteDescriptionObserverAdapter
682 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
683 public:
684 SetRemoteDescriptionObserverAdapter(
685 rtc::scoped_refptr<PeerConnection> pc,
686 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
687 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
688
689 // SetRemoteDescriptionObserverInterface implementation.
690 void OnSetRemoteDescriptionComplete(RTCError error) override {
691 if (error.ok())
692 pc_->PostSetSessionDescriptionSuccess(wrapper_);
693 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100694 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100695 }
696
697 private:
698 rtc::scoped_refptr<PeerConnection> pc_;
699 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
700};
701
deadbeef293e9262017-01-11 12:28:30 -0800702bool PeerConnectionInterface::RTCConfiguration::operator==(
703 const PeerConnectionInterface::RTCConfiguration& o) const {
704 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700705 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800706 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000707 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700708 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800709 BundlePolicy bundle_policy;
710 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700711 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
712 int ice_candidate_pool_size;
713 bool disable_ipv6;
714 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700715 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100716 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700717 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200718 absl::optional<int> screencast_min_bitrate;
719 absl::optional<bool> combined_audio_video_bwe;
720 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800721 TcpCandidatePolicy tcp_candidate_policy;
722 CandidateNetworkPolicy candidate_network_policy;
723 int audio_jitter_buffer_max_packets;
724 bool audio_jitter_buffer_fast_accelerate;
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100725 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 12:28:30 -0800726 int ice_connection_receiving_timeout;
727 int ice_backup_candidate_pair_ping_interval;
728 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800729 bool prioritize_most_likely_ice_candidate_pairs;
730 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800731 bool prune_turn_ports;
732 bool presume_writable_when_fully_relayed;
733 bool enable_ice_renomination;
734 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<int> ice_check_interval_strong_connectivity;
736 absl::optional<int> ice_check_interval_weak_connectivity;
737 absl::optional<int> ice_check_min_interval;
738 absl::optional<int> ice_unwritable_timeout;
739 absl::optional<int> ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800740 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200741 absl::optional<int> stun_candidate_keepalive_interval;
742 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200743 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800744 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200745 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700746 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700747 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700748 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700749 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100750 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800751 };
752 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
753 "Did you add something to RTCConfiguration and forget to "
754 "update operator==?");
755 return type == o.type && servers == o.servers &&
756 bundle_policy == o.bundle_policy &&
757 rtcp_mux_policy == o.rtcp_mux_policy &&
758 tcp_candidate_policy == o.tcp_candidate_policy &&
759 candidate_network_policy == o.candidate_network_policy &&
760 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
761 audio_jitter_buffer_fast_accelerate ==
762 o.audio_jitter_buffer_fast_accelerate &&
Jakob Ivarsson10403ae2018-11-27 15:45:20 +0100763 audio_jitter_buffer_min_delay_ms ==
764 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 12:28:30 -0800765 ice_connection_receiving_timeout ==
766 o.ice_connection_receiving_timeout &&
767 ice_backup_candidate_pair_ping_interval ==
768 o.ice_backup_candidate_pair_ping_interval &&
769 continual_gathering_policy == o.continual_gathering_policy &&
770 certificates == o.certificates &&
771 prioritize_most_likely_ice_candidate_pairs ==
772 o.prioritize_most_likely_ice_candidate_pairs &&
773 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800774 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700775 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100776 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800777 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800778 screencast_min_bitrate == o.screencast_min_bitrate &&
779 combined_audio_video_bwe == o.combined_audio_video_bwe &&
780 enable_dtls_srtp == o.enable_dtls_srtp &&
781 ice_candidate_pool_size == o.ice_candidate_pool_size &&
782 prune_turn_ports == o.prune_turn_ports &&
783 presume_writable_when_fully_relayed ==
784 o.presume_writable_when_fully_relayed &&
785 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800786 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800787 ice_check_interval_strong_connectivity ==
788 o.ice_check_interval_strong_connectivity &&
789 ice_check_interval_weak_connectivity ==
790 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700791 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700792 ice_unwritable_timeout == o.ice_unwritable_timeout &&
793 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-06 23:30:17 -0800794 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800795 stun_candidate_keepalive_interval ==
796 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200797 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800798 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800799 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700800 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700801 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700802 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700803 use_media_transport_for_data_channels ==
804 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100805 crypto_options == o.crypto_options &&
806 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800807}
808
809bool PeerConnectionInterface::RTCConfiguration::operator!=(
810 const PeerConnectionInterface::RTCConfiguration& o) const {
811 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800812}
813
zhihuang8f65cdf2016-05-06 18:40:30 -0700814// Generate a RTCP CNAME when a PeerConnection is created.
815std::string GenerateRtcpCname() {
816 std::string cname;
817 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100818 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800819 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700820 }
821 return cname;
822}
823
zhihuang1c378ed2017-08-17 14:10:50 -0700824bool ValidateOfferAnswerOptions(
825 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
826 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
827 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700828}
829
zhihuang1c378ed2017-08-17 14:10:50 -0700830// From |rtc_options|, fill parts of |session_options| shared by all generated
831// m= sections (in other words, nothing that involves a map/array).
832void ExtractSharedMediaSessionOptions(
833 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
834 cricket::MediaSessionOptions* session_options) {
835 session_options->vad_enabled = rtc_options.voice_activity_detection;
836 session_options->bundle_enabled = rtc_options.use_rtp_mux;
837}
zhihuanga77e6bb2017-08-14 18:17:48 -0700838
zhihuang38ede132017-06-15 12:52:32 -0700839PeerConnection::PeerConnection(PeerConnectionFactory* factory,
840 std::unique_ptr<RtcEventLog> event_log,
841 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000842 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700843 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700844 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700845 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700846 remote_streams_(StreamCollection::Create()),
847 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000848
849PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100850 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800851 RTC_DCHECK_RUN_ON(signaling_thread());
852
Steve Anton8af21862017-12-15 11:20:13 -0800853 // Need to stop transceivers before destroying the stats collector because
854 // AudioRtpSender has a reference to the StatsCollector it will update when
855 // stopping.
856 for (auto transceiver : transceivers_) {
857 transceiver->Stop();
858 }
Steve Anton4171afb2017-11-20 10:20:22 -0800859
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700860 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800861 if (stats_collector_) {
862 stats_collector_->WaitForPendingRequest();
863 stats_collector_ = nullptr;
864 }
Steve Anton75737c02017-11-06 10:37:17 -0800865
Steve Anton8af21862017-12-15 11:20:13 -0800866 // Don't destroy BaseChannels until after stats has been cleaned up so that
867 // the last stats request can still read from the channels.
868 DestroyAllChannels();
869
Mirko Bonadei675513b2017-11-09 11:09:25 +0100870 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800871
872 webrtc_session_desc_factory_.reset();
873 sctp_invoker_.reset();
874 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800875 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800876 transport_controller_.reset();
877
deadbeef91dd5672016-05-18 16:55:30 -0700878 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700879 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700880 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700881 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700882 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700883 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800884 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700885 event_log_.reset();
886 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000887}
888
Steve Anton8af21862017-12-15 11:20:13 -0800889void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800890 // Destroy video channels first since they may have a pointer to a voice
891 // channel.
892 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800893 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800894 DestroyTransceiverChannel(transceiver);
895 }
896 }
897 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800898 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800899 DestroyTransceiverChannel(transceiver);
900 }
901 }
902 DestroyDataChannel();
903}
904
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000906 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700907 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100908 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700909
910 RTCError config_error = ValidateConfiguration(configuration);
911 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100912 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700913 return false;
914 }
915
Benjamin Wrightcab58882018-05-02 15:12:47 -0700916 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100917 RTC_LOG(LS_ERROR)
918 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100919 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800920 return false;
921 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200922
Benjamin Wrightcab58882018-05-02 15:12:47 -0700923 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800924 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100925 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100926 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800927 return false;
928 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700929
Benjamin Wrightcab58882018-05-02 15:12:47 -0700930 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700931 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700932 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700933 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800934
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200935 cricket::ServerAddresses stun_servers;
936 std::vector<cricket::RelayServerConfig> turn_servers;
937
938 RTCErrorType parse_error =
939 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
940 if (parse_error != RTCErrorType::NONE) {
941 return false;
942 }
943
deadbeef91dd5672016-05-18 16:55:30 -0700944 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700945 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700946 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200947 RTC_FROM_HERE,
948 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
949 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000950 return false;
951 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200952 // If initialization was successful, note if STUN or TURN servers
953 // were supplied.
954 if (!stun_servers.empty()) {
955 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
956 }
957 if (!turn_servers.empty()) {
958 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
959 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000960
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700961 // Send information about IPv4/IPv6 status.
962 PeerConnectionAddressFamilyCounter address_family;
963 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
964 address_family = kPeerConnection_IPv6;
965 } else {
966 address_family = kPeerConnection_IPv4;
967 }
968 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
969 kPeerConnectionAddressFamilyCounter_Max);
970
Zhi Huange830e682018-03-30 10:48:35 -0700971 const PeerConnectionFactoryInterface::Options& options = factory_->options();
972
Steve Anton75737c02017-11-06 10:37:17 -0800973 // RFC 3264: The numeric value of the session id and version in the
974 // o line MUST be representable with a "64 bit signed integer".
975 // Due to this constraint session id |session_id_| is max limited to
976 // LLONG_MAX.
977 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700978 JsepTransportController::Config config;
979 config.redetermine_role_on_ice_restart =
980 configuration.redetermine_role_on_ice_restart;
981 config.ssl_max_version = factory_->options().ssl_max_version;
982 config.disable_encryption = options.disable_encryption;
983 config.bundle_policy = configuration.bundle_policy;
984 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700985 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
986 // stub.
987 config.crypto_options = configuration.crypto_options.has_value()
988 ? *configuration.crypto_options
989 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700990 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700991 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700992#if defined(ENABLE_EXTERNAL_AUTH)
993 config.enable_external_auth = true;
994#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700995 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700996
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700997 if (configuration.use_media_transport ||
998 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700999 if (!factory_->media_transport_factory()) {
1000 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -07001001 << "PeerConnecton is initialized with use_media_transport = true or "
1002 << "use_media_transport_for_data_channels = true "
1003 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -07001004 return false;
1005 }
1006
1007 config.media_transport_factory = factory_->media_transport_factory();
1008 }
1009
Zhi Huange830e682018-03-30 10:48:35 -07001010 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -07001011 signaling_thread(), network_thread(), port_allocator_.get(),
1012 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001013 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:59 +00001014 this, &PeerConnection::OnTransportControllerConnectionState);
1015 transport_controller_->SignalStandardizedIceConnectionState.connect(
1016 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001017 transport_controller_->SignalConnectionState.connect(
1018 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001019 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001020 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001021 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001022 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001023 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001024 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1025 transport_controller_->SignalDtlsHandshakeError.connect(
1026 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1027
1028 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001029
deadbeefab9b2d12015-10-14 11:33:11 -07001030 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001031 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001032
Steve Antonba818672017-11-06 10:21:57 -08001033 configuration_ = configuration;
1034
Steve Anton75737c02017-11-06 10:37:17 -08001035 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1036 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1037 if (!configuration.certificates.empty()) {
1038 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1039 // just picking the first one. The decision should be made based on the DTLS
1040 // handshake. The DTLS negotiations need to know about all certificates.
1041 certificate = configuration.certificates[0];
1042 }
1043
Steve Antond25da372017-11-06 14:50:29 -08001044 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001045
1046 if (options.disable_encryption) {
1047 dtls_enabled_ = false;
1048 } else {
1049 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001050 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001051 // |configuration| can override the default |dtls_enabled_| value.
1052 if (configuration.enable_dtls_srtp) {
1053 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1054 }
1055 }
1056
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001057 if (configuration.use_media_transport_for_data_channels) {
1058 if (configuration.enable_rtp_data_channel) {
1059 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1060 "use_media_transport_for_data_channels are "
1061 "incompatible and cannot both be set to true";
1062 return false;
1063 }
1064 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1065 } else if (configuration.enable_rtp_data_channel) {
1066 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1067 // set. It takes precendence over the disable_sctp_data_channels
1068 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001069 data_channel_type_ = cricket::DCT_RTP;
1070 } else {
1071 // DTLS has to be enabled to use SCTP.
1072 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1073 data_channel_type_ = cricket::DCT_SCTP;
1074 }
1075 }
1076
1077 video_options_.screencast_min_bitrate_kbps =
1078 configuration.screencast_min_bitrate;
1079 audio_options_.combined_audio_video_bwe =
1080 configuration.combined_audio_video_bwe;
1081
1082 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001083 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001084
1085 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001086 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001087
Jakob Ivarsson10403ae2018-11-27 15:45:20 +01001088 audio_options_.audio_jitter_buffer_min_delay_ms =
1089 configuration.audio_jitter_buffer_min_delay_ms;
1090
Steve Anton75737c02017-11-06 10:37:17 -08001091 // Whether the certificate generator/certificate is null or not determines
1092 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1093 // the right instructions by clearing the variables if needed.
1094 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001095 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001096 certificate = nullptr;
1097 } else if (certificate) {
1098 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001099 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001100 }
1101
1102 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1103 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001104 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001105 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1106 this, &PeerConnection::OnCertificateReady);
1107
1108 if (options.disable_encryption) {
1109 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1110 }
1111
1112 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001113 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-10 16:08:05 -08001114 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001115
Steve Anton4171afb2017-11-20 10:20:22 -08001116 // Add default audio/video transceivers for Plan B SDP.
1117 if (!IsUnifiedPlan()) {
1118 transceivers_.push_back(
1119 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1120 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1121 transceivers_.push_back(
1122 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1123 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1124 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001125 int delay_ms =
1126 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001127 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1128 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129 return true;
1130}
1131
Steve Anton038834f2017-07-14 15:59:59 -07001132RTCError PeerConnection::ValidateConfiguration(
1133 const RTCConfiguration& config) const {
1134 if (config.ice_regather_interval_range &&
1135 config.continual_gathering_policy == GATHER_ONCE) {
1136 return RTCError(RTCErrorType::INVALID_PARAMETER,
1137 "ice_regather_interval_range specified but continual "
1138 "gathering policy is GATHER_ONCE");
1139 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001140 auto result =
1141 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1142 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001143}
1144
Yves Gerey665174f2018-06-19 15:03:05 +02001145rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001146 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1147 "Plan SdpSemantics. Please use GetSenders "
1148 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001149 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001150}
1151
Yves Gerey665174f2018-06-19 15:03:05 +02001152rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001153 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1154 "Plan SdpSemantics. Please use GetReceivers "
1155 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001156 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001157}
1158
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001159bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001160 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1161 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001162 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001163 if (IsClosed()) {
1164 return false;
1165 }
deadbeefab9b2d12015-10-14 11:33:11 -07001166 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001167 return false;
1168 }
deadbeefab9b2d12015-10-14 11:33:11 -07001169
1170 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001171 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1172 observer->SignalAudioTrackAdded.connect(this,
1173 &PeerConnection::OnAudioTrackAdded);
1174 observer->SignalAudioTrackRemoved.connect(
1175 this, &PeerConnection::OnAudioTrackRemoved);
1176 observer->SignalVideoTrackAdded.connect(this,
1177 &PeerConnection::OnVideoTrackAdded);
1178 observer->SignalVideoTrackRemoved.connect(
1179 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001180 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001181
deadbeefab9b2d12015-10-14 11:33:11 -07001182 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001183 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001184 }
1185 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001186 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001187 }
1188
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001189 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001190 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 return true;
1192}
1193
1194void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001195 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1196 "Plan SdpSemantics. Please use RemoveTrack "
1197 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001198 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001199 if (!IsClosed()) {
1200 for (const auto& track : local_stream->GetAudioTracks()) {
1201 RemoveAudioTrack(track.get(), local_stream);
1202 }
1203 for (const auto& track : local_stream->GetVideoTracks()) {
1204 RemoveVideoTrack(track.get(), local_stream);
1205 }
deadbeefab9b2d12015-10-14 11:33:11 -07001206 }
deadbeefab9b2d12015-10-14 11:33:11 -07001207 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001208 stream_observers_.erase(
1209 std::remove_if(
1210 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001211 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001212 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001213 }),
1214 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001215
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216 if (IsClosed()) {
1217 return;
1218 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001219 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001220}
1221
Steve Anton2d6c76a2018-01-05 17:10:52 -08001222RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001223 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001224 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001225 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001226 if (!track) {
1227 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1228 }
1229 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1230 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1231 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1232 "Track has invalid kind: " + track->kind());
1233 }
Steve Antonf9381f02017-12-14 10:23:57 -08001234 if (IsClosed()) {
1235 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1236 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001237 }
Steve Anton4171afb2017-11-20 10:20:22 -08001238 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001239 LOG_AND_RETURN_ERROR(
1240 RTCErrorType::INVALID_PARAMETER,
1241 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001242 }
Steve Antonf9381f02017-12-14 10:23:57 -08001243 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001244 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1245 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001246 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001247 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001248 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001249 }
1250 return sender_or_error;
1251}
deadbeefe1f9d832016-01-14 15:35:42 -08001252
Steve Antonf9381f02017-12-14 10:23:57 -08001253RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1254PeerConnection::AddTrackPlanB(
1255 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001256 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001257 if (stream_ids.size() > 1u) {
1258 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1259 "AddTrack with more than one stream is not "
1260 "supported with Plan B semantics.");
1261 }
1262 std::vector<std::string> adjusted_stream_ids = stream_ids;
1263 if (adjusted_stream_ids.empty()) {
1264 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1265 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001266 cricket::MediaType media_type =
1267 (track->kind() == MediaStreamTrackInterface::kAudioKind
1268 ? cricket::MEDIA_TYPE_AUDIO
1269 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001270 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001271 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001272 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001273 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001274 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001275 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001276 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001277 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001278 if (sender_info) {
1279 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001280 }
Steve Antonf9381f02017-12-14 10:23:57 -08001281 } else {
1282 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001283 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001284 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001285 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001286 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001287 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001288 if (sender_info) {
1289 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001290 }
deadbeefe1f9d832016-01-14 15:35:42 -08001291 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001292 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001293}
deadbeefe1f9d832016-01-14 15:35:42 -08001294
Steve Antonf9381f02017-12-14 10:23:57 -08001295RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1296PeerConnection::AddTrackUnifiedPlan(
1297 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001298 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001299 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1300 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001301 RTC_LOG(LS_INFO) << "Reusing an existing "
1302 << cricket::MediaTypeToString(transceiver->media_type())
1303 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001304 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001305 transceiver->internal()->set_direction(
1306 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001307 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001308 transceiver->internal()->set_direction(
1309 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001310 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001311 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001312 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 } else {
1314 cricket::MediaType media_type =
1315 (track->kind() == MediaStreamTrackInterface::kAudioKind
1316 ? cricket::MEDIA_TYPE_AUDIO
1317 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001318 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1319 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001320 std::string sender_id = track->id();
1321 // Avoid creating a sender with an existing ID by generating a random ID.
1322 // This can happen if this is the second time AddTrack has created a sender
1323 // for this track.
1324 if (FindSenderById(sender_id)) {
1325 sender_id = rtc::CreateRandomUuid();
1326 }
Florent Castelli892acf02018-10-01 22:47:20 +02001327 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001328 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1329 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001330 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001331 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001332 }
Steve Antonf9381f02017-12-14 10:23:57 -08001333 return transceiver->sender();
1334}
1335
1336rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1337PeerConnection::FindFirstTransceiverForAddedTrack(
1338 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1339 RTC_DCHECK(track);
1340 for (auto transceiver : transceivers_) {
1341 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001342 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001343 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001344 !transceiver->internal()->has_ever_been_used_to_send() &&
1345 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001346 return transceiver;
1347 }
1348 }
1349 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001350}
1351
1352bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1353 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001354 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001355}
1356
Steve Anton24db5732018-07-23 10:27:33 -07001357RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001358 rtc::scoped_refptr<RtpSenderInterface> sender) {
1359 if (!sender) {
1360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1361 }
deadbeefe1f9d832016-01-14 15:35:42 -08001362 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1364 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001365 }
Steve Antonf9381f02017-12-14 10:23:57 -08001366 if (IsUnifiedPlan()) {
1367 auto transceiver = FindTransceiverBySender(sender);
1368 if (!transceiver || !sender->track()) {
1369 return RTCError::OK();
1370 }
1371 sender->SetTrack(nullptr);
1372 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001373 transceiver->internal()->set_direction(
1374 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001375 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001376 transceiver->internal()->set_direction(
1377 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001378 }
Steve Anton4171afb2017-11-20 10:20:22 -08001379 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001380 bool removed;
1381 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1382 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1383 } else {
1384 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1385 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1386 }
1387 if (!removed) {
1388 LOG_AND_RETURN_ERROR(
1389 RTCErrorType::INVALID_PARAMETER,
1390 "Couldn't find sender " + sender->id() + " to remove.");
1391 }
Steve Anton4171afb2017-11-20 10:20:22 -08001392 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001393 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001394 return RTCError::OK();
1395}
1396
1397rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1398PeerConnection::FindTransceiverBySender(
1399 rtc::scoped_refptr<RtpSenderInterface> sender) {
1400 for (auto transceiver : transceivers_) {
1401 if (transceiver->sender() == sender) {
1402 return transceiver;
1403 }
1404 }
1405 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001406}
1407
Steve Anton9158ef62017-11-27 13:01:52 -08001408RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1409PeerConnection::AddTransceiver(
1410 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1411 return AddTransceiver(track, RtpTransceiverInit());
1412}
1413
1414RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1415PeerConnection::AddTransceiver(
1416 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1417 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001418 RTC_CHECK(IsUnifiedPlan())
1419 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001420 if (!track) {
1421 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1422 }
1423 cricket::MediaType media_type;
1424 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1425 media_type = cricket::MEDIA_TYPE_AUDIO;
1426 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1427 media_type = cricket::MEDIA_TYPE_VIDEO;
1428 } else {
1429 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1430 "Track kind is not audio or video");
1431 }
1432 return AddTransceiver(media_type, track, init);
1433}
1434
1435RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1436PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1437 return AddTransceiver(media_type, RtpTransceiverInit());
1438}
1439
1440RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1441PeerConnection::AddTransceiver(cricket::MediaType media_type,
1442 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001443 RTC_CHECK(IsUnifiedPlan())
1444 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001445 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1446 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1447 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1448 "media type is not audio or video");
1449 }
1450 return AddTransceiver(media_type, nullptr, init);
1451}
1452
1453RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1454PeerConnection::AddTransceiver(
1455 cricket::MediaType media_type,
1456 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001457 const RtpTransceiverInit& init,
1458 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001459 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1460 media_type == cricket::MEDIA_TYPE_VIDEO));
1461 if (track) {
1462 RTC_DCHECK_EQ(media_type,
1463 (track->kind() == MediaStreamTrackInterface::kAudioKind
1464 ? cricket::MEDIA_TYPE_AUDIO
1465 : cricket::MEDIA_TYPE_VIDEO));
1466 }
1467
1468 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001469 if (init.send_encodings.size() > 1) {
1470 LOG_AND_RETURN_ERROR(
1471 RTCErrorType::UNSUPPORTED_PARAMETER,
1472 "Attempted to create an encoder with more than 1 encoding parameter.");
1473 }
1474
1475 for (const auto& encoding : init.send_encodings) {
1476 if (encoding.ssrc.has_value()) {
1477 LOG_AND_RETURN_ERROR(
1478 RTCErrorType::UNSUPPORTED_PARAMETER,
1479 "Attempted to set an unimplemented parameter of RtpParameters.");
1480 }
1481 }
1482
1483 RtpParameters parameters;
1484 parameters.encodings = init.send_encodings;
1485 if (UnimplementedRtpParameterHasValue(parameters)) {
1486 LOG_AND_RETURN_ERROR(
1487 RTCErrorType::UNSUPPORTED_PARAMETER,
1488 "Attempted to set an unimplemented parameter of RtpParameters.");
1489 }
Steve Anton9158ef62017-11-27 13:01:52 -08001490
Steve Anton3d954a62018-04-02 11:27:23 -07001491 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1492 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001493 // Set the sender ID equal to the track ID if the track is specified unless
1494 // that sender ID is already in use.
1495 std::string sender_id =
1496 (track && !FindSenderById(track->id()) ? track->id()
1497 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001498 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1499 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001500 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1501 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1502 transceiver->internal()->set_direction(init.direction);
1503
Steve Anton22da89f2018-01-25 13:58:07 -08001504 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001505 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001506 }
Steve Antonf9381f02017-12-14 10:23:57 -08001507
1508 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1509}
1510
Steve Anton02ee47c2018-01-10 16:26:06 -08001511rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1512PeerConnection::CreateSender(
1513 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001514 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001515 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001516 const std::vector<std::string>& stream_ids,
1517 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001518 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1520 RTC_DCHECK(!track ||
1521 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1522 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1523 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001524 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001525 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001526 } else {
1527 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1528 RTC_DCHECK(!track ||
1529 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1530 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001531 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001532 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001533 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001534 bool set_track_succeeded = sender->SetTrack(track);
1535 RTC_DCHECK(set_track_succeeded);
1536 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001537 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001538 return sender;
1539}
1540
1541rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1542PeerConnection::CreateReceiver(cricket::MediaType media_type,
1543 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001544 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1545 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001546 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001547 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001548 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1549 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001550 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001551 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001552 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001553 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001554 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1555 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001556 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001557 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001558 return receiver;
1559}
1560
1561rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1562PeerConnection::CreateAndAddTransceiver(
1563 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1564 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1565 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001566 // Ensure that the new sender does not have an ID that is already in use by
1567 // another sender.
1568 // Allow receiver IDs to conflict since those come from remote SDP (which
1569 // could be invalid, but should not cause a crash).
1570 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001571 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1572 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001573 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001574 transceiver->internal()->SignalNegotiationNeeded.connect(
1575 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001576 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001577}
1578
Steve Anton52d86772018-02-20 15:48:12 -08001579void PeerConnection::OnNegotiationNeeded() {
1580 RTC_DCHECK_RUN_ON(signaling_thread());
1581 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001582 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001583}
1584
deadbeeffac06552015-11-25 11:26:01 -08001585rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001586 const std::string& kind,
1587 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001588 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1589 "Plan SdpSemantics. Please use AddTransceiver "
1590 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001591 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001592 if (IsClosed()) {
1593 return nullptr;
1594 }
Steve Anton4171afb2017-11-20 10:20:22 -08001595
Seth Hampson5b4f0752018-04-02 16:31:36 -07001596 // Internally we need to have one stream with Plan B semantics, so we
1597 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001598 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001599 if (stream_id.empty()) {
1600 stream_ids.push_back(rtc::CreateRandomUuid());
1601 RTC_LOG(LS_INFO)
1602 << "No stream_id specified for sender. Generated stream ID: "
1603 << stream_ids[0];
1604 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001605 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001606 }
1607
Steve Anton4171afb2017-11-20 10:20:22 -08001608 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001609 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001610 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001611 auto* audio_sender = new AudioRtpSender(
1612 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001613 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001614 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001615 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001616 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001617 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001618 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001619 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001620 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001621 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001622 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001623 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001624 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001625 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001626 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001627 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001628 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001629
deadbeefe1f9d832016-01-14 15:35:42 -08001630 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001631}
1632
deadbeef70ab1a12015-09-28 16:53:55 -07001633std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1634 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001635 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001636 for (auto sender : GetSendersInternal()) {
1637 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001638 }
1639 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001640}
1641
Steve Anton4171afb2017-11-20 10:20:22 -08001642std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1643PeerConnection::GetSendersInternal() const {
1644 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1645 all_senders;
1646 for (auto transceiver : transceivers_) {
1647 auto senders = transceiver->internal()->senders();
1648 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1649 }
1650 return all_senders;
1651}
1652
deadbeef70ab1a12015-09-28 16:53:55 -07001653std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1654PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001655 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001656 for (const auto& receiver : GetReceiversInternal()) {
1657 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001658 }
1659 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001660}
1661
Steve Anton4171afb2017-11-20 10:20:22 -08001662std::vector<
1663 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1664PeerConnection::GetReceiversInternal() const {
1665 std::vector<
1666 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1667 all_receivers;
1668 for (auto transceiver : transceivers_) {
1669 auto receivers = transceiver->internal()->receivers();
1670 all_receivers.insert(all_receivers.end(), receivers.begin(),
1671 receivers.end());
1672 }
1673 return all_receivers;
1674}
1675
Steve Anton9158ef62017-11-27 13:01:52 -08001676std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1677PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001678 RTC_CHECK(IsUnifiedPlan())
1679 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001680 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1681 for (auto transceiver : transceivers_) {
1682 all_transceivers.push_back(transceiver);
1683 }
1684 return all_transceivers;
1685}
1686
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001688 MediaStreamTrackInterface* track,
1689 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001690 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001691 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001692 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001693 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001694 return false;
1695 }
1696
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001697 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001698 // The StatsCollector is used to tell if a track is valid because it may
1699 // remember tracks that the PeerConnection previously removed.
1700 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001701 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1702 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001703 return false;
1704 }
Steve Antonad182762018-09-05 20:22:40 +00001705 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1706 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001707 return true;
1708}
1709
hbos74e1a4f2016-09-15 23:33:01 -07001710void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001711 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001712 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001713 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001714 stats_collector_->GetStatsReport(callback);
1715}
1716
Henrik Boström1df1bf82018-03-20 13:24:20 +01001717void PeerConnection::GetStats(
1718 rtc::scoped_refptr<RtpSenderInterface> selector,
1719 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1720 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1721 RTC_DCHECK(callback);
1722 RTC_DCHECK(stats_collector_);
1723 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1724 if (selector) {
1725 for (const auto& proxy_transceiver : transceivers_) {
1726 for (const auto& proxy_sender :
1727 proxy_transceiver->internal()->senders()) {
1728 if (proxy_sender == selector) {
1729 internal_sender = proxy_sender->internal();
1730 break;
1731 }
1732 }
1733 if (internal_sender)
1734 break;
1735 }
1736 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001737 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001738 // belong to the PeerConnection (in Plan B, senders can be removed from the
1739 // PeerConnection). This means that "all the stats objects representing the
1740 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1741 // produces an empty stats report.
1742 stats_collector_->GetStatsReport(internal_sender, callback);
1743}
1744
1745void PeerConnection::GetStats(
1746 rtc::scoped_refptr<RtpReceiverInterface> selector,
1747 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1748 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1749 RTC_DCHECK(callback);
1750 RTC_DCHECK(stats_collector_);
1751 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1752 if (selector) {
1753 for (const auto& proxy_transceiver : transceivers_) {
1754 for (const auto& proxy_receiver :
1755 proxy_transceiver->internal()->receivers()) {
1756 if (proxy_receiver == selector) {
1757 internal_receiver = proxy_receiver->internal();
1758 break;
1759 }
1760 }
1761 if (internal_receiver)
1762 break;
1763 }
1764 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001765 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001766 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1767 // the PeerConnection). This means that "all the stats objects representing
1768 // the selector" is an empty set. Invoking GetStatsReport() with a null
1769 // selector produces an empty stats report.
1770 stats_collector_->GetStatsReport(internal_receiver, callback);
1771}
1772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1774 return signaling_state_;
1775}
1776
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001777PeerConnectionInterface::IceConnectionState
1778PeerConnection::ice_connection_state() {
1779 return ice_connection_state_;
1780}
1781
Alex Loiko9289eda2018-11-23 16:18:59 +00001782PeerConnectionInterface::IceConnectionState
1783PeerConnection::standardized_ice_connection_state() {
1784 return standardized_ice_connection_state_;
1785}
1786
Jonas Olsson635474e2018-10-18 15:58:17 +02001787PeerConnectionInterface::PeerConnectionState
1788PeerConnection::peer_connection_state() {
1789 return connection_state_;
1790}
1791
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001792PeerConnectionInterface::IceGatheringState
1793PeerConnection::ice_gathering_state() {
1794 return ice_gathering_state_;
1795}
1796
Yves Gerey665174f2018-06-19 15:03:05 +02001797rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001798 const std::string& label,
1799 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001800 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001801
deadbeefab9b2d12015-10-14 11:33:11 -07001802 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001803
kwibergd1fe2812016-04-27 06:47:29 -07001804 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001805 if (config) {
1806 internal_config.reset(new InternalDataChannelInit(*config));
1807 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001808 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001809 InternalCreateDataChannel(label, internal_config.get()));
1810 if (!channel.get()) {
1811 return nullptr;
1812 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001813
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001814 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1815 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001816 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001817 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001818 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001819 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001820 return DataChannelProxy::Create(signaling_thread(), channel.get());
1821}
1822
1823void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001824 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001825 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001826
nisse7ce109a2017-01-31 00:57:56 -08001827 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001828 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001829 return;
1830 }
deadbeefab9b2d12015-10-14 11:33:11 -07001831
Steve Anton8d3444d2017-10-20 15:30:51 -07001832 if (IsClosed()) {
1833 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001834 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001835 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001836 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001837 return;
1838 }
1839
zhihuang1c378ed2017-08-17 14:10:50 -07001840 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001841 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001842 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001843 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001844 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001845 return;
1846 }
1847
Steve Anton22da89f2018-01-25 13:58:07 -08001848 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1849 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1850 if (IsUnifiedPlan()) {
1851 RTCError error = HandleLegacyOfferOptions(options);
1852 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001853 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001854 return;
1855 }
1856 }
1857
zhihuang1c378ed2017-08-17 14:10:50 -07001858 cricket::MediaSessionOptions session_options;
1859 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001860 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001861}
1862
Steve Anton22da89f2018-01-25 13:58:07 -08001863RTCError PeerConnection::HandleLegacyOfferOptions(
1864 const RTCOfferAnswerOptions& options) {
1865 RTC_DCHECK(IsUnifiedPlan());
1866
1867 if (options.offer_to_receive_audio == 0) {
1868 RemoveRecvDirectionFromReceivingTransceiversOfType(
1869 cricket::MEDIA_TYPE_AUDIO);
1870 } else if (options.offer_to_receive_audio == 1) {
1871 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1872 } else if (options.offer_to_receive_audio > 1) {
1873 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1874 "offer_to_receive_audio > 1 is not supported.");
1875 }
1876
1877 if (options.offer_to_receive_video == 0) {
1878 RemoveRecvDirectionFromReceivingTransceiversOfType(
1879 cricket::MEDIA_TYPE_VIDEO);
1880 } else if (options.offer_to_receive_video == 1) {
1881 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1882 } else if (options.offer_to_receive_video > 1) {
1883 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1884 "offer_to_receive_video > 1 is not supported.");
1885 }
1886
1887 return RTCError::OK();
1888}
1889
1890void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1891 cricket::MediaType media_type) {
1892 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001893 RtpTransceiverDirection new_direction =
1894 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1895 if (new_direction != transceiver->direction()) {
1896 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1897 << " transceiver (MID="
1898 << transceiver->mid().value_or("<not set>") << ") from "
1899 << RtpTransceiverDirectionToString(
1900 transceiver->direction())
1901 << " to "
1902 << RtpTransceiverDirectionToString(new_direction)
1903 << " since CreateOffer specified offer_to_receive=0";
1904 transceiver->internal()->set_direction(new_direction);
1905 }
Steve Anton22da89f2018-01-25 13:58:07 -08001906 }
1907}
1908
1909void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1910 cricket::MediaType media_type) {
1911 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001912 RTC_LOG(LS_INFO)
1913 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1914 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001915 RtpTransceiverInit init;
1916 init.direction = RtpTransceiverDirection::kRecvOnly;
1917 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1918 }
1919}
1920
1921std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1922PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1923 std::vector<
1924 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1925 receiving_transceivers;
1926 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001927 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001928 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1929 receiving_transceivers.push_back(transceiver);
1930 }
1931 }
1932 return receiving_transceivers;
1933}
1934
htaa2a49d92016-03-04 02:51:39 -08001935void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1936 const RTCOfferAnswerOptions& options) {
1937 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001938 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001939 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001940 return;
1941 }
1942
Steve Antondffead82018-02-06 10:31:29 -08001943 if (!(signaling_state_ == kHaveRemoteOffer ||
1944 signaling_state_ == kHaveLocalPrAnswer)) {
1945 std::string error =
1946 "PeerConnection cannot create an answer in a state other than "
1947 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001948 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001949 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001950 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001951 return;
1952 }
1953
Steve Antondffead82018-02-06 10:31:29 -08001954 // The remote description should be set if we're in the right state.
1955 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001956
Steve Anton22da89f2018-01-25 13:58:07 -08001957 if (IsUnifiedPlan()) {
1958 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1959 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1960 "supported with Unified Plan semantics. Use the "
1961 "RtpTransceiver API instead.";
1962 }
1963 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1964 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1965 "supported with Unified Plan semantics. Use the "
1966 "RtpTransceiver API instead.";
1967 }
1968 }
1969
htaa2a49d92016-03-04 02:51:39 -08001970 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001971 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001972
Steve Antond25da372017-11-06 14:50:29 -08001973 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001974}
1975
1976void PeerConnection::SetLocalDescription(
1977 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001978 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001979 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001980
Steve Anton80dd7b52018-02-16 17:08:42 -08001981 // The SetLocalDescription contract is that we take ownership of the session
1982 // description regardless of the outcome, so wrap it in a unique_ptr right
1983 // away. Ideally, SetLocalDescription's signature will be changed to take the
1984 // description as a unique_ptr argument to formalize this agreement.
1985 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1986
nisse7ce109a2017-01-31 00:57:56 -08001987 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001988 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001989 return;
1990 }
Steve Anton8a006912017-12-04 15:25:56 -08001991
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001993 PostSetSessionDescriptionFailure(
1994 observer,
1995 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001996 return;
1997 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001998
Steve Anton80dd7b52018-02-16 17:08:42 -08001999 // If a session error has occurred the PeerConnection is in a possibly
2000 // inconsistent state so fail right away.
2001 if (session_error() != SessionError::kNone) {
2002 std::string error_message = GetSessionErrorMsg();
2003 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002004 PostSetSessionDescriptionFailure(
2005 observer,
2006 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002007 return;
2008 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002009
Steve Anton80dd7b52018-02-16 17:08:42 -08002010 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
2011 if (!error.ok()) {
2012 std::string error_message = GetSetDescriptionErrorMessage(
2013 cricket::CS_LOCAL, desc->GetType(), error);
2014 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002015 PostSetSessionDescriptionFailure(
2016 observer,
2017 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08002018 return;
2019 }
2020
2021 // Grab the description type before moving ownership to ApplyLocalDescription,
2022 // which may destroy it before returning.
2023 const SdpType type = desc->GetType();
2024
2025 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002026 // |desc| may be destroyed at this point.
2027
2028 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002029 // If ApplyLocalDescription fails, the PeerConnection could be in an
2030 // inconsistent state, so act conservatively here and set the session error
2031 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2032 SetSessionError(SessionError::kContent, error.message());
2033 std::string error_message =
2034 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2035 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002036 PostSetSessionDescriptionFailure(
2037 observer,
2038 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002039 return;
2040 }
Steve Anton8a006912017-12-04 15:25:56 -08002041 RTC_DCHECK(local_description());
2042
2043 PostSetSessionDescriptionSuccess(observer);
2044
Steve Antonad182762018-09-05 20:22:40 +00002045 // MaybeStartGathering needs to be called after posting
2046 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2047 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002048 transport_controller_->MaybeStartGathering();
2049
Steve Antona3a92c22017-12-07 10:27:41 -08002050 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002051 // TODO(deadbeef): We already had to hop to the network thread for
2052 // MaybeStartGathering...
2053 network_thread()->Invoke<void>(
2054 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2055 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002056 // Make UMA notes about what was agreed to.
2057 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002058 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002059 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002060}
2061
2062RTCError PeerConnection::ApplyLocalDescription(
2063 std::unique_ptr<SessionDescriptionInterface> desc) {
2064 RTC_DCHECK_RUN_ON(signaling_thread());
2065 RTC_DCHECK(desc);
2066
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002067 // Update stats here so that we have the most recent stats for tracks and
2068 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002069 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002070
Steve Antondcc3c022017-12-22 16:02:54 -08002071 // Take a reference to the old local description since it's used below to
2072 // compare against the new local description. When setting the new local
2073 // description, grab ownership of the replaced session description in case it
2074 // is the same as |old_local_description|, to keep it alive for the duration
2075 // of the method.
2076 const SessionDescriptionInterface* old_local_description =
2077 local_description();
2078 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002079 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002080 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002081 replaced_local_description = pending_local_description_
2082 ? std::move(pending_local_description_)
2083 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002084 current_local_description_ = std::move(desc);
2085 pending_local_description_ = nullptr;
2086 current_remote_description_ = std::move(pending_remote_description_);
2087 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002088 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002089 pending_local_description_ = std::move(desc);
2090 }
2091 // The session description to apply now must be accessed by
2092 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002093 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002094
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002095 if (!is_caller_) {
2096 if (remote_description()) {
2097 // Remote description was applied first, so this PC is the callee.
2098 is_caller_ = false;
2099 } else {
2100 // Local description is applied first, so this PC is the caller.
2101 is_caller_ = true;
2102 }
2103 }
2104
Zhi Huange830e682018-03-30 10:48:35 -07002105 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2106 if (!error.ok()) {
2107 return error;
2108 }
2109
Steve Antondcc3c022017-12-22 16:02:54 -08002110 if (IsUnifiedPlan()) {
2111 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002112 cricket::CS_LOCAL, *local_description(), old_local_description,
2113 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002114 if (!error.ok()) {
2115 return error;
2116 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002117 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2118 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002119 for (auto transceiver : transceivers_) {
2120 const ContentInfo* content =
2121 FindMediaSectionForTransceiver(transceiver, local_description());
2122 if (!content) {
2123 continue;
2124 }
2125 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002126 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2127 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002128 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002129 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2130 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2131 // "recvonly", process the removal of a remote track for the media
2132 // description, given transceiver, removeList, and muteTracks.
2133 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2134 (transceiver->internal()->fired_direction() &&
2135 RtpTransceiverDirectionHasRecv(
2136 *transceiver->internal()->fired_direction()))) {
2137 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2138 &removed_streams);
2139 }
2140 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2141 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002142 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002143 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002144 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002145 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002146 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002147 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002148 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002149 }
2150 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002151 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002152 }
2153 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002154 // Media channels will be created only when offer is set. These may use new
2155 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002156 if (type == SdpType::kOffer) {
2157 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2158 // description is applied. Restore back to old description.
2159 RTCError error = CreateChannels(*local_description()->description());
2160 if (!error.ok()) {
2161 return error;
2162 }
2163 }
Steve Antondcc3c022017-12-22 16:02:54 -08002164 // Remove unused channels if MediaContentDescription is rejected.
2165 RemoveUnusedChannels(local_description()->description());
2166 }
Steve Anton8a006912017-12-04 15:25:56 -08002167
Zhi Huange830e682018-03-30 10:48:35 -07002168 error = UpdateSessionState(type, cricket::CS_LOCAL,
2169 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002170 if (!error.ok()) {
2171 return error;
2172 }
Steve Antondcc3c022017-12-22 16:02:54 -08002173
Steve Anton8a006912017-12-04 15:25:56 -08002174 if (remote_description()) {
2175 // Now that we have a local description, we can push down remote candidates.
2176 UseCandidatesInSessionDescription(remote_description());
2177 }
2178
2179 pending_ice_restarts_.clear();
2180 if (session_error() != SessionError::kNone) {
2181 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2182 }
2183
deadbeefab9b2d12015-10-14 11:33:11 -07002184 // If setting the description decided our SSL role, allocate any necessary
2185 // SCTP sids.
2186 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002187 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002188 AllocateSctpSids(role);
2189 }
2190
Steve Antond3679212018-01-17 17:41:02 -08002191 if (IsUnifiedPlan()) {
2192 for (auto transceiver : transceivers_) {
2193 const ContentInfo* content =
2194 FindMediaSectionForTransceiver(transceiver, local_description());
2195 if (!content) {
2196 continue;
2197 }
Steve Anton74255ff2018-01-24 18:32:57 -08002198 const auto& streams = content->media_description()->streams();
2199 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002200 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002201 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002202 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002203 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002204 } else {
2205 // 0 is a special value meaning "this sender has no associated send
2206 // stream". Need to call this so the sender won't attempt to configure
2207 // a no longer existing stream and run into DCHECKs in the lower
2208 // layers.
2209 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002210 }
2211 }
2212 } else {
2213 // Plan B semantics.
2214
Steve Antondcc3c022017-12-22 16:02:54 -08002215 // Update state and SSRC of local MediaStreams and DataChannels based on the
2216 // local session description.
2217 const cricket::ContentInfo* audio_content =
2218 GetFirstAudioContent(local_description()->description());
2219 if (audio_content) {
2220 if (audio_content->rejected) {
2221 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2222 } else {
2223 const cricket::AudioContentDescription* audio_desc =
2224 audio_content->media_description()->as_audio();
2225 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2226 }
deadbeeffaac4972015-11-12 15:33:07 -08002227 }
deadbeefab9b2d12015-10-14 11:33:11 -07002228
Steve Antondcc3c022017-12-22 16:02:54 -08002229 const cricket::ContentInfo* video_content =
2230 GetFirstVideoContent(local_description()->description());
2231 if (video_content) {
2232 if (video_content->rejected) {
2233 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2234 } else {
2235 const cricket::VideoContentDescription* video_desc =
2236 video_content->media_description()->as_video();
2237 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2238 }
deadbeeffaac4972015-11-12 15:33:07 -08002239 }
deadbeefab9b2d12015-10-14 11:33:11 -07002240 }
2241
2242 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002243 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002244 if (data_content) {
2245 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002246 data_content->media_description()->as_data();
Steve Anton68586e82018-12-13 17:41:25 -08002247 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 11:33:11 -07002248 cricket::kMediaProtocolRtpPrefix)) {
2249 UpdateLocalRtpDataChannels(data_desc->streams());
2250 }
2251 }
2252
Steve Anton8a006912017-12-04 15:25:56 -08002253 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254}
2255
Steve Anton06817cd2018-12-18 15:55:30 -08002256// The SDP parser used to populate these values by default for the 'content
2257// name' if an a=mid line was absent.
2258static absl::string_view GetDefaultMidForPlanB(cricket::MediaType media_type) {
2259 switch (media_type) {
2260 case cricket::MEDIA_TYPE_AUDIO:
2261 return cricket::CN_AUDIO;
2262 case cricket::MEDIA_TYPE_VIDEO:
2263 return cricket::CN_VIDEO;
2264 case cricket::MEDIA_TYPE_DATA:
2265 return cricket::CN_DATA;
2266 }
2267 RTC_NOTREACHED();
2268 return "";
2269}
2270
2271void PeerConnection::FillInMissingRemoteMids(
2272 cricket::SessionDescription* remote_description) {
2273 RTC_DCHECK(remote_description);
2274 const cricket::ContentInfos& local_contents =
2275 (local_description() ? local_description()->description()->contents()
2276 : cricket::ContentInfos());
2277 std::set<std::string> used_mids = seen_mids_;
2278 for (size_t i = 0; i < remote_description->contents().size(); ++i) {
2279 cricket::ContentInfo& content = remote_description->contents()[i];
2280 if (!content.name.empty()) {
2281 continue;
2282 }
2283 absl::string_view new_mid;
2284 absl::string_view source_explanation;
2285 if (IsUnifiedPlan()) {
2286 if (i < local_contents.size()) {
2287 new_mid = local_contents[i].name;
2288 source_explanation = "from the matching local media section";
2289 } else {
2290 new_mid = AllocateMid(&used_mids);
2291 source_explanation = "generated just now";
2292 }
2293 } else {
2294 new_mid = GetDefaultMidForPlanB(content.media_description()->type());
2295 source_explanation = "to match pre-existing behavior";
2296 }
2297 content.name = std::string(new_mid);
2298 remote_description->transport_infos()[i].content_name =
2299 std::string(new_mid);
2300 RTC_LOG(LS_INFO) << "SetRemoteDescription: Remote media section at i=" << i
2301 << " is missing an a=mid line. Filling in the value '"
2302 << new_mid << "' " << source_explanation << ".";
2303 }
2304}
2305
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002306void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002307 SetSessionDescriptionObserver* observer,
2308 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002309 SetRemoteDescription(
2310 std::unique_ptr<SessionDescriptionInterface>(desc),
2311 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2312 new SetRemoteDescriptionObserverAdapter(this, observer)));
2313}
2314
2315void PeerConnection::SetRemoteDescription(
2316 std::unique_ptr<SessionDescriptionInterface> desc,
2317 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002318 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002319
nisse7ce109a2017-01-31 00:57:56 -08002320 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002321 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322 return;
2323 }
Steve Anton8a006912017-12-04 15:25:56 -08002324
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002325 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002326 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002327 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002328 return;
2329 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002330
Steve Anton80dd7b52018-02-16 17:08:42 -08002331 // If a session error has occurred the PeerConnection is in a possibly
2332 // inconsistent state so fail right away.
2333 if (session_error() != SessionError::kNone) {
2334 std::string error_message = GetSessionErrorMsg();
2335 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2336 observer->OnSetRemoteDescriptionComplete(
2337 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2338 return;
2339 }
Steve Anton71439a62018-02-15 11:53:06 -08002340
Steve Antonba42e992018-04-09 14:10:01 -07002341 if (desc->GetType() == SdpType::kOffer) {
2342 // Report to UMA the format of the received offer.
2343 ReportSdpFormatReceived(*desc);
2344 }
2345
Steve Anton06817cd2018-12-18 15:55:30 -08002346 // Handle remote descriptions missing a=mid lines for interop with legacy end
2347 // points.
2348 FillInMissingRemoteMids(desc->description());
2349
Steve Anton80dd7b52018-02-16 17:08:42 -08002350 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002351 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002352 std::string error_message = GetSetDescriptionErrorMessage(
2353 cricket::CS_REMOTE, desc->GetType(), error);
2354 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002355 observer->OnSetRemoteDescriptionComplete(
2356 RTCError(error.type(), std::move(error_message)));
2357 return;
2358 }
Steve Anton71439a62018-02-15 11:53:06 -08002359
Steve Anton80dd7b52018-02-16 17:08:42 -08002360 // Grab the description type before moving ownership to
2361 // ApplyRemoteDescription, which may destroy it before returning.
2362 const SdpType type = desc->GetType();
2363
2364 error = ApplyRemoteDescription(std::move(desc));
2365 // |desc| may be destroyed at this point.
2366
2367 if (!error.ok()) {
2368 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2369 // inconsistent state, so act conservatively here and set the session error
2370 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2371 SetSessionError(SessionError::kContent, error.message());
2372 std::string error_message =
2373 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2374 RTC_LOG(LS_ERROR) << error_message;
2375 observer->OnSetRemoteDescriptionComplete(
2376 RTCError(error.type(), std::move(error_message)));
2377 return;
2378 }
2379 RTC_DCHECK(remote_description());
2380
2381 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002382 // TODO(deadbeef): We already had to hop to the network thread for
2383 // MaybeStartGathering...
2384 network_thread()->Invoke<void>(
2385 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2386 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002387 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002388 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002389 }
2390
2391 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002392 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002393}
2394
2395RTCError PeerConnection::ApplyRemoteDescription(
2396 std::unique_ptr<SessionDescriptionInterface> desc) {
2397 RTC_DCHECK_RUN_ON(signaling_thread());
2398 RTC_DCHECK(desc);
2399
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002400 // Update stats here so that we have the most recent stats for tracks and
2401 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002402 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002403
Steve Antondcc3c022017-12-22 16:02:54 -08002404 // Take a reference to the old remote description since it's used below to
2405 // compare against the new remote description. When setting the new remote
2406 // description, grab ownership of the replaced session description in case it
2407 // is the same as |old_remote_description|, to keep it alive for the duration
2408 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002409 const SessionDescriptionInterface* old_remote_description =
2410 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002411 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002412 SdpType type = desc->GetType();
2413 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002414 replaced_remote_description = pending_remote_description_
2415 ? std::move(pending_remote_description_)
2416 : std::move(current_remote_description_);
2417 current_remote_description_ = std::move(desc);
2418 pending_remote_description_ = nullptr;
2419 current_local_description_ = std::move(pending_local_description_);
2420 } else {
2421 replaced_remote_description = std::move(pending_remote_description_);
2422 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002423 }
Steve Anton8a006912017-12-04 15:25:56 -08002424 // The session description to apply now must be accessed by
2425 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002426 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002427
Zhi Huange830e682018-03-30 10:48:35 -07002428 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2429 if (!error.ok()) {
2430 return error;
2431 }
Steve Anton8a006912017-12-04 15:25:56 -08002432 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002433 if (IsUnifiedPlan()) {
2434 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002435 cricket::CS_REMOTE, *remote_description(), local_description(),
2436 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002437 if (!error.ok()) {
2438 return error;
2439 }
Steve Antondcc3c022017-12-22 16:02:54 -08002440 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002441 // Media channels will be created only when offer is set. These may use new
2442 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002443 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002444 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002445 // description is applied. Restore back to old description.
2446 RTCError error = CreateChannels(*remote_description()->description());
2447 if (!error.ok()) {
2448 return error;
2449 }
2450 }
Steve Antondcc3c022017-12-22 16:02:54 -08002451 // Remove unused channels if MediaContentDescription is rejected.
2452 RemoveUnusedChannels(remote_description()->description());
2453 }
Steve Anton8a006912017-12-04 15:25:56 -08002454
Zhi Huange830e682018-03-30 10:48:35 -07002455 // NOTE: Candidates allocation will be initiated only when
2456 // SetLocalDescription is called.
2457 error = UpdateSessionState(type, cricket::CS_REMOTE,
2458 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002459 if (!error.ok()) {
2460 return error;
2461 }
2462
2463 if (local_description() &&
2464 !UseCandidatesInSessionDescription(remote_description())) {
2465 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2466 }
2467
2468 if (old_remote_description) {
2469 for (const cricket::ContentInfo& content :
2470 old_remote_description->description()->contents()) {
2471 // Check if this new SessionDescription contains new ICE ufrag and
2472 // password that indicates the remote peer requests an ICE restart.
2473 // TODO(deadbeef): When we start storing both the current and pending
2474 // remote description, this should reset pending_ice_restarts and compare
2475 // against the current description.
2476 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2477 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002478 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002479 pending_ice_restarts_.insert(content.name);
2480 }
2481 } else {
2482 // We retain all received candidates only if ICE is not restarted.
2483 // When ICE is restarted, all previous candidates belong to an old
2484 // generation and should not be kept.
2485 // TODO(deadbeef): This goes against the W3C spec which says the remote
2486 // description should only contain candidates from the last set remote
2487 // description plus any candidates added since then. We should remove
2488 // this once we're sure it won't break anything.
2489 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2490 old_remote_description, content.name, mutable_remote_description());
2491 }
2492 }
2493 }
2494
2495 if (session_error() != SessionError::kNone) {
2496 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2497 }
2498
2499 // Set the the ICE connection state to connecting since the connection may
2500 // become writable with peer reflexive candidates before any remote candidate
2501 // is signaled.
2502 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2503 // is to have a new signal the indicates a change in checking state from the
2504 // transport and expose a new checking() member from transport that can be
2505 // read to determine the current checking state. The existing SignalConnecting
2506 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002507 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002508 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002509 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2510 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2511 }
2512
deadbeefab9b2d12015-10-14 11:33:11 -07002513 // If setting the description decided our SSL role, allocate any necessary
2514 // SCTP sids.
2515 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002516 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002517 AllocateSctpSids(role);
2518 }
2519
Steve Antondcc3c022017-12-22 16:02:54 -08002520 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002521 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002522 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002523 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002524 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002525 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002526 for (auto transceiver : transceivers_) {
2527 const ContentInfo* content =
2528 FindMediaSectionForTransceiver(transceiver, remote_description());
2529 if (!content) {
2530 continue;
2531 }
2532 const MediaContentDescription* media_desc = content->media_description();
2533 RtpTransceiverDirection local_direction =
2534 RtpTransceiverDirectionReversed(media_desc->direction());
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002535 // Roughly the same as steps 2.2.8.6 of section 4.4.1.6 "Set the
2536 // RTCSessionDescription: Set the associated remote streams given
2537 // transceiver.[[Receiver]], msids, addList, and removeList".
2538 // https://w3c.github.io/webrtc-pc/#set-the-rtcsessiondescription
2539 if (RtpTransceiverDirectionHasRecv(local_direction)) {
2540 std::vector<std::string> stream_ids;
2541 if (!media_desc->streams().empty()) {
2542 // The remote description has signaled the stream IDs.
2543 stream_ids = media_desc->streams()[0].stream_ids();
Steve Antonef65ef12018-01-10 17:15:20 -08002544 }
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002545 RTC_LOG(LS_INFO) << "Processing the MSIDs for MID=" << content->name
2546 << " (" << GetStreamIdsString(stream_ids) << ").";
2547 SetAssociatedRemoteStreams(transceiver->internal()->receiver_internal(),
2548 stream_ids, &added_streams,
2549 &removed_streams);
2550 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6
2551 // "Set the RTCSessionDescription: If direction is sendrecv or recvonly,
2552 // and transceiver's current direction is neither sendrecv nor recvonly,
2553 // process the addition of a remote track for the media description.
2554 if (!transceiver->fired_direction() ||
2555 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction())) {
2556 RTC_LOG(LS_INFO)
2557 << "Processing the addition of a remote track for MID="
2558 << content->name << ".";
2559 now_receiving_transceivers.push_back(transceiver);
Henrik Boström5b147782018-12-04 11:25:05 +01002560 }
Steve Antondcc3c022017-12-22 16:02:54 -08002561 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002562 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2563 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2564 // removal of a remote track for the media description, given transceiver,
2565 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002566 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002567 (transceiver->fired_direction() &&
2568 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2569 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2570 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002571 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002572 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2573 transceiver->internal()->set_fired_direction(local_direction);
2574 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2575 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002576 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002577 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2578 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002579 transceiver->internal()->set_current_direction(local_direction);
2580 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002581 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2582 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002583 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002584 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2585 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002586 transceiver->Stop();
2587 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002588 if (!content->rejected &&
2589 RtpTransceiverDirectionHasRecv(local_direction)) {
2590 // Set ssrc to 0 in the case of an unsignalled ssrc.
2591 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002592 if (!media_desc->streams().empty() &&
2593 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002594 ssrc = media_desc->streams()[0].first_ssrc();
2595 }
2596 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002597 }
Steve Antondcc3c022017-12-22 16:02:54 -08002598 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002599 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002600 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002601 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002602 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002603 observer->OnTrack(transceiver);
2604 observer->OnAddTrack(transceiver->receiver(),
2605 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002606 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002607 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002608 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002609 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002610 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002611 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002612 }
2613 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002614 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002615 }
Steve Antondcc3c022017-12-22 16:02:54 -08002616 }
2617
Henrik Boströmfdb92012017-11-09 19:55:44 +01002618 const cricket::ContentInfo* audio_content =
2619 GetFirstAudioContent(remote_description()->description());
2620 const cricket::ContentInfo* video_content =
2621 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002622 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002623 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002624 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002625 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002626 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002627 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002628
2629 // Check if the descriptions include streams, just in case the peer supports
2630 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002631 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002632 (audio_desc && !audio_desc->streams().empty()) ||
2633 (video_desc && !video_desc->streams().empty())) {
2634 remote_peer_supports_msid_ = true;
2635 }
deadbeefab9b2d12015-10-14 11:33:11 -07002636
2637 // We wait to signal new streams until we finish processing the description,
2638 // since only at that point will new streams have all their tracks.
2639 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2640
Steve Antondcc3c022017-12-22 16:02:54 -08002641 if (!IsUnifiedPlan()) {
2642 // TODO(steveanton): When removing RTP senders/receivers in response to a
2643 // rejected media section, there is some cleanup logic that expects the
2644 // voice/ video channel to still be set. But in this method the voice/video
2645 // channel would have been destroyed by the SetRemoteDescription caller
2646 // above so the cleanup that relies on them fails to run. The RemoveSenders
2647 // calls should be moved to right before the DestroyChannel calls to fix
2648 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002649
Steve Antondcc3c022017-12-22 16:02:54 -08002650 // Find all audio rtp streams and create corresponding remote AudioTracks
2651 // and MediaStreams.
2652 if (audio_content) {
2653 if (audio_content->rejected) {
2654 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2655 } else {
2656 bool default_audio_track_needed =
2657 !remote_peer_supports_msid_ &&
2658 RtpTransceiverDirectionHasSend(audio_desc->direction());
2659 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2660 default_audio_track_needed, audio_desc->type(),
2661 new_streams);
2662 }
deadbeeffaac4972015-11-12 15:33:07 -08002663 }
deadbeefab9b2d12015-10-14 11:33:11 -07002664
Steve Antondcc3c022017-12-22 16:02:54 -08002665 // Find all video rtp streams and create corresponding remote VideoTracks
2666 // and MediaStreams.
2667 if (video_content) {
2668 if (video_content->rejected) {
2669 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2670 } else {
2671 bool default_video_track_needed =
2672 !remote_peer_supports_msid_ &&
2673 RtpTransceiverDirectionHasSend(video_desc->direction());
2674 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2675 default_video_track_needed, video_desc->type(),
2676 new_streams);
2677 }
deadbeeffaac4972015-11-12 15:33:07 -08002678 }
deadbeefab9b2d12015-10-14 11:33:11 -07002679
Steve Antondcc3c022017-12-22 16:02:54 -08002680 // Update the DataChannels with the information from the remote peer.
2681 if (data_desc) {
Steve Anton68586e82018-12-13 17:41:25 -08002682 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-22 16:02:54 -08002683 cricket::kMediaProtocolRtpPrefix)) {
2684 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2685 }
deadbeefab9b2d12015-10-14 11:33:11 -07002686 }
deadbeefab9b2d12015-10-14 11:33:11 -07002687
Steve Antondcc3c022017-12-22 16:02:54 -08002688 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002689 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002690 for (size_t i = 0; i < new_streams->count(); ++i) {
2691 MediaStreamInterface* new_stream = new_streams->at(i);
2692 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002693 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002694 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2695 }
deadbeefab9b2d12015-10-14 11:33:11 -07002696
Steve Antondcc3c022017-12-22 16:02:54 -08002697 UpdateEndedRemoteMediaStreams();
2698 }
deadbeefab9b2d12015-10-14 11:33:11 -07002699
Steve Anton8a006912017-12-04 15:25:56 -08002700 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002701}
2702
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002703void PeerConnection::SetAssociatedRemoteStreams(
2704 rtc::scoped_refptr<RtpReceiverInternal> receiver,
2705 const std::vector<std::string>& stream_ids,
2706 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* added_streams,
2707 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2708 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2709 for (const std::string& stream_id : stream_ids) {
2710 rtc::scoped_refptr<MediaStreamInterface> stream =
2711 remote_streams_->find(stream_id);
2712 if (!stream) {
2713 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2714 MediaStream::Create(stream_id));
2715 remote_streams_->AddStream(stream);
2716 added_streams->push_back(stream);
2717 }
2718 media_streams.push_back(stream);
2719 }
2720 // Special case: "a=msid" missing, use random stream ID.
2721 if (media_streams.empty() &&
2722 !(remote_description()->description()->msid_signaling() &
2723 cricket::kMsidSignalingMediaSection)) {
2724 if (!missing_msid_default_stream_) {
2725 missing_msid_default_stream_ = MediaStreamProxy::Create(
2726 rtc::Thread::Current(), MediaStream::Create(rtc::CreateRandomUuid()));
2727 added_streams->push_back(missing_msid_default_stream_);
2728 }
2729 media_streams.push_back(missing_msid_default_stream_);
2730 }
2731 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
2732 receiver->streams();
2733 // SetStreams() will add/remove the receiver's track to/from the streams. This
2734 // differs from the spec - the spec uses an "addList" and "removeList" to
2735 // update the stream-track relationships in a later step. We do this earlier,
2736 // changing the order of things, but the end-result is the same.
2737 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2738 // instead. https://crbug.com/webrtc/9480
2739 receiver->SetStreams(media_streams);
2740 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2741}
2742
Steve Anton0f5400a2018-07-17 14:25:36 -07002743void PeerConnection::ProcessRemovalOfRemoteTrack(
2744 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2745 transceiver,
2746 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2747 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2748 RTC_DCHECK(transceiver->mid());
2749 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2750 << *transceiver->mid();
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002751 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 14:25:36 -07002752 transceiver->internal()->receiver_internal()->streams();
2753 // This will remove the remote track from the streams.
2754 transceiver->internal()->receiver_internal()->set_stream_ids({});
2755 remove_list->push_back(transceiver);
Henrik Boströmafa07dd2018-12-20 11:06:02 +01002756 RemoveRemoteStreamsIfEmpty(previous_streams, removed_streams);
2757}
2758
2759void PeerConnection::RemoveRemoteStreamsIfEmpty(
2760 const std::vector<rtc::scoped_refptr<MediaStreamInterface>>& remote_streams,
2761 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2762 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead of
2763 // streams, see if the stream was removed by checking if this was the last
2764 // receiver with that stream ID.
2765 for (auto remote_stream : remote_streams) {
2766 if (remote_stream->GetAudioTracks().empty() &&
2767 remote_stream->GetVideoTracks().empty()) {
2768 remote_streams_->RemoveStream(remote_stream);
2769 removed_streams->push_back(remote_stream);
Steve Anton0f5400a2018-07-17 14:25:36 -07002770 }
2771 }
2772}
2773
Steve Antondcc3c022017-12-22 16:02:54 -08002774RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2775 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002776 const SessionDescriptionInterface& new_session,
2777 const SessionDescriptionInterface* old_local_description,
2778 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002779 RTC_DCHECK(IsUnifiedPlan());
2780
Steve Anton7464fca2018-01-19 11:10:37 -08002781 const cricket::ContentGroup* bundle_group = nullptr;
2782 if (new_session.GetType() == SdpType::kOffer) {
2783 auto bundle_group_or_error =
2784 GetEarlyBundleGroup(*new_session.description());
2785 if (!bundle_group_or_error.ok()) {
2786 return bundle_group_or_error.MoveError();
2787 }
2788 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002789 }
Steve Antondcc3c022017-12-22 16:02:54 -08002790
Steve Antondcc3c022017-12-22 16:02:54 -08002791 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002792 for (size_t i = 0; i < new_contents.size(); ++i) {
2793 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002794 cricket::MediaType media_type = new_content.media_description()->type();
2795 seen_mids_.insert(new_content.name);
2796 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2797 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002798 const cricket::ContentInfo* old_local_content = nullptr;
2799 if (old_local_description &&
2800 i < old_local_description->description()->contents().size()) {
2801 old_local_content =
2802 &old_local_description->description()->contents()[i];
2803 }
2804 const cricket::ContentInfo* old_remote_content = nullptr;
2805 if (old_remote_description &&
2806 i < old_remote_description->description()->contents().size()) {
2807 old_remote_content =
2808 &old_remote_description->description()->contents()[i];
2809 }
Steve Antondcc3c022017-12-22 16:02:54 -08002810 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002811 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2812 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002813 if (!transceiver_or_error.ok()) {
2814 return transceiver_or_error.MoveError();
2815 }
2816 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002817 RTCError error =
2818 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2819 if (!error.ok()) {
2820 return error;
2821 }
2822 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002823 if (GetDataMid() && new_content.name != *GetDataMid()) {
2824 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002825 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2826 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002827 continue;
2828 }
2829 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2830 if (!error.ok()) {
2831 return error;
2832 }
Steve Antondcc3c022017-12-22 16:02:54 -08002833 } else {
2834 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2835 "Unknown section type.");
2836 }
2837 }
2838
2839 return RTCError::OK();
2840}
2841
2842RTCError PeerConnection::UpdateTransceiverChannel(
2843 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2844 transceiver,
2845 const cricket::ContentInfo& content,
2846 const cricket::ContentGroup* bundle_group) {
2847 RTC_DCHECK(IsUnifiedPlan());
2848 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002849 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002850 if (content.rejected) {
2851 if (channel) {
2852 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002853 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002854 }
2855 } else {
2856 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002857 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002858 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002859 } else {
Steve Anton69470252018-02-09 11:43:08 -08002860 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002861 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002862 }
2863 if (!channel) {
2864 LOG_AND_RETURN_ERROR(
2865 RTCErrorType::INTERNAL_ERROR,
2866 "Failed to create channel for mid=" + content.name);
2867 }
2868 transceiver->internal()->SetChannel(channel);
2869 }
2870 }
2871 return RTCError::OK();
2872}
2873
Steve Antonfa2260d2017-12-28 16:38:23 -08002874RTCError PeerConnection::UpdateDataChannel(
2875 cricket::ContentSource source,
2876 const cricket::ContentInfo& content,
2877 const cricket::ContentGroup* bundle_group) {
2878 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002879 // If data channels are disabled, ignore this media section. CreateAnswer
2880 // will take care of rejecting it.
2881 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002882 }
2883 if (content.rejected) {
2884 DestroyDataChannel();
2885 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002886 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002887 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002888 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2889 "Failed to create data channel.");
2890 }
2891 }
2892 if (source == cricket::CS_REMOTE) {
2893 const MediaContentDescription* data_desc = content.media_description();
2894 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2895 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2896 }
2897 }
2898 }
2899 return RTCError::OK();
2900}
2901
Steve Antondcc3c022017-12-22 16:02:54 -08002902RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2903PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002904 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002905 size_t mline_index,
2906 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002907 const ContentInfo* old_local_content,
2908 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002909 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002910 // If this is an offer then the m= section might be recycled. If the m=
2911 // section is being recycled (defined as: rejected in the current local or
2912 // remote description and not rejected in new description), dissociate the
2913 // currently associated RtpTransceiver by setting its mid property to null,
2914 // and discard the mapping between the transceiver and its m= section index.
2915 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2916 old_remote_content)) {
2917 // We want to dissociate the transceiver that has the rejected mid.
2918 const std::string& old_mid =
2919 (old_local_content && old_local_content->rejected)
2920 ? old_local_content->name
2921 : old_remote_content->name;
2922 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002923 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002924 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2925 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002926 old_transceiver->internal()->set_mid(absl::nullopt);
2927 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002928 }
2929 }
2930 const MediaContentDescription* media_desc = content.media_description();
2931 auto transceiver = GetAssociatedTransceiver(content.name);
2932 if (source == cricket::CS_LOCAL) {
2933 // Find the RtpTransceiver that corresponds to this m= section, using the
2934 // mapping between transceivers and m= section indices established when
2935 // creating the offer.
2936 if (!transceiver) {
2937 transceiver = GetTransceiverByMLineIndex(mline_index);
2938 }
2939 if (!transceiver) {
2940 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2941 "Unknown transceiver");
2942 }
2943 } else {
2944 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2945 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2946 // of the same type...
2947 if (!transceiver &&
2948 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2949 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2950 }
2951 // If no RtpTransceiver was found in the previous step, create one with a
2952 // recvonly direction.
2953 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002954 RTC_LOG(LS_INFO) << "Adding "
2955 << cricket::MediaTypeToString(media_desc->type())
2956 << " transceiver for MID=" << content.name
2957 << " at i=" << mline_index
2958 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002959 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002960 auto sender =
2961 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002962 std::string receiver_id;
2963 if (!media_desc->streams().empty()) {
2964 receiver_id = media_desc->streams()[0].id;
2965 } else {
2966 receiver_id = rtc::CreateRandomUuid();
2967 }
2968 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002969 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002970 transceiver->internal()->set_direction(
2971 RtpTransceiverDirection::kRecvOnly);
2972 }
2973 }
2974 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002975 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002976 LOG_AND_RETURN_ERROR(
2977 RTCErrorType::INVALID_PARAMETER,
2978 "Transceiver type does not match media description type.");
2979 }
2980 // Associate the found or created RtpTransceiver with the m= section by
2981 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2982 // section, and establish a mapping between the transceiver and the index of
2983 // the m= section.
2984 transceiver->internal()->set_mid(content.name);
2985 transceiver->internal()->set_mline_index(mline_index);
2986 return std::move(transceiver);
2987}
2988
2989rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2990PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2991 RTC_DCHECK(IsUnifiedPlan());
2992 for (auto transceiver : transceivers_) {
2993 if (transceiver->mid() == mid) {
2994 return transceiver;
2995 }
2996 }
2997 return nullptr;
2998}
2999
3000rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3001PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
3002 RTC_DCHECK(IsUnifiedPlan());
3003 for (auto transceiver : transceivers_) {
3004 if (transceiver->internal()->mline_index() == mline_index) {
3005 return transceiver;
3006 }
3007 }
3008 return nullptr;
3009}
3010
3011rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3012PeerConnection::FindAvailableTransceiverToReceive(
3013 cricket::MediaType media_type) const {
3014 RTC_DCHECK(IsUnifiedPlan());
3015 // From JSEP section 5.10 (Applying a Remote Description):
3016 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
3017 // the same type that were added to the PeerConnection by addTrack and are not
3018 // associated with any m= section and are not stopped, find the first such
3019 // RtpTransceiver.
3020 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08003021 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08003022 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3023 !transceiver->stopped()) {
3024 return transceiver;
3025 }
3026 }
3027 return nullptr;
3028}
3029
Steve Antoned10bd92017-12-05 10:52:59 -08003030const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
3031 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3032 transceiver,
3033 const SessionDescriptionInterface* sdesc) const {
3034 RTC_DCHECK(transceiver);
3035 RTC_DCHECK(sdesc);
3036 if (IsUnifiedPlan()) {
3037 if (!transceiver->internal()->mid()) {
3038 // This transceiver is not associated with a media section yet.
3039 return nullptr;
3040 }
3041 return sdesc->description()->GetContentByName(
3042 *transceiver->internal()->mid());
3043 } else {
3044 // Plan B only allows at most one audio and one video section, so use the
3045 // first media section of that type.
3046 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08003047 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08003048 }
3049}
3050
deadbeef46c73892016-11-16 19:42:04 -08003051PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3052 return configuration_;
3053}
3054
deadbeef293e9262017-01-11 12:28:30 -08003055bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3056 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003057 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07003058 if (IsClosed()) {
3059 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3060 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3061 }
3062
Qingsi Wanga2d60672018-04-11 16:57:45 -07003063 // According to JSEP, after setLocalDescription, changing the candidate pool
3064 // size is not allowed, and changing the set of ICE servers will not result
3065 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08003066 if (local_description() && configuration.ice_candidate_pool_size !=
3067 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003068 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3069 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08003070 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003071 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003072
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003073 if (local_description() &&
3074 configuration.use_media_transport != configuration_.use_media_transport) {
3075 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3076 "SetLocalDescription.";
3077 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3078 }
3079
3080 if (remote_description() &&
3081 configuration.use_media_transport != configuration_.use_media_transport) {
3082 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
3083 "SetRemoteDescription.";
3084 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3085 }
3086
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003087 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003088 configuration.use_media_transport_for_data_channels !=
3089 configuration_.use_media_transport_for_data_channels) {
3090 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3091 "after calling SetLocalDescription.";
3092 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3093 }
3094
3095 if (remote_description() &&
3096 configuration.use_media_transport_for_data_channels !=
3097 configuration_.use_media_transport_for_data_channels) {
3098 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
3099 "after calling SetRemoteDescription.";
3100 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3101 }
3102
3103 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003104 configuration.crypto_options != configuration_.crypto_options) {
3105 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
3106 "SetLocalDescription.";
3107 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3108 }
3109
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08003110 if (configuration.use_media_transport_for_data_channels ||
3111 configuration.use_media_transport) {
3112 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
3113 << "Media transport requires MaxBundle policy.";
3114 }
3115
deadbeef293e9262017-01-11 12:28:30 -08003116 // The simplest (and most future-compatible) way to tell if the config was
3117 // modified in an invalid way is to copy each property we do support
3118 // modifying, then use operator==. There are far more properties we don't
3119 // support modifying than those we do, and more could be added.
3120 RTCConfiguration modified_config = configuration_;
3121 modified_config.servers = configuration.servers;
3122 modified_config.type = configuration.type;
3123 modified_config.ice_candidate_pool_size =
3124 configuration.ice_candidate_pool_size;
3125 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003126 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003127 modified_config.ice_check_interval_strong_connectivity =
3128 configuration.ice_check_interval_strong_connectivity;
3129 modified_config.ice_check_interval_weak_connectivity =
3130 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003131 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3132 modified_config.ice_unwritable_min_checks =
3133 configuration.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08003134 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003135 modified_config.stun_candidate_keepalive_interval =
3136 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003137 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003138 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003139 modified_config.active_reset_srtp_params =
3140 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003141 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003142 modified_config.use_media_transport_for_data_channels =
3143 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003144 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003145 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003146 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3147 }
3148
Steve Anton038834f2017-07-14 15:59:59 -07003149 // Validate the modified configuration.
3150 RTCError validate_error = ValidateConfiguration(modified_config);
3151 if (!validate_error.ok()) {
3152 return SafeSetError(std::move(validate_error), error);
3153 }
3154
deadbeef293e9262017-01-11 12:28:30 -08003155 // Note that this isn't possible through chromium, since it's an unsigned
3156 // short in WebIDL.
3157 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003158 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003159 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3160 }
3161
3162 // Parse ICE servers before hopping to network thread.
3163 cricket::ServerAddresses stun_servers;
3164 std::vector<cricket::RelayServerConfig> turn_servers;
3165 RTCErrorType parse_error =
3166 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3167 if (parse_error != RTCErrorType::NONE) {
3168 return SafeSetError(parse_error, error);
3169 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003170 // Note if STUN or TURN servers were supplied.
3171 if (!stun_servers.empty()) {
3172 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3173 }
3174 if (!turn_servers.empty()) {
3175 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3176 }
deadbeef293e9262017-01-11 12:28:30 -08003177
3178 // In theory this shouldn't fail.
3179 if (!network_thread()->Invoke<bool>(
3180 RTC_FROM_HERE,
3181 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3182 stun_servers, turn_servers, modified_config.type,
3183 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003184 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003185 modified_config.turn_customizer,
3186 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003187 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003188 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3189 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003190
deadbeefd1a38b52016-12-10 13:15:33 -08003191 // As described in JSEP, calling setConfiguration with new ICE servers or
3192 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3193 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003194 if (modified_config.servers != configuration_.servers ||
3195 modified_config.type != configuration_.type ||
3196 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003197 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003198 }
skvladd1f5fda2017-02-03 16:54:05 -08003199
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003200 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003201 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003202 modified_config.use_media_transport ||
3203 modified_config.use_media_transport_for_data_channels
3204 ? factory_->media_transport_factory()
3205 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003206
Zhi Huangb57e1692018-06-12 11:41:11 -07003207 if (configuration_.active_reset_srtp_params !=
3208 modified_config.active_reset_srtp_params) {
3209 transport_controller_->SetActiveResetSrtpParams(
3210 modified_config.active_reset_srtp_params);
3211 }
3212
deadbeef293e9262017-01-11 12:28:30 -08003213 configuration_ = modified_config;
3214 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003215}
3216
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003217bool PeerConnection::AddIceCandidate(
3218 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003219 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003220 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003221 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003222 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003223 return false;
3224 }
Steve Antond25da372017-11-06 14:50:29 -08003225
3226 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003227 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003228 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003229 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003230 return false;
3231 }
3232
3233 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003234 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003235 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003236 return false;
3237 }
3238
3239 bool valid = false;
3240 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3241 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003242 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003243 return false;
3244 }
3245
3246 // Add this candidate to the remote session description.
3247 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003248 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003249 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003250 return false;
3251 }
3252
3253 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003254 bool result = UseCandidate(ice_candidate);
3255 if (result) {
3256 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3257 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3258 } else {
3259 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3260 }
3261 return result;
Steve Antond25da372017-11-06 14:50:29 -08003262 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003263 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003264 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003265 return true;
3266 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003267}
3268
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003269bool PeerConnection::RemoveIceCandidates(
3270 const std::vector<cricket::Candidate>& candidates) {
3271 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003272 if (IsClosed()) {
3273 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3274 return false;
3275 }
3276
Steve Antond25da372017-11-06 14:50:29 -08003277 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003278 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3279 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003280 return false;
3281 }
3282
3283 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003284 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003285 return false;
3286 }
3287
3288 size_t number_removed =
3289 mutable_remote_description()->RemoveCandidates(candidates);
3290 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003291 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003292 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003293 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003294 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003295 }
3296
3297 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003298 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3299 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003300 RTC_LOG(LS_ERROR)
3301 << "RemoveIceCandidates: Error when removing remote candidates: "
3302 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003303 }
3304 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003305}
3306
Niels Möller0c4f7be2018-05-07 14:01:37 +02003307RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003308 if (!worker_thread()->IsCurrent()) {
3309 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003310 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003311 }
3312
Niels Möller0c4f7be2018-05-07 14:01:37 +02003313 const bool has_min = bitrate.min_bitrate_bps.has_value();
3314 const bool has_start = bitrate.start_bitrate_bps.has_value();
3315 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003316 if (has_min && *bitrate.min_bitrate_bps < 0) {
3317 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3318 "min_bitrate_bps <= 0");
3319 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003320 if (has_start) {
3321 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003322 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003323 "start_bitrate_bps < min_bitrate_bps");
3324 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003325 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3326 "curent_bitrate_bps < 0");
3327 }
3328 }
3329 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003330 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003331 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003332 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003333 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3334 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3335 "max_bitrate_bps < min_bitrate_bps");
3336 } else if (*bitrate.max_bitrate_bps < 0) {
3337 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3338 "max_bitrate_bps < 0");
3339 }
3340 }
3341
zstein4b979802017-06-02 14:37:37 -07003342 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003343 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003344
3345 return RTCError::OK();
3346}
3347
Alex Narest78609d52017-10-20 10:37:47 +02003348void PeerConnection::SetBitrateAllocationStrategy(
3349 std::unique_ptr<rtc::BitrateAllocationStrategy>
3350 bitrate_allocation_strategy) {
3351 rtc::Thread* worker_thread = factory_->worker_thread();
3352 if (!worker_thread->IsCurrent()) {
3353 rtc::BitrateAllocationStrategy* strategy_raw =
3354 bitrate_allocation_strategy.release();
3355 auto functor = [this, strategy_raw]() {
3356 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003357 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003358 };
3359 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3360 return;
3361 }
3362 RTC_DCHECK(call_.get());
3363 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3364}
3365
henrika5f6bf242017-11-01 11:06:56 +01003366void PeerConnection::SetAudioPlayout(bool playout) {
3367 if (!worker_thread()->IsCurrent()) {
3368 worker_thread()->Invoke<void>(
3369 RTC_FROM_HERE,
3370 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3371 return;
3372 }
3373 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003374 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003375 audio_state->SetPlayout(playout);
3376}
3377
3378void PeerConnection::SetAudioRecording(bool recording) {
3379 if (!worker_thread()->IsCurrent()) {
3380 worker_thread()->Invoke<void>(
3381 RTC_FROM_HERE,
3382 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3383 return;
3384 }
3385 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003386 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003387 audio_state->SetRecording(recording);
3388}
3389
Steve Anton8c0f7a72017-10-03 10:03:10 -07003390std::unique_ptr<rtc::SSLCertificate>
3391PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003392 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3393 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003394 return nullptr;
3395 }
Steve Antonf25303e2018-10-16 15:23:31 -07003396 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003397}
3398
Zhi Huang70b820f2018-01-27 14:16:15 -08003399std::unique_ptr<rtc::SSLCertChain>
3400PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003401 auto audio_transceiver = GetFirstAudioTransceiver();
3402 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003403 return nullptr;
3404 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003405 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003406 audio_transceiver->internal()->channel()->transport_name());
3407}
3408
3409rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3410PeerConnection::GetFirstAudioTransceiver() const {
3411 for (auto transceiver : transceivers_) {
3412 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3413 return transceiver;
3414 }
3415 }
3416 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003417}
3418
ivoc14d5dbe2016-07-04 07:06:55 -07003419bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3420 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003421 // TODO(eladalon): It would be better to not allow negative values into PC.
3422 const size_t max_size = (max_size_bytes < 0)
3423 ? RtcEventLog::kUnlimitedOutput
3424 : rtc::saturated_cast<size_t>(max_size_bytes);
Bjorn Terelius8b556022018-11-27 15:43:01 +01003425 int64_t output_period_ms = webrtc::RtcEventLog::kImmediateOutput;
3426 if (field_trial::IsEnabled("WebRTC-RtcEventLogNewFormat")) {
3427 output_period_ms = 5000;
3428 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003429 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003430 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 15:43:01 +01003431 output_period_ms);
Elad Alon99c3fe52017-10-13 16:29:40 +02003432}
3433
Bjorn Tereliusde939432017-11-20 17:38:14 +01003434bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3435 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003436 // TODO(eladalon): In C++14, this can be done with a lambda.
3437 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003438 bool operator()() {
3439 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3440 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003441 PeerConnection* const pc;
3442 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003443 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003444 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003445 return worker_thread()->Invoke<bool>(
3446 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003447}
3448
3449void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003450 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003451 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3452}
3453
Harald Alvestrandad88c882018-11-28 16:47:46 +01003454rtc::scoped_refptr<DtlsTransportInterface>
3455PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3456 return transport_controller_->LookupDtlsTransportByMid(mid);
3457}
3458
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003459const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003460 return pending_local_description_ ? pending_local_description_.get()
3461 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003462}
3463
3464const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003465 return pending_remote_description_ ? pending_remote_description_.get()
3466 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003467}
3468
deadbeeffe4a8a42016-12-20 17:56:17 -08003469const SessionDescriptionInterface* PeerConnection::current_local_description()
3470 const {
Steve Anton75737c02017-11-06 10:37:17 -08003471 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003472}
3473
3474const SessionDescriptionInterface* PeerConnection::current_remote_description()
3475 const {
Steve Anton75737c02017-11-06 10:37:17 -08003476 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003477}
3478
3479const SessionDescriptionInterface* PeerConnection::pending_local_description()
3480 const {
Steve Anton75737c02017-11-06 10:37:17 -08003481 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003482}
3483
3484const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3485 const {
Steve Anton75737c02017-11-06 10:37:17 -08003486 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003487}
3488
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003489void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003490 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003491 // Update stats here so that we have the most recent stats for tracks and
3492 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003493 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003494
Steve Anton75737c02017-11-06 10:37:17 -08003495 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003496 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003497
Steve Anton8af21862017-12-15 11:20:13 -08003498 for (auto transceiver : transceivers_) {
3499 transceiver->Stop();
3500 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003501
3502 // Ensure that all asynchronous stats requests are completed before destroying
3503 // the transport controller below.
3504 if (stats_collector_) {
3505 stats_collector_->WaitForPendingRequest();
3506 }
3507
3508 // Don't destroy BaseChannels until after stats has been cleaned up so that
3509 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003510 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003511
Qingsi Wang93a84392018-01-30 17:13:09 -08003512 // The event log is used in the transport controller, which must be outlived
3513 // by the former. CreateOffer by the peer connection is implemented
3514 // asynchronously and if the peer connection is closed without resetting the
3515 // WebRTC session description factory, the session description factory would
3516 // call the transport controller.
3517 webrtc_session_desc_factory_.reset();
3518 transport_controller_.reset();
3519
deadbeef42a42632017-03-10 15:18:00 -08003520 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003521 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3522 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003523
Steve Anton978b8762017-09-29 12:15:02 -07003524 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003525 call_.reset();
3526 // The event log must outlive call (and any other object that uses it).
3527 event_log_.reset();
3528 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003529 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003530 // The .h file says that observer can be discarded after close() returns.
3531 // Make sure this is true.
3532 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003533}
3534
Steve Antonad182762018-09-05 20:22:40 +00003535void PeerConnection::OnMessage(rtc::Message* msg) {
3536 switch (msg->message_id) {
3537 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3538 SetSessionDescriptionMsg* param =
3539 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3540 param->observer->OnSuccess();
3541 delete param;
3542 break;
3543 }
3544 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3545 SetSessionDescriptionMsg* param =
3546 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3547 param->observer->OnFailure(std::move(param->error));
3548 delete param;
3549 break;
3550 }
3551 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3552 CreateSessionDescriptionMsg* param =
3553 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3554 param->observer->OnFailure(std::move(param->error));
3555 delete param;
3556 break;
3557 }
3558 case MSG_GETSTATS: {
3559 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3560 StatsReports reports;
3561 stats_->GetStats(param->track, &reports);
3562 param->observer->OnComplete(reports);
3563 delete param;
3564 break;
3565 }
3566 case MSG_FREE_DATACHANNELS: {
3567 sctp_data_channels_to_free_.clear();
3568 break;
3569 }
3570 case MSG_REPORT_USAGE_PATTERN: {
3571 ReportUsagePattern();
3572 break;
3573 }
3574 default:
3575 RTC_NOTREACHED() << "Not implemented";
3576 break;
3577 }
3578}
3579
Steve Antonafb0bb72018-02-20 11:35:37 -08003580cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3581 RTC_DCHECK(!IsUnifiedPlan());
3582 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3583 GetAudioTransceiver()->internal()->channel());
3584 if (voice_channel) {
3585 return voice_channel->media_channel();
3586 } else {
3587 return nullptr;
3588 }
3589}
3590
3591cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3592 RTC_DCHECK(!IsUnifiedPlan());
3593 auto* video_channel = static_cast<cricket::VideoChannel*>(
3594 GetVideoTransceiver()->internal()->channel());
3595 if (video_channel) {
3596 return video_channel->media_channel();
3597 } else {
3598 return nullptr;
3599 }
3600}
3601
Steve Anton4171afb2017-11-20 10:20:22 -08003602void PeerConnection::CreateAudioReceiver(
3603 MediaStreamInterface* stream,
3604 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003605 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3606 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003607 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3608 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003609 auto* audio_receiver = new AudioRtpReceiver(
3610 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003611 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003612 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3613 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3614 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003615 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003616 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003617 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003618}
3619
Steve Anton4171afb2017-11-20 10:20:22 -08003620void PeerConnection::CreateVideoReceiver(
3621 MediaStreamInterface* stream,
3622 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003623 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3624 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003625 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3626 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003627 auto* video_receiver = new VideoRtpReceiver(
3628 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003629 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003630 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3631 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3632 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003633 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003634 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003635 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003636}
3637
deadbeef70ab1a12015-09-28 16:53:55 -07003638// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3639// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003640rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003641 const RtpSenderInfo& remote_sender_info) {
3642 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3643 if (!receiver) {
3644 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3645 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003646 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003647 }
Steve Anton4171afb2017-11-20 10:20:22 -08003648 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3649 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3650 } else {
3651 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3652 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003653 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003654}
3655
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003656void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3657 MediaStreamInterface* stream) {
3658 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003659 RTC_DCHECK(track);
3660 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003661 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003662 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003663 // We already have a sender for this track, so just change the stream_id
3664 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003665 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003666 return;
3667 }
3668
3669 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003670 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003671 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003672 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003673 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003674 // If the sender has already been configured in SDP, we call SetSsrc,
3675 // which will connect the sender to the underlying transport. This can
3676 // occur if a local session description that contains the ID of the sender
3677 // is set before AddStream is called. It can also occur if the local
3678 // session description is not changed and RemoveStream is called, and
3679 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003680 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003681 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003682 if (sender_info) {
3683 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003684 }
3685}
3686
3687// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3688// indefinitely, when we have unified plan SDP.
3689void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3690 MediaStreamInterface* stream) {
3691 RTC_DCHECK(!IsClosed());
3692 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003693 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003694 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3695 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003696 return;
3697 }
Steve Anton4171afb2017-11-20 10:20:22 -08003698 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003699}
3700
3701void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3702 MediaStreamInterface* stream) {
3703 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003704 RTC_DCHECK(track);
3705 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003706 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003707 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003708 // We already have a sender for this track, so just change the stream_id
3709 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003710 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003711 return;
3712 }
3713
3714 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003715 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003716 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003717 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003718 GetVideoTransceiver()->internal()->AddSender(new_sender);
3719 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003720 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003721 if (sender_info) {
3722 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003723 }
3724}
3725
3726void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3727 MediaStreamInterface* stream) {
3728 RTC_DCHECK(!IsClosed());
3729 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003730 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003731 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3732 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003733 return;
3734 }
Steve Anton4171afb2017-11-20 10:20:22 -08003735 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003736}
3737
Steve Antonba818672017-11-06 10:21:57 -08003738void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003739 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003740 if (ice_connection_state_ == new_state) {
3741 return;
3742 }
3743
deadbeefcbecd352015-09-23 11:50:27 -07003744 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003745 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003746 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003747 return;
3748 }
Steve Antonba818672017-11-06 10:21:57 -08003749
Mirko Bonadei675513b2017-11-09 11:09:25 +01003750 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3751 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003752 RTC_DCHECK(ice_connection_state_ !=
3753 PeerConnectionInterface::kIceConnectionClosed);
3754
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003755 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003756 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003757}
3758
Alex Loiko9289eda2018-11-23 16:18:59 +00003759void PeerConnection::SetStandardizedIceConnectionState(
3760 PeerConnectionInterface::IceConnectionState new_state) {
3761 RTC_DCHECK(signaling_thread()->IsCurrent());
3762 if (standardized_ice_connection_state_ == new_state)
3763 return;
3764 if (IsClosed())
3765 return;
3766 standardized_ice_connection_state_ = new_state;
Jonas Olsson12046902018-12-06 11:25:14 +01003767 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:59 +00003768}
3769
Jonas Olsson635474e2018-10-18 15:58:17 +02003770void PeerConnection::SetConnectionState(
3771 PeerConnectionInterface::PeerConnectionState new_state) {
3772 RTC_DCHECK(signaling_thread()->IsCurrent());
3773 if (connection_state_ == new_state)
3774 return;
3775 if (IsClosed())
3776 return;
3777 connection_state_ = new_state;
3778 Observer()->OnConnectionChange(new_state);
3779}
3780
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003781void PeerConnection::OnIceGatheringChange(
3782 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003783 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003784 if (IsClosed()) {
3785 return;
3786 }
3787 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003788 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003789}
3790
jbauch81bf7b02017-03-25 08:31:12 -07003791void PeerConnection::OnIceCandidate(
3792 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003793 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003794 if (IsClosed()) {
3795 return;
3796 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003797 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003798 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3799 candidate->candidate().address().IsPrivateIP()) {
3800 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3801 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003802 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003803}
3804
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003805void PeerConnection::OnIceCandidatesRemoved(
3806 const std::vector<cricket::Candidate>& candidates) {
3807 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003808 if (IsClosed()) {
3809 return;
3810 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003811 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003812}
3813
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003814void PeerConnection::ChangeSignalingState(
3815 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003816 RTC_DCHECK(signaling_thread()->IsCurrent());
3817 if (signaling_state_ == signaling_state) {
3818 return;
3819 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003820 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3821 << GetSignalingStateString(signaling_state_)
3822 << " New state: "
3823 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003824 signaling_state_ = signaling_state;
3825 if (signaling_state == kClosed) {
3826 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003827 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:59 +00003828 standardized_ice_connection_state_ =
3829 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 15:58:17 +02003830 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3831 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003832 if (ice_gathering_state_ != kIceGatheringComplete) {
3833 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003834 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003835 }
3836 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003837 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003838}
3839
deadbeefeb459812015-12-15 19:24:43 -08003840void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3841 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003842 if (IsClosed()) {
3843 return;
3844 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003845 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003846 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003847}
3848
deadbeefeb459812015-12-15 19:24:43 -08003849void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3850 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003851 if (IsClosed()) {
3852 return;
3853 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003854 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003855 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003856}
3857
3858void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3859 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003860 if (IsClosed()) {
3861 return;
3862 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003863 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003864 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003865}
3866
3867void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3868 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003869 if (IsClosed()) {
3870 return;
3871 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003872 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003873 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003874}
3875
Henrik Boström31638672017-11-23 17:48:32 +01003876void PeerConnection::PostSetSessionDescriptionSuccess(
3877 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003878 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3879 signaling_thread()->Post(RTC_FROM_HERE, this,
3880 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003881}
3882
deadbeefab9b2d12015-10-14 11:33:11 -07003883void PeerConnection::PostSetSessionDescriptionFailure(
3884 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003885 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003886 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003887 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3888 msg->error = std::move(error);
3889 signaling_thread()->Post(RTC_FROM_HERE, this,
3890 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003891}
3892
3893void PeerConnection::PostCreateSessionDescriptionFailure(
3894 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003895 RTCError error) {
3896 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003897 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3898 msg->error = std::move(error);
3899 signaling_thread()->Post(RTC_FROM_HERE, this,
3900 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003901}
3902
zhihuang1c378ed2017-08-17 14:10:50 -07003903void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003904 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003905 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003906 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003907
Steve Antondcc3c022017-12-22 16:02:54 -08003908 if (IsUnifiedPlan()) {
3909 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3910 } else {
3911 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3912 }
3913
Steve Antonfa2260d2017-12-28 16:38:23 -08003914 // Intentionally unset the data channel type for RTP data channel with the
3915 // second condition. Otherwise the RTP data channels would be successfully
3916 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3917 // when building with chromium. We want to leave RTP data channels broken, so
3918 // people won't try to use them.
3919 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3920 session_options->data_channel_type = data_channel_type();
3921 }
3922
Steve Antondcc3c022017-12-22 16:02:54 -08003923 // Apply ICE restart flag and renomination flag.
3924 for (auto& options : session_options->media_description_options) {
3925 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3926 options.transport_options.enable_ice_renomination =
3927 configuration_.enable_ice_renomination;
3928 }
3929
3930 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003931 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003932 session_options->pooled_ice_credentials =
3933 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3934 RTC_FROM_HERE,
3935 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3936 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003937 session_options->offer_extmap_allow_mixed =
3938 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003939}
3940
3941void PeerConnection::GetOptionsForPlanBOffer(
3942 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3943 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003944 // Figure out transceiver directional preferences.
3945 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3946 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3947
3948 // By default, generate sendrecv/recvonly m= sections.
3949 bool recv_audio = true;
3950 bool recv_video = true;
3951
3952 // By default, only offer a new m= section if we have media to send with it.
3953 bool offer_new_audio_description = send_audio;
3954 bool offer_new_video_description = send_video;
3955 bool offer_new_data_description = HasDataChannels();
3956
3957 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003958 if (offer_answer_options.offer_to_receive_audio !=
3959 RTCOfferAnswerOptions::kUndefined) {
3960 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003961 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003962 offer_new_audio_description ||
3963 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003964 }
Steve Antondcc3c022017-12-22 16:02:54 -08003965 if (offer_answer_options.offer_to_receive_video !=
3966 RTCOfferAnswerOptions::kUndefined) {
3967 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003968 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003969 offer_new_video_description ||
3970 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003971 }
3972
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003973 absl::optional<size_t> audio_index;
3974 absl::optional<size_t> video_index;
3975 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003976 // If a current description exists, generate m= sections in the same order,
3977 // using the first audio/video/data section that appears and rejecting
3978 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003979 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003980 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003981 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003982 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3983 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3984 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003985 }
3986
zhihuang1c378ed2017-08-17 14:10:50 -07003987 // Add audio/video/data m= sections to the end if needed.
3988 if (!audio_index && offer_new_audio_description) {
3989 session_options->media_description_options.push_back(
3990 cricket::MediaDescriptionOptions(
3991 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003992 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3993 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003994 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003995 }
zhihuang1c378ed2017-08-17 14:10:50 -07003996 if (!video_index && offer_new_video_description) {
3997 session_options->media_description_options.push_back(
3998 cricket::MediaDescriptionOptions(
3999 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08004000 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4001 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004002 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07004003 }
zhihuang1c378ed2017-08-17 14:10:50 -07004004 if (!data_index && offer_new_data_description) {
4005 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004006 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004007 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004008 }
4009
4010 cricket::MediaDescriptionOptions* audio_media_description_options =
4011 !audio_index ? nullptr
4012 : &session_options->media_description_options[*audio_index];
4013 cricket::MediaDescriptionOptions* video_media_description_options =
4014 !video_index ? nullptr
4015 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004016
Steve Anton4171afb2017-11-20 10:20:22 -08004017 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004018 video_media_description_options,
4019 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004020}
4021
Steve Antondcc3c022017-12-22 16:02:54 -08004022static cricket::MediaDescriptionOptions
4023GetMediaDescriptionOptionsForTransceiver(
4024 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4025 transceiver,
4026 const std::string& mid) {
4027 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08004028 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08004029 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08004030 // This behavior is specified in JSEP. The gist is that:
4031 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
4032 // sendrecv.
4033 // 2. If the MSID is included, then it must be included in any subsequent
4034 // offer/answer exactly the same until the RtpTransceiver is stopped.
4035 if (!transceiver->stopped() &&
4036 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
4037 transceiver->internal()->has_ever_been_used_to_send())) {
4038 cricket::SenderOptions sender_options;
4039 sender_options.track_id = transceiver->sender()->id();
4040 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02004041 int num_send_encoding_layers =
4042 transceiver->sender()->init_send_encodings().size();
4043 sender_options.num_sim_layers =
4044 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08004045 media_description_options.sender_options.push_back(sender_options);
4046 }
Steve Antondcc3c022017-12-22 16:02:54 -08004047 return media_description_options;
4048}
4049
Steve Anton5c72e712018-12-10 14:25:30 -08004050// Returns the ContentInfo at mline index |i|, or null if none exists.
4051static const ContentInfo* GetContentByIndex(
4052 const SessionDescriptionInterface* sdesc,
4053 size_t i) {
4054 if (!sdesc) {
4055 return nullptr;
4056 }
4057 const ContentInfos& contents = sdesc->description()->contents();
4058 return (i < contents.size() ? &contents[i] : nullptr);
4059}
4060
Steve Antondcc3c022017-12-22 16:02:54 -08004061void PeerConnection::GetOptionsForUnifiedPlanOffer(
4062 const RTCOfferAnswerOptions& offer_answer_options,
4063 cricket::MediaSessionOptions* session_options) {
4064 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
4065 // Offers) and 5.2.2 (Subsequent Offers).
4066 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
4067 const ContentInfos& local_contents =
4068 (local_description() ? local_description()->description()->contents()
4069 : ContentInfos());
4070 const ContentInfos& remote_contents =
4071 (remote_description() ? remote_description()->description()->contents()
4072 : ContentInfos());
4073 // The mline indices that can be recycled. New transceivers should reuse these
4074 // slots first.
4075 std::queue<size_t> recycleable_mline_indices;
4076 // Track the MIDs used in previous offer/answer exchanges and the current
4077 // offer so that new, unique MIDs are generated.
4078 std::set<std::string> used_mids = seen_mids_;
4079 // First, go through each media section that exists in either the local or
4080 // remote description and generate a media section in this offer for the
4081 // associated transceiver. If a media section can be recycled, generate a
4082 // default, rejected media section here that can be later overwritten.
4083 for (size_t i = 0;
4084 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
4085 // Either |local_content| or |remote_content| is non-null.
4086 const ContentInfo* local_content =
4087 (i < local_contents.size() ? &local_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004088 const ContentInfo* current_local_content =
4089 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-22 16:02:54 -08004090 const ContentInfo* remote_content =
4091 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 14:25:30 -08004092 const ContentInfo* current_remote_content =
4093 GetContentByIndex(current_remote_description(), i);
4094 bool had_been_rejected =
4095 (current_local_content && current_local_content->rejected) ||
4096 (current_remote_content && current_remote_content->rejected);
Steve Antondcc3c022017-12-22 16:02:54 -08004097 const std::string& mid =
4098 (local_content ? local_content->name : remote_content->name);
4099 cricket::MediaType media_type =
4100 (local_content ? local_content->media_description()->type()
4101 : remote_content->media_description()->type());
4102 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4103 media_type == cricket::MEDIA_TYPE_VIDEO) {
4104 auto transceiver = GetAssociatedTransceiver(mid);
4105 RTC_CHECK(transceiver);
4106 // A media section is considered eligible for recycling if it is marked as
Steve Anton5c72e712018-12-10 14:25:30 -08004107 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08004108 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08004109 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08004110 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4111 RtpTransceiverDirection::kInactive,
4112 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08004113 recycleable_mline_indices.push(i);
4114 } else {
4115 session_options->media_description_options.push_back(
4116 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
4117 // CreateOffer shouldn't really cause any state changes in
4118 // PeerConnection, but we need a way to match new transceivers to new
4119 // media sections in SetLocalDescription and JSEP specifies this is done
4120 // by recording the index of the media section generated for the
4121 // transceiver in the offer.
4122 transceiver->internal()->set_mline_index(i);
4123 }
4124 } else {
4125 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004126 RTC_CHECK(GetDataMid());
4127 if (had_been_rejected || mid != *GetDataMid()) {
4128 session_options->media_description_options.push_back(
4129 GetMediaDescriptionOptionsForRejectedData(mid));
4130 } else {
4131 session_options->media_description_options.push_back(
4132 GetMediaDescriptionOptionsForActiveData(mid));
4133 }
Steve Antondcc3c022017-12-22 16:02:54 -08004134 }
4135 }
4136 // Next, look for transceivers that are newly added (that is, are not stopped
4137 // and not associated). Reuse media sections marked as recyclable first,
4138 // otherwise append to the end of the offer. New media sections should be
4139 // added in the order they were added to the PeerConnection.
4140 for (auto transceiver : transceivers_) {
4141 if (transceiver->mid() || transceiver->stopped()) {
4142 continue;
4143 }
4144 size_t mline_index;
4145 if (!recycleable_mline_indices.empty()) {
4146 mline_index = recycleable_mline_indices.front();
4147 recycleable_mline_indices.pop();
4148 session_options->media_description_options[mline_index] =
4149 GetMediaDescriptionOptionsForTransceiver(transceiver,
4150 AllocateMid(&used_mids));
4151 } else {
4152 mline_index = session_options->media_description_options.size();
4153 session_options->media_description_options.push_back(
4154 GetMediaDescriptionOptionsForTransceiver(transceiver,
4155 AllocateMid(&used_mids)));
4156 }
4157 // See comment above for why CreateOffer changes the transceiver's state.
4158 transceiver->internal()->set_mline_index(mline_index);
4159 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004160 // Lastly, add a m-section if we have local data channels and an m section
4161 // does not already exist.
4162 if (!GetDataMid() && HasDataChannels()) {
4163 session_options->media_description_options.push_back(
4164 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4165 }
Steve Antondcc3c022017-12-22 16:02:54 -08004166}
4167
4168void PeerConnection::GetOptionsForAnswer(
4169 const RTCOfferAnswerOptions& offer_answer_options,
4170 cricket::MediaSessionOptions* session_options) {
4171 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4172
4173 if (IsUnifiedPlan()) {
4174 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4175 } else {
4176 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4177 }
4178
Steve Antonfa2260d2017-12-28 16:38:23 -08004179 // Intentionally unset the data channel type for RTP data channel. Otherwise
4180 // the RTP data channels would be successfully negotiated by default and the
4181 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4182 // We want to leave RTP data channels broken, so people won't try to use them.
4183 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4184 session_options->data_channel_type = data_channel_type();
4185 }
4186
Steve Antondcc3c022017-12-22 16:02:54 -08004187 // Apply ICE renomination flag.
4188 for (auto& options : session_options->media_description_options) {
4189 options.transport_options.enable_ice_renomination =
4190 configuration_.enable_ice_renomination;
4191 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004192
4193 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004194 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004195 session_options->pooled_ice_credentials =
4196 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4197 RTC_FROM_HERE,
4198 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4199 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004200}
4201
Steve Antondcc3c022017-12-22 16:02:54 -08004202void PeerConnection::GetOptionsForPlanBAnswer(
4203 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004204 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004205 // Figure out transceiver directional preferences.
4206 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4207 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4208
4209 // By default, generate sendrecv/recvonly m= sections. The direction is also
4210 // restricted by the direction in the offer.
4211 bool recv_audio = true;
4212 bool recv_video = true;
4213
4214 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004215 if (offer_answer_options.offer_to_receive_audio !=
4216 RTCOfferAnswerOptions::kUndefined) {
4217 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004218 }
Steve Antondcc3c022017-12-22 16:02:54 -08004219 if (offer_answer_options.offer_to_receive_video !=
4220 RTCOfferAnswerOptions::kUndefined) {
4221 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004222 }
4223
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004224 absl::optional<size_t> audio_index;
4225 absl::optional<size_t> video_index;
4226 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004227
4228 // Generate m= sections that match those in the offer.
4229 // Note that mediasession.cc will handle intersection our preferred
4230 // direction with the offered direction.
4231 GenerateMediaDescriptionOptions(
4232 remote_description(),
4233 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4234 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4235 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004236
4237 cricket::MediaDescriptionOptions* audio_media_description_options =
4238 !audio_index ? nullptr
4239 : &session_options->media_description_options[*audio_index];
4240 cricket::MediaDescriptionOptions* video_media_description_options =
4241 !video_index ? nullptr
4242 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004243
Steve Anton4171afb2017-11-20 10:20:22 -08004244 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004245 video_media_description_options,
4246 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004247}
zhihuangaf388472016-11-02 16:49:48 -07004248
Steve Antondcc3c022017-12-22 16:02:54 -08004249void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4250 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4251 cricket::MediaSessionOptions* session_options) {
4252 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4253 // Answers) and 5.3.2 (Subsequent Answers).
4254 RTC_DCHECK(remote_description());
4255 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4256 for (const ContentInfo& content :
4257 remote_description()->description()->contents()) {
4258 cricket::MediaType media_type = content.media_description()->type();
4259 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4260 media_type == cricket::MEDIA_TYPE_VIDEO) {
4261 auto transceiver = GetAssociatedTransceiver(content.name);
4262 RTC_CHECK(transceiver);
4263 session_options->media_description_options.push_back(
4264 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4265 } else {
4266 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004267 // Reject all data sections if data channels are disabled.
4268 // Reject a data section if it has already been rejected.
4269 // Reject all data sections except for the first one.
4270 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4271 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004272 session_options->media_description_options.push_back(
4273 GetMediaDescriptionOptionsForRejectedData(content.name));
4274 } else {
4275 session_options->media_description_options.push_back(
4276 GetMediaDescriptionOptionsForActiveData(content.name));
4277 }
Steve Antondcc3c022017-12-22 16:02:54 -08004278 }
4279 }
htaa2a49d92016-03-04 02:51:39 -08004280}
4281
zhihuang1c378ed2017-08-17 14:10:50 -07004282void PeerConnection::GenerateMediaDescriptionOptions(
4283 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004284 RtpTransceiverDirection audio_direction,
4285 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004286 absl::optional<size_t>* audio_index,
4287 absl::optional<size_t>* video_index,
4288 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004289 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004290 for (const cricket::ContentInfo& content :
4291 session_desc->description()->contents()) {
4292 if (IsAudioContent(&content)) {
4293 // If we already have an audio m= section, reject this extra one.
4294 if (*audio_index) {
4295 session_options->media_description_options.push_back(
4296 cricket::MediaDescriptionOptions(
4297 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004298 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004299 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004300 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004301 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004302 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4303 content.name, audio_direction,
4304 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004305 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004306 }
4307 } else if (IsVideoContent(&content)) {
4308 // If we already have an video m= section, reject this extra one.
4309 if (*video_index) {
4310 session_options->media_description_options.push_back(
4311 cricket::MediaDescriptionOptions(
4312 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton5c72e712018-12-10 14:25:30 -08004313 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 14:10:50 -07004314 } else {
Steve Anton5c72e712018-12-10 14:25:30 -08004315 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 14:10:50 -07004316 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 14:25:30 -08004317 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4318 content.name, video_direction,
4319 stopped));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004320 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004321 }
4322 } else {
4323 RTC_DCHECK(IsDataContent(&content));
4324 // If we already have an data m= section, reject this extra one.
4325 if (*data_index) {
4326 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004327 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004328 } else {
4329 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004330 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004331 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004332 }
4333 }
htaa2a49d92016-03-04 02:51:39 -08004334 }
deadbeefab9b2d12015-10-14 11:33:11 -07004335}
4336
Steve Antonfa2260d2017-12-28 16:38:23 -08004337cricket::MediaDescriptionOptions
4338PeerConnection::GetMediaDescriptionOptionsForActiveData(
4339 const std::string& mid) const {
4340 // Direction for data sections is meaningless, but legacy endpoints might
4341 // expect sendrecv.
4342 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4343 RtpTransceiverDirection::kSendRecv,
4344 /*stopped=*/false);
4345 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4346 return options;
4347}
4348
4349cricket::MediaDescriptionOptions
4350PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4351 const std::string& mid) const {
4352 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4353 RtpTransceiverDirection::kInactive,
4354 /*stopped=*/true);
4355 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4356 return options;
4357}
4358
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004359absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004360 switch (data_channel_type_) {
4361 case cricket::DCT_RTP:
4362 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004363 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004364 }
4365 return rtp_data_channel_->content_name();
4366 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004367 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004368 case cricket::DCT_MEDIA_TRANSPORT:
4369 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004370 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004371 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004372 }
4373}
4374
Steve Anton4171afb2017-11-20 10:20:22 -08004375void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4376 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4377 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004378 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004379}
4380
Steve Anton4171afb2017-11-20 10:20:22 -08004381void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004382 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004383 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004384 cricket::MediaType media_type,
4385 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004386 RTC_DCHECK(!IsUnifiedPlan());
4387
Steve Anton4171afb2017-11-20 10:20:22 -08004388 std::vector<RtpSenderInfo>* current_senders =
4389 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004390
Steve Anton4171afb2017-11-20 10:20:22 -08004391 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004392 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004393 for (auto sender_it = current_senders->begin();
4394 sender_it != current_senders->end();
4395 /* incremented manually */) {
4396 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004397 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004398 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004399 std::string params_stream_id;
4400 if (params) {
4401 params_stream_id =
4402 (!params->first_stream_id().empty() ? params->first_stream_id()
4403 : kDefaultStreamId);
4404 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004405 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004406 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004407 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004408 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004409 sender_exists) {
4410 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004411 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004412 OnRemoteSenderRemoved(info, media_type);
4413 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004414 }
4415 }
4416
Steve Anton4171afb2017-11-20 10:20:22 -08004417 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004418 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004419 if (!params.has_ssrcs()) {
4420 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4421 // sender, this means it is coming from a Unified Plan endpoint,so we just
4422 // create a default.
4423 default_sender_needed = true;
4424 break;
4425 }
4426
Seth Hampson845e8782018-03-02 11:34:10 -08004427 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004428 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004429 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4430 // not supported in Plan B, we just take the first here and create the
4431 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004432 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004433 (!params.first_stream_id().empty() ? params.first_stream_id()
4434 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004435 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004436 uint32_t ssrc = params.first_ssrc();
4437
4438 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004439 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004440 if (!stream) {
4441 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004442 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004443 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004444 remote_streams_->AddStream(stream);
4445 new_streams->AddStream(stream);
4446 }
4447
Steve Anton4171afb2017-11-20 10:20:22 -08004448 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004449 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004450 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004451 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004452 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004453 }
4454 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004455
Steve Anton4171afb2017-11-20 10:20:22 -08004456 // Add default sender if necessary.
4457 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004458 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004459 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004460 if (!default_stream) {
4461 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004462 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004463 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004464 remote_streams_->AddStream(default_stream);
4465 new_streams->AddStream(default_stream);
4466 }
Steve Anton4171afb2017-11-20 10:20:22 -08004467 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4468 ? kDefaultAudioSenderId
4469 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004470 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004471 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004472 if (!default_sender_info) {
4473 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004474 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004475 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004476 }
4477 }
deadbeefab9b2d12015-10-14 11:33:11 -07004478}
4479
Steve Anton4171afb2017-11-20 10:20:22 -08004480void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4481 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004482 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4483 << " receiver for track_id=" << sender_info.sender_id
4484 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004485
Steve Anton3d954a62018-04-02 11:27:23 -07004486 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004487 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004488 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004489 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004490 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004491 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004492 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004493 }
4494}
4495
Steve Anton4171afb2017-11-20 10:20:22 -08004496void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4497 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004498 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4499 << " receiver for track_id=" << sender_info.sender_id
4500 << " and stream_id=" << sender_info.stream_id;
4501
Seth Hampson845e8782018-03-02 11:34:10 -08004502 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004503
Henrik Boström933d8b02017-10-10 10:05:16 -07004504 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004505 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004506 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4507 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004508 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004509 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004510 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004511 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004512 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004513 }
4514 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004515 // Stopping or destroying a VideoRtpReceiver will end the
4516 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004517 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004518 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004519 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004520 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004521 // There's no guarantee the track is still available, e.g. the track may
4522 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004523 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004524 }
4525 } else {
nisseede5da42017-01-12 05:15:36 -08004526 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004527 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004528 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004529 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004530 }
deadbeefab9b2d12015-10-14 11:33:11 -07004531}
4532
4533void PeerConnection::UpdateEndedRemoteMediaStreams() {
4534 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4535 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4536 MediaStreamInterface* stream = remote_streams_->at(i);
4537 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4538 streams_to_remove.push_back(stream);
4539 }
4540 }
4541
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004542 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004543 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004544 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004545 }
4546}
4547
Steve Anton4171afb2017-11-20 10:20:22 -08004548void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004549 const std::vector<cricket::StreamParams>& streams,
4550 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004551 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004552
Seth Hampson845e8782018-03-02 11:34:10 -08004553 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004554 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004555 for (auto sender_it = current_senders->begin();
4556 sender_it != current_senders->end();
4557 /* incremented manually */) {
4558 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004559 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004560 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4561 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004562 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004563 OnLocalSenderRemoved(info, media_type);
4564 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004565 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004566 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004567 }
4568 }
4569
Steve Anton4171afb2017-11-20 10:20:22 -08004570 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004571 for (const cricket::StreamParams& params : streams) {
4572 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004573 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004574 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004575 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004576 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004577 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004578 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004579 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004580 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004581 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004582 }
4583 }
4584}
4585
Steve Anton4171afb2017-11-20 10:20:22 -08004586void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4587 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004588 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004589 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004590 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004591 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4592 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004593 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004594 return;
4595 }
4596
deadbeeffac06552015-11-25 11:26:01 -08004597 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004598 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004599 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004600 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004601 }
deadbeeffac06552015-11-25 11:26:01 -08004602
Seth Hampson5b4f0752018-04-02 16:31:36 -07004603 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004604 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004605}
4606
Steve Anton4171afb2017-11-20 10:20:22 -08004607void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4608 cricket::MediaType media_type) {
4609 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004610 if (!sender) {
4611 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004612 // SessionDescriptions has been renegotiated.
4613 return;
4614 }
deadbeeffac06552015-11-25 11:26:01 -08004615
4616 // A sender has been removed from the SessionDescription but it's still
4617 // associated with the PeerConnection. This only occurs if the SDP doesn't
4618 // match with the calls to CreateSender, AddStream and RemoveStream.
4619 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004620 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004621 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004622 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004623 }
deadbeeffac06552015-11-25 11:26:01 -08004624
Steve Anton4171afb2017-11-20 10:20:22 -08004625 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004626}
4627
4628void PeerConnection::UpdateLocalRtpDataChannels(
4629 const cricket::StreamParamsVec& streams) {
4630 std::vector<std::string> existing_channels;
4631
4632 // Find new and active data channels.
4633 for (const cricket::StreamParams& params : streams) {
4634 // |it->sync_label| is actually the data channel label. The reason is that
4635 // we use the same naming of data channels as we do for
4636 // MediaStreams and Tracks.
4637 // For MediaStreams, the sync_label is the MediaStream label and the
4638 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004639 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004640 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004641 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004642 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004643 continue;
4644 }
4645 // Set the SSRC the data channel should use for sending.
4646 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4647 existing_channels.push_back(data_channel_it->first);
4648 }
4649
4650 UpdateClosingRtpDataChannels(existing_channels, true);
4651}
4652
4653void PeerConnection::UpdateRemoteRtpDataChannels(
4654 const cricket::StreamParamsVec& streams) {
4655 std::vector<std::string> existing_channels;
4656
4657 // Find new and active data channels.
4658 for (const cricket::StreamParams& params : streams) {
4659 // The data channel label is either the mslabel or the SSRC if the mslabel
4660 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004661 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004662 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004663 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004664 auto data_channel_it = rtp_data_channels_.find(label);
4665 if (data_channel_it == rtp_data_channels_.end()) {
4666 // This is a new data channel.
4667 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4668 } else {
4669 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4670 }
4671 existing_channels.push_back(label);
4672 }
4673
4674 UpdateClosingRtpDataChannels(existing_channels, false);
4675}
4676
4677void PeerConnection::UpdateClosingRtpDataChannels(
4678 const std::vector<std::string>& active_channels,
4679 bool is_local_update) {
4680 auto it = rtp_data_channels_.begin();
4681 while (it != rtp_data_channels_.end()) {
4682 DataChannel* data_channel = it->second;
4683 if (std::find(active_channels.begin(), active_channels.end(),
4684 data_channel->label()) != active_channels.end()) {
4685 ++it;
4686 continue;
4687 }
4688
4689 if (is_local_update) {
4690 data_channel->SetSendSsrc(0);
4691 } else {
4692 data_channel->RemotePeerRequestClose();
4693 }
4694
4695 if (data_channel->state() == DataChannel::kClosed) {
4696 rtp_data_channels_.erase(it);
4697 it = rtp_data_channels_.begin();
4698 } else {
4699 ++it;
4700 }
4701 }
4702}
4703
4704void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4705 uint32_t remote_ssrc) {
4706 rtc::scoped_refptr<DataChannel> channel(
4707 InternalCreateDataChannel(label, nullptr));
4708 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004709 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004710 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004711 return;
4712 }
4713 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004714 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4715 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004716 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004717}
4718
4719rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4720 const std::string& label,
4721 const InternalDataChannelInit* config) {
4722 if (IsClosed()) {
4723 return nullptr;
4724 }
Steve Anton75737c02017-11-06 10:37:17 -08004725 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004726 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004727 << "InternalCreateDataChannel: Data is not supported in this call.";
4728 return nullptr;
4729 }
4730 InternalDataChannelInit new_config =
4731 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004732 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004733 if (new_config.id < 0) {
4734 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004735 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004736 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004737 RTC_LOG(LS_ERROR)
4738 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004739 return nullptr;
4740 }
4741 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004742 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004743 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004744 return nullptr;
4745 }
4746 }
4747
Steve Anton75737c02017-11-06 10:37:17 -08004748 rtc::scoped_refptr<DataChannel> channel(
4749 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004750 if (!channel) {
4751 sid_allocator_.ReleaseSid(new_config.id);
4752 return nullptr;
4753 }
4754
4755 if (channel->data_channel_type() == cricket::DCT_RTP) {
4756 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004757 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4758 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004759 return nullptr;
4760 }
4761 rtp_data_channels_[channel->label()] = channel;
4762 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004763 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004764 sctp_data_channels_.push_back(channel);
4765 channel->SignalClosed.connect(this,
4766 &PeerConnection::OnSctpDataChannelClosed);
4767 }
4768
Steve Anton2d8609c2018-01-23 16:38:46 -08004769 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004770 return channel;
4771}
4772
4773bool PeerConnection::HasDataChannels() const {
4774 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4775}
4776
4777void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4778 for (const auto& channel : sctp_data_channels_) {
4779 if (channel->id() < 0) {
4780 int sid;
4781 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004782 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004783 continue;
4784 }
4785 channel->SetSctpSid(sid);
4786 }
4787 }
4788}
4789
4790void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004791 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004792 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4793 ++it) {
4794 if (it->get() == channel) {
4795 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004796 // After the closing procedure is done, it's safe to use this ID for
4797 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004798 sid_allocator_.ReleaseSid(channel->id());
4799 }
deadbeefbd292462015-12-14 18:15:29 -08004800 // Since this method is triggered by a signal from the DataChannel,
4801 // we can't free it directly here; we need to free it asynchronously.
4802 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004803 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004804 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4805 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004806 return;
4807 }
4808 }
4809}
4810
deadbeefab9b2d12015-10-14 11:33:11 -07004811void PeerConnection::OnDataChannelDestroyed() {
4812 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4813 // DataChannel may callback to us and try to modify the list.
4814 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4815 temp_rtp_dcs.swap(rtp_data_channels_);
4816 for (const auto& kv : temp_rtp_dcs) {
4817 kv.second->OnTransportChannelDestroyed();
4818 }
4819
4820 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4821 temp_sctp_dcs.swap(sctp_data_channels_);
4822 for (const auto& channel : temp_sctp_dcs) {
4823 channel->OnTransportChannelDestroyed();
4824 }
4825}
4826
4827void PeerConnection::OnDataChannelOpenMessage(
4828 const std::string& label,
4829 const InternalDataChannelInit& config) {
4830 rtc::scoped_refptr<DataChannel> channel(
4831 InternalCreateDataChannel(label, &config));
4832 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004833 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004834 return;
4835 }
4836
deadbeefa601f5c2016-06-06 14:27:39 -07004837 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4838 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004839 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004840 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004841}
4842
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004843bool PeerConnection::HandleOpenMessage_s(
4844 const cricket::ReceiveDataParams& params,
4845 const rtc::CopyOnWriteBuffer& buffer) {
4846 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4847 // Received OPEN message; parse and signal that a new data channel should
4848 // be created.
4849 std::string label;
4850 InternalDataChannelInit config;
4851 config.id = params.ssrc;
4852 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4853 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4854 << params.ssrc;
4855 return true;
4856 }
4857 config.open_handshake_role = InternalDataChannelInit::kAcker;
4858 OnDataChannelOpenMessage(label, config);
4859 return true;
4860 }
4861 return false;
4862}
4863
Steve Anton4171afb2017-11-20 10:20:22 -08004864rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4865PeerConnection::GetAudioTransceiver() const {
4866 // This method only works with Plan B SDP, where there is a single
4867 // audio/video transceiver.
4868 RTC_DCHECK(!IsUnifiedPlan());
4869 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004870 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004871 return transceiver;
4872 }
4873 }
4874 RTC_NOTREACHED();
4875 return nullptr;
4876}
4877
4878rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4879PeerConnection::GetVideoTransceiver() const {
4880 // This method only works with Plan B SDP, where there is a single
4881 // audio/video transceiver.
4882 RTC_DCHECK(!IsUnifiedPlan());
4883 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004884 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004885 return transceiver;
4886 }
4887 }
4888 RTC_NOTREACHED();
4889 return nullptr;
4890}
4891
4892// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4893// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004894bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004895 switch (type) {
4896 case cricket::MEDIA_TYPE_AUDIO:
4897 return !GetAudioTransceiver()->internal()->senders().empty();
4898 case cricket::MEDIA_TYPE_VIDEO:
4899 return !GetVideoTransceiver()->internal()->senders().empty();
4900 case cricket::MEDIA_TYPE_DATA:
4901 return false;
4902 }
4903 RTC_NOTREACHED();
4904 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004905}
4906
Steve Anton4171afb2017-11-20 10:20:22 -08004907rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4908PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4909 for (auto transceiver : transceivers_) {
4910 for (auto sender : transceiver->internal()->senders()) {
4911 if (sender->track() == track) {
4912 return sender;
4913 }
4914 }
4915 }
4916 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004917}
4918
Steve Anton4171afb2017-11-20 10:20:22 -08004919rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4920PeerConnection::FindSenderById(const std::string& sender_id) const {
4921 for (auto transceiver : transceivers_) {
4922 for (auto sender : transceiver->internal()->senders()) {
4923 if (sender->id() == sender_id) {
4924 return sender;
4925 }
4926 }
4927 }
4928 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004929}
4930
Steve Anton4171afb2017-11-20 10:20:22 -08004931rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4932PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4933 for (auto transceiver : transceivers_) {
4934 for (auto receiver : transceiver->internal()->receivers()) {
4935 if (receiver->id() == receiver_id) {
4936 return receiver;
4937 }
4938 }
4939 }
4940 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004941}
4942
Steve Anton4171afb2017-11-20 10:20:22 -08004943std::vector<PeerConnection::RtpSenderInfo>*
4944PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4945 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4946 media_type == cricket::MEDIA_TYPE_VIDEO);
4947 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4948 ? &remote_audio_sender_infos_
4949 : &remote_video_sender_infos_;
4950}
4951
4952std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004953 cricket::MediaType media_type) {
4954 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4955 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004956 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4957 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004958}
4959
Steve Anton4171afb2017-11-20 10:20:22 -08004960const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4961 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004962 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004963 const std::string sender_id) const {
4964 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004965 if (sender_info.stream_id == stream_id &&
4966 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004967 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004968 }
4969 }
4970 return nullptr;
4971}
4972
4973DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4974 for (const auto& channel : sctp_data_channels_) {
4975 if (channel->id() == sid) {
4976 return channel;
4977 }
4978 }
4979 return nullptr;
4980}
4981
deadbeef91dd5672016-05-18 16:55:30 -07004982bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004983 const cricket::ServerAddresses& stun_servers,
4984 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004985 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004986 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004987 // To handle both internal and externally created port allocator, we will
4988 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004989 port_allocator_flags_ = port_allocator_->flags();
4990 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4991 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4992 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004993 // If the disable-IPv6 flag was specified, we'll not override it
4994 // by experiment.
4995 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004996 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004997 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4998 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004999 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005000 }
5001
zhihuangb09b3f92017-03-07 14:40:51 -08005002 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005003 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01005004 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08005005 }
5006
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005007 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005008 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005009 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005010 }
5011
honghaiz60347052016-05-31 18:29:12 -07005012 if (configuration.candidate_network_policy ==
5013 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005014 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01005015 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07005016 }
5017
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005018 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07005019 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01005020 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5021 }
5022
Qingsi Wanga2d60672018-04-11 16:57:45 -07005023 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005024 // No step delay is used while allocating ports.
5025 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
5026 port_allocator_->set_candidate_filter(
5027 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07005028 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005029
Harald Alvestrandb2a74782018-06-28 13:54:07 +02005030 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07005031 for (auto& turn_server : turn_servers_copy) {
5032 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07005033 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005034 // Call this last since it may create pooled allocator sessions using the
5035 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005036 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005037 stun_servers, std::move(turn_servers_copy),
5038 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
5039 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005040 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005041 return true;
5042}
5043
deadbeef91dd5672016-05-18 16:55:30 -07005044bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08005045 const cricket::ServerAddresses& stun_servers,
5046 const std::vector<cricket::RelayServerConfig>& turn_servers,
5047 IceTransportsType type,
5048 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02005049 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005050 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005051 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005052 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08005053 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07005054 // According to JSEP, after setLocalDescription, changing the candidate pool
5055 // size is not allowed, and changing the set of ICE servers will not result
5056 // in new candidates being gathered.
5057 if (local_description()) {
5058 port_allocator_->FreezeCandidatePool();
5059 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07005060 // Add the custom tls turn servers if they exist.
5061 auto turn_servers_copy = turn_servers;
5062 for (auto& turn_server : turn_servers_copy) {
5063 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
5064 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005065 // Call this last since it may create pooled allocator sessions using the
5066 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08005067 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07005068 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5069 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07005070}
5071
Steve Antonba818672017-11-06 10:21:57 -08005072cricket::ChannelManager* PeerConnection::channel_manager() const {
5073 return factory_->channel_manager();
5074}
5075
Elad Alon99c3fe52017-10-13 16:29:40 +02005076bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01005077 std::unique_ptr<RtcEventLogOutput> output,
5078 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08005079 if (!event_log_) {
5080 return false;
5081 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01005082 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07005083}
5084
5085void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08005086 if (event_log_) {
5087 event_log_->StopLogging();
5088 }
ivoc14d5dbe2016-07-04 07:06:55 -07005089}
nisseeaabdf62017-05-05 02:23:02 -07005090
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005091cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08005092 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08005093 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005094 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08005095 if (channel && channel->content_name() == content_name) {
5096 return channel;
5097 }
Steve Anton75737c02017-11-06 10:37:17 -08005098 }
5099 if (rtp_data_channel() &&
5100 rtp_data_channel()->content_name() == content_name) {
5101 return rtp_data_channel();
5102 }
5103 return nullptr;
5104}
5105
5106bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005107 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005108 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005109 RTC_LOG(LS_INFO)
5110 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005111 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005112 return false;
5113 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005114 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005115 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005116 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08005117 return false;
5118 }
5119
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005120 absl::optional<rtc::SSLRole> dtls_role;
5121 if (sctp_mid_) {
5122 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
5123 } else if (is_caller_) {
5124 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
5125 }
Zhi Huange830e682018-03-30 10:48:35 -07005126 if (dtls_role) {
5127 *role = *dtls_role;
5128 return true;
5129 }
5130 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005131}
5132
5133bool PeerConnection::GetSslRole(const std::string& content_name,
5134 rtc::SSLRole* role) {
5135 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005136 RTC_LOG(LS_INFO)
5137 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005138 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005139 return false;
5140 }
5141
Zhi Huange830e682018-03-30 10:48:35 -07005142 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5143 if (dtls_role) {
5144 *role = *dtls_role;
5145 return true;
5146 }
5147 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005148}
5149
Steve Antonf8470812017-12-04 10:46:21 -08005150void PeerConnection::SetSessionError(SessionError error,
5151 const std::string& error_desc) {
5152 RTC_DCHECK_RUN_ON(signaling_thread());
5153 if (error != session_error_) {
5154 session_error_ = error;
5155 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005156 }
5157}
5158
Zhi Huange830e682018-03-30 10:48:35 -07005159RTCError PeerConnection::UpdateSessionState(
5160 SdpType type,
5161 cricket::ContentSource source,
5162 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005163 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005164
5165 // If there's already a pending error then no state transition should happen.
5166 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005167 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005168
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005169 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005170 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005171 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005172 }
5173
5174 // Update the signaling state according to the specified state machine (see
5175 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005176 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005177 ChangeSignalingState(source == cricket::CS_LOCAL
5178 ? PeerConnectionInterface::kHaveLocalOffer
5179 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005180 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005181 ChangeSignalingState(source == cricket::CS_LOCAL
5182 ? PeerConnectionInterface::kHaveLocalPrAnswer
5183 : PeerConnectionInterface::kHaveRemotePrAnswer);
5184 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005185 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005186 ChangeSignalingState(PeerConnectionInterface::kStable);
5187 }
5188
5189 // Update internal objects according to the session description's media
5190 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005191 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005192 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005193 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005194 }
5195
Steve Anton8a006912017-12-04 15:25:56 -08005196 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005197}
5198
Steve Anton8a006912017-12-04 15:25:56 -08005199RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005200 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005201 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005202 const SessionDescriptionInterface* sdesc =
5203 (source == cricket::CS_LOCAL ? local_description()
5204 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005205 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005206
5207 // Push down the new SDP media section for each audio/video transceiver.
5208 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005209 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005210 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005211 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005212 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005213 continue;
5214 }
5215 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005216 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005217 if (!content_desc) {
5218 continue;
5219 }
5220 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005221 bool success = (source == cricket::CS_LOCAL)
5222 ? channel->SetLocalContent(content_desc, type, &error)
5223 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005224 if (!success) {
5225 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5226 }
5227 }
5228
5229 // If using the RtpDataChannel, push down the new SDP section for it too.
5230 if (rtp_data_channel_) {
5231 const ContentInfo* data_content =
5232 cricket::GetFirstDataContent(sdesc->description());
5233 if (data_content && !data_content->rejected) {
5234 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005235 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005236 if (data_desc) {
5237 std::string error;
5238 bool success =
5239 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005240 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005241 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005242 if (!success) {
5243 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5244 std::move(error));
5245 }
Steve Anton75737c02017-11-06 10:37:17 -08005246 }
5247 }
5248 }
Steve Antoned10bd92017-12-05 10:52:59 -08005249
Steve Anton75737c02017-11-06 10:37:17 -08005250 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5251 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5252 if (sctp_transport_ && local_description() && remote_description() &&
5253 cricket::GetFirstDataContent(local_description()->description()) &&
5254 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005255 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005256 RTC_FROM_HERE,
5257 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005258 if (!success) {
5259 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5260 "Failed to push down SCTP parameters.");
5261 }
Steve Anton75737c02017-11-06 10:37:17 -08005262 }
Steve Antoned10bd92017-12-05 10:52:59 -08005263
Steve Anton8a006912017-12-04 15:25:56 -08005264 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005265}
5266
5267bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5268 RTC_DCHECK(network_thread()->IsCurrent());
5269 RTC_DCHECK(local_description());
5270 RTC_DCHECK(remote_description());
5271 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5272 // When we support "max-message-size", that would also be pushed down here.
5273 return sctp_transport_->Start(
5274 GetSctpPort(local_description()->description()),
5275 GetSctpPort(remote_description()->description()));
5276}
5277
Steve Anton8a006912017-12-04 15:25:56 -08005278RTCError PeerConnection::PushdownTransportDescription(
5279 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005280 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005281 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005282
Zhi Huange830e682018-03-30 10:48:35 -07005283 if (source == cricket::CS_LOCAL) {
5284 const SessionDescriptionInterface* sdesc = local_description();
5285 RTC_DCHECK(sdesc);
5286 return transport_controller_->SetLocalDescription(type,
5287 sdesc->description());
5288 } else {
5289 const SessionDescriptionInterface* sdesc = remote_description();
5290 RTC_DCHECK(sdesc);
5291 return transport_controller_->SetRemoteDescription(type,
5292 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005293 }
Steve Anton75737c02017-11-06 10:37:17 -08005294}
5295
5296bool PeerConnection::GetTransportDescription(
5297 const SessionDescription* description,
5298 const std::string& content_name,
5299 cricket::TransportDescription* tdesc) {
5300 if (!description || !tdesc) {
5301 return false;
5302 }
5303 const TransportInfo* transport_info =
5304 description->GetTransportInfoByName(content_name);
5305 if (!transport_info) {
5306 return false;
5307 }
5308 *tdesc = transport_info->description;
5309 return true;
5310}
5311
Steve Anton75737c02017-11-06 10:37:17 -08005312cricket::IceConfig PeerConnection::ParseIceConfig(
5313 const PeerConnectionInterface::RTCConfiguration& config) const {
5314 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005315 switch (config.continual_gathering_policy) {
5316 case PeerConnectionInterface::GATHER_ONCE:
5317 gathering_policy = cricket::GATHER_ONCE;
5318 break;
5319 case PeerConnectionInterface::GATHER_CONTINUALLY:
5320 gathering_policy = cricket::GATHER_CONTINUALLY;
5321 break;
5322 default:
5323 RTC_NOTREACHED();
5324 gathering_policy = cricket::GATHER_ONCE;
5325 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005326
Steve Anton75737c02017-11-06 10:37:17 -08005327 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005328 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5329 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005330 ice_config.prioritize_most_likely_candidate_pairs =
5331 config.prioritize_most_likely_ice_candidate_pairs;
5332 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005333 RTCConfigurationToIceConfigOptionalInt(
5334 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005335 ice_config.continual_gathering_policy = gathering_policy;
5336 ice_config.presume_writable_when_fully_relayed =
5337 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005338 ice_config.ice_check_interval_strong_connectivity =
5339 config.ice_check_interval_strong_connectivity;
5340 ice_config.ice_check_interval_weak_connectivity =
5341 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005342 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-29 23:08:51 -08005343 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5344 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-06 23:30:17 -08005345 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005346 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005347 ice_config.regather_all_networks_interval_range =
5348 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005349 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005350 return ice_config;
5351}
5352
Steve Antona41959e2018-11-28 11:15:33 -08005353static absl::string_view GetTrackIdBySsrc(
5354 const SessionDescriptionInterface* session_description,
5355 uint32_t ssrc) {
5356 if (!session_description) {
5357 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005358 }
Steve Antona41959e2018-11-28 11:15:33 -08005359 for (const cricket::ContentInfo& content :
5360 session_description->description()->contents()) {
5361 const cricket::MediaContentDescription& media =
5362 *content.media_description();
5363 if (media.type() == cricket::MEDIA_TYPE_AUDIO ||
5364 media.type() == cricket::MEDIA_TYPE_VIDEO) {
5365 const cricket::StreamParams* stream_params =
5366 cricket::GetStreamBySsrc(media.streams(), ssrc);
5367 if (stream_params) {
5368 return stream_params->id;
5369 }
5370 }
5371 }
5372 return {};
Steve Anton75737c02017-11-06 10:37:17 -08005373}
5374
Steve Antona41959e2018-11-28 11:15:33 -08005375absl::string_view PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc) {
5376 return GetTrackIdBySsrc(local_description(), ssrc);
5377}
5378
5379absl::string_view PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc) {
5380 return GetTrackIdBySsrc(remote_description(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -08005381}
5382
5383bool PeerConnection::SendData(const cricket::SendDataParams& params,
5384 const rtc::CopyOnWriteBuffer& payload,
5385 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005386 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5387 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5388 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005389 return false;
5390 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005391 if (media_transport_) {
5392 SendDataParams send_params;
5393 send_params.type = ToWebrtcDataMessageType(params.type);
5394 send_params.ordered = params.ordered;
5395 if (params.max_rtx_count >= 0) {
5396 send_params.max_rtx_count = params.max_rtx_count;
5397 } else if (params.max_rtx_ms >= 0) {
5398 send_params.max_rtx_ms = params.max_rtx_ms;
5399 }
5400 return media_transport_->SendData(params.sid, send_params, payload).ok();
5401 }
Steve Anton75737c02017-11-06 10:37:17 -08005402 return rtp_data_channel_
5403 ? rtp_data_channel_->SendData(params, payload, result)
5404 : network_thread()->Invoke<bool>(
5405 RTC_FROM_HERE,
5406 Bind(&cricket::SctpTransportInternal::SendData,
5407 sctp_transport_.get(), params, payload, result));
5408}
5409
5410bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005411 RTC_DCHECK_RUN_ON(signaling_thread());
5412 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005413 // Don't log an error here, because DataChannels are expected to call
5414 // ConnectDataChannel in this state. It's the only way to initially tell
5415 // whether or not the underlying transport is ready.
5416 return false;
5417 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005418 if (media_transport_) {
5419 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5420 &DataChannel::OnChannelReady);
5421 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5422 &DataChannel::OnDataReceived);
5423 SignalMediaTransportChannelClosing_s.connect(
5424 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5425 SignalMediaTransportChannelClosed_s.connect(
5426 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5427 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005428 rtp_data_channel_->SignalReadyToSendData.connect(
5429 webrtc_data_channel, &DataChannel::OnChannelReady);
5430 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5431 &DataChannel::OnDataReceived);
5432 } else {
5433 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5434 &DataChannel::OnChannelReady);
5435 SignalSctpDataReceived.connect(webrtc_data_channel,
5436 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005437 SignalSctpClosingProcedureStartedRemotely.connect(
5438 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5439 SignalSctpClosingProcedureComplete.connect(
5440 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005441 }
5442 return true;
5443}
5444
5445void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005446 RTC_DCHECK_RUN_ON(signaling_thread());
5447 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005448 RTC_LOG(LS_ERROR)
5449 << "DisconnectDataChannel called when rtp_data_channel_ and "
5450 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005451 return;
5452 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005453 if (media_transport_) {
5454 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5455 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5456 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5457 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5458 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005459 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5460 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5461 } else {
5462 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5463 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005464 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5465 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005466 }
5467}
5468
5469void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005470 if (media_transport_) {
5471 // No-op. Media transport does not need to add streams.
5472 return;
5473 }
Steve Anton75737c02017-11-06 10:37:17 -08005474 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005475 RTC_LOG(LS_ERROR)
5476 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005477 return;
5478 }
5479 network_thread()->Invoke<void>(
5480 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5481 sctp_transport_.get(), sid));
5482}
5483
5484void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005485 if (media_transport_) {
5486 media_transport_->CloseChannel(sid);
5487 return;
5488 }
Steve Anton75737c02017-11-06 10:37:17 -08005489 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005490 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005491 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005492 return;
5493 }
5494 network_thread()->Invoke<void>(
5495 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5496 sctp_transport_.get(), sid));
5497}
5498
5499bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005500 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005501 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005502 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005503 sctp_ready_to_send_data_;
5504}
5505
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005506void PeerConnection::OnDataReceived(int channel_id,
5507 DataMessageType type,
5508 const rtc::CopyOnWriteBuffer& buffer) {
5509 cricket::ReceiveDataParams params;
5510 params.sid = channel_id;
5511 params.type = ToCricketDataMessageType(type);
5512 media_transport_invoker_->AsyncInvoke<void>(
5513 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5514 RTC_DCHECK_RUN_ON(signaling_thread());
5515 if (!HandleOpenMessage_s(params, buffer)) {
5516 SignalMediaTransportReceivedData_s(params, buffer);
5517 }
5518 });
5519}
5520
5521void PeerConnection::OnChannelClosing(int channel_id) {
5522 media_transport_invoker_->AsyncInvoke<void>(
5523 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5524 RTC_DCHECK_RUN_ON(signaling_thread());
5525 SignalMediaTransportChannelClosing_s(channel_id);
5526 });
5527}
5528
5529void PeerConnection::OnChannelClosed(int channel_id) {
5530 media_transport_invoker_->AsyncInvoke<void>(
5531 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5532 RTC_DCHECK_RUN_ON(signaling_thread());
5533 SignalMediaTransportChannelClosed_s(channel_id);
5534 });
5535}
5536
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005537absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005538 if (sctp_mid_ && transport_controller_) {
5539 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5540 if (dtls_transport) {
5541 return dtls_transport->transport_name();
5542 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005543 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005544 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005545 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005546}
5547
Qingsi Wang72a43a12018-02-20 16:03:18 -08005548cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5549 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005550 network_thread()->Invoke<void>(
5551 RTC_FROM_HERE,
5552 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5553 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005554 return candidate_states_list;
5555}
5556
Steve Anton5dfde182018-02-06 10:34:40 -08005557std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5558 const {
5559 std::map<std::string, std::string> transport_names_by_mid;
5560 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005561 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005562 if (channel) {
5563 transport_names_by_mid[channel->content_name()] =
5564 channel->transport_name();
5565 }
Steve Anton75737c02017-11-06 10:37:17 -08005566 }
Steve Anton5dfde182018-02-06 10:34:40 -08005567 if (rtp_data_channel_) {
5568 transport_names_by_mid[rtp_data_channel_->content_name()] =
5569 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005570 }
5571 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005572 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005573 RTC_DCHECK(transport_name);
5574 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005575 }
Steve Anton5dfde182018-02-06 10:34:40 -08005576 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005577}
5578
Steve Anton5dfde182018-02-06 10:34:40 -08005579std::map<std::string, cricket::TransportStats>
5580PeerConnection::GetTransportStatsByNames(
5581 const std::set<std::string>& transport_names) {
5582 if (!network_thread()->IsCurrent()) {
5583 return network_thread()
5584 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5585 RTC_FROM_HERE,
5586 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005587 }
Steve Anton5dfde182018-02-06 10:34:40 -08005588 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5589 for (const std::string& transport_name : transport_names) {
5590 cricket::TransportStats transport_stats;
5591 bool success =
5592 transport_controller_->GetStats(transport_name, &transport_stats);
5593 if (success) {
5594 transport_stats_by_name[transport_name] = std::move(transport_stats);
5595 } else {
5596 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5597 << transport_name;
5598 }
5599 }
5600 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005601}
5602
5603bool PeerConnection::GetLocalCertificate(
5604 const std::string& transport_name,
5605 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005606 if (!certificate) {
5607 return false;
5608 }
5609 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5610 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005611}
5612
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005613std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005614 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005615 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005616}
5617
5618cricket::DataChannelType PeerConnection::data_channel_type() const {
5619 return data_channel_type_;
5620}
5621
5622bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5623 return pending_ice_restarts_.find(content_name) !=
5624 pending_ice_restarts_.end();
5625}
5626
Steve Anton75737c02017-11-06 10:37:17 -08005627bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5628 return transport_controller_->NeedsIceRestart(content_name);
5629}
5630
5631void PeerConnection::OnCertificateReady(
5632 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5633 transport_controller_->SetLocalCertificate(certificate);
5634}
5635
5636void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005637 SetSessionError(SessionError::kTransport,
5638 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005639}
5640
Alex Loiko9289eda2018-11-23 16:18:59 +00005641void PeerConnection::OnTransportControllerConnectionState(
5642 cricket::IceConnectionState state) {
5643 switch (state) {
5644 case cricket::kIceConnectionConnecting:
5645 // If the current state is Connected or Completed, then there were
5646 // writable channels but now there are not, so the next state must
5647 // be Disconnected.
5648 // kIceConnectionConnecting is currently used as the default,
5649 // un-connected state by the TransportController, so its only use is
5650 // detecting disconnections.
5651 if (ice_connection_state_ ==
5652 PeerConnectionInterface::kIceConnectionConnected ||
5653 ice_connection_state_ ==
5654 PeerConnectionInterface::kIceConnectionCompleted) {
5655 SetIceConnectionState(
5656 PeerConnectionInterface::kIceConnectionDisconnected);
5657 }
5658 break;
5659 case cricket::kIceConnectionFailed:
5660 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5661 break;
5662 case cricket::kIceConnectionConnected:
5663 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
5664 "all transports are writable.";
5665 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5666 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5667 break;
5668 case cricket::kIceConnectionCompleted:
5669 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
5670 "all transports are complete.";
5671 if (ice_connection_state_ !=
5672 PeerConnectionInterface::kIceConnectionConnected) {
5673 // If jumping directly from "checking" to "connected",
5674 // signal "connected" first.
5675 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5676 }
5677 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
5678 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
5679 ReportTransportStats();
5680 break;
5681 default:
5682 RTC_NOTREACHED();
5683 }
5684}
5685
Steve Anton75737c02017-11-06 10:37:17 -08005686void PeerConnection::OnTransportControllerCandidatesGathered(
5687 const std::string& transport_name,
5688 const cricket::Candidates& candidates) {
5689 RTC_DCHECK(signaling_thread()->IsCurrent());
5690 int sdp_mline_index;
5691 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005692 RTC_LOG(LS_ERROR)
5693 << "OnTransportControllerCandidatesGathered: content name "
5694 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005695 return;
5696 }
5697
5698 for (cricket::Candidates::const_iterator citer = candidates.begin();
5699 citer != candidates.end(); ++citer) {
5700 // Use transport_name as the candidate media id.
5701 std::unique_ptr<JsepIceCandidate> candidate(
5702 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5703 if (local_description()) {
5704 mutable_local_description()->AddCandidate(candidate.get());
5705 }
5706 OnIceCandidate(std::move(candidate));
5707 }
5708}
5709
5710void PeerConnection::OnTransportControllerCandidatesRemoved(
5711 const std::vector<cricket::Candidate>& candidates) {
5712 RTC_DCHECK(signaling_thread()->IsCurrent());
5713 // Sanity check.
5714 for (const cricket::Candidate& candidate : candidates) {
5715 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005716 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005717 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005718 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005719 return;
5720 }
5721 }
5722
5723 if (local_description()) {
5724 mutable_local_description()->RemoveCandidates(candidates);
5725 }
5726 OnIceCandidatesRemoved(candidates);
5727}
5728
5729void PeerConnection::OnTransportControllerDtlsHandshakeError(
5730 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005731 RTC_HISTOGRAM_ENUMERATION(
5732 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5733 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005734}
5735
Steve Antoned10bd92017-12-05 10:52:59 -08005736void PeerConnection::EnableSending() {
5737 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005738 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005739 if (channel && !channel->enabled()) {
5740 channel->Enable(true);
5741 }
Steve Anton75737c02017-11-06 10:37:17 -08005742 }
5743
Steve Anton4171afb2017-11-20 10:20:22 -08005744 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005745 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005746 }
Steve Anton75737c02017-11-06 10:37:17 -08005747}
5748
5749// Returns the media index for a local ice candidate given the content name.
5750bool PeerConnection::GetLocalCandidateMediaIndex(
5751 const std::string& content_name,
5752 int* sdp_mline_index) {
5753 if (!local_description() || !sdp_mline_index) {
5754 return false;
5755 }
5756
5757 bool content_found = false;
5758 const ContentInfos& contents = local_description()->description()->contents();
5759 for (size_t index = 0; index < contents.size(); ++index) {
5760 if (contents[index].name == content_name) {
5761 *sdp_mline_index = static_cast<int>(index);
5762 content_found = true;
5763 break;
5764 }
5765 }
5766 return content_found;
5767}
5768
5769bool PeerConnection::UseCandidatesInSessionDescription(
5770 const SessionDescriptionInterface* remote_desc) {
5771 if (!remote_desc) {
5772 return true;
5773 }
5774 bool ret = true;
5775
5776 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5777 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5778 for (size_t n = 0; n < candidates->count(); ++n) {
5779 const IceCandidateInterface* candidate = candidates->at(n);
5780 bool valid = false;
5781 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5782 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005783 RTC_LOG(LS_INFO)
5784 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005785 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005786 }
5787 continue;
5788 }
5789 ret = UseCandidate(candidate);
5790 if (!ret) {
5791 break;
5792 }
5793 }
5794 }
5795 return ret;
5796}
5797
5798bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5799 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5800 size_t remote_content_size =
5801 remote_description()->description()->contents().size();
5802 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005803 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005804 return false;
5805 }
5806
5807 cricket::ContentInfo content =
5808 remote_description()->description()->contents()[mediacontent_index];
5809 std::vector<cricket::Candidate> candidates;
5810 candidates.push_back(candidate->candidate());
5811 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005812 RTCError error =
5813 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005814 if (error.ok()) {
5815 // Candidates successfully submitted for checking.
5816 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5817 ice_connection_state_ ==
5818 PeerConnectionInterface::kIceConnectionDisconnected) {
5819 // If state is New, then the session has just gotten its first remote ICE
5820 // candidates, so go to Checking.
5821 // If state is Disconnected, the session is re-using old candidates or
5822 // receiving additional ones, so go to Checking.
5823 // If state is Connected, stay Connected.
5824 // TODO(bemasc): If state is Connected, and the new candidates are for a
5825 // newly added transport, then the state actually _should_ move to
5826 // checking. Add a way to distinguish that case.
5827 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5828 }
5829 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005830 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005831 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005832 }
5833 return true;
5834}
5835
5836void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005837 // Destroy video channel first since it may have a pointer to the
5838 // voice channel.
5839 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005840 if (!video_info || video_info->rejected) {
5841 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005842 }
5843
Steve Anton6fec8802017-12-04 10:37:29 -08005844 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5845 if (!audio_info || audio_info->rejected) {
5846 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005847 }
5848
5849 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5850 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005851 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005852 }
5853}
5854
Steve Antondcc3c022017-12-22 16:02:54 -08005855RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5856 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005857 const cricket::ContentGroup* bundle_group = nullptr;
5858 if (configuration_.bundle_policy ==
5859 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005860 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005861 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005862 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5863 "max-bundle configured but session description "
5864 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005865 }
5866 }
Steve Antondcc3c022017-12-22 16:02:54 -08005867 return std::move(bundle_group);
5868}
5869
5870RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005871 // Creating the media channels. Transports should already have been created
5872 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005873 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005874 if (voice && !voice->rejected &&
5875 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005876 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005877 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005878 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5879 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005880 }
5881 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5882 }
5883
Steve Antondcc3c022017-12-22 16:02:54 -08005884 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005885 if (video && !video->rejected &&
5886 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005887 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005888 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005889 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5890 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005891 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005892 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005893 }
5894
Steve Antondcc3c022017-12-22 16:02:54 -08005895 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005896 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005897 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005898 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005899 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5900 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005901 }
5902 }
5903
Steve Anton8a006912017-12-04 15:25:56 -08005904 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005905}
5906
Steve Anton4171afb2017-11-20 10:20:22 -08005907// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005908cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005909 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005910 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005911 MediaTransportInterface* media_transport = nullptr;
5912 if (configuration_.use_media_transport) {
5913 media_transport = GetMediaTransport(mid);
5914 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005915
Steve Anton75737c02017-11-06 10:37:17 -08005916 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005917 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005918 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5919 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005920 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005921 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005922 }
Steve Anton75737c02017-11-06 10:37:17 -08005923 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5924 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005925 voice_channel->SignalSentPacket.connect(this,
5926 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005927 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005928
Steve Antoneda6ccd2017-12-04 10:21:55 -08005929 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005930}
5931
Steve Anton4171afb2017-11-20 10:20:22 -08005932// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005933cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005934 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005935 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5936
5937 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005938 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005939 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005940 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5941 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005942 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005943 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005944 }
Steve Anton75737c02017-11-06 10:37:17 -08005945 video_channel->SignalDtlsSrtpSetupFailure.connect(
5946 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005947 video_channel->SignalSentPacket.connect(this,
5948 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005949 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005950
Steve Antoneda6ccd2017-12-04 10:21:55 -08005951 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005952}
5953
Zhi Huange830e682018-03-30 10:48:35 -07005954bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005955 switch (data_channel_type_) {
5956 case cricket::DCT_MEDIA_TRANSPORT:
5957 if (network_thread()->Invoke<bool>(
5958 RTC_FROM_HERE,
5959 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5960 this, mid))) {
5961 for (const auto& channel : sctp_data_channels_) {
5962 channel->OnTransportChannelCreated();
5963 }
5964 return true;
5965 }
Steve Anton75737c02017-11-06 10:37:17 -08005966 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005967 case cricket::DCT_SCTP:
5968 if (!sctp_factory_) {
5969 RTC_LOG(LS_ERROR)
5970 << "Trying to create SCTP transport, but didn't compile with "
5971 "SCTP support (HAVE_SCTP)";
5972 return false;
5973 }
5974 if (!network_thread()->Invoke<bool>(
5975 RTC_FROM_HERE,
5976 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5977 return false;
5978 }
5979 for (const auto& channel : sctp_data_channels_) {
5980 channel->OnTransportChannelCreated();
5981 }
5982 return true;
5983 case cricket::DCT_RTP:
5984 default:
5985 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5986 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5987 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5988 SrtpRequired(), GetCryptoOptions());
5989 if (!rtp_data_channel_) {
5990 return false;
5991 }
5992 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5993 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5994 rtp_data_channel_->SignalSentPacket.connect(
5995 this, &PeerConnection::OnSentPacket_w);
5996 rtp_data_channel_->SetRtpTransport(rtp_transport);
5997 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005998 }
5999
Steve Anton75737c02017-11-06 10:37:17 -08006000 return true;
6001}
6002
6003Call::Stats PeerConnection::GetCallStats() {
6004 if (!worker_thread()->IsCurrent()) {
6005 return worker_thread()->Invoke<Call::Stats>(
6006 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
6007 }
6008 if (call_) {
6009 return call_->GetStats();
6010 } else {
6011 return Call::Stats();
6012 }
6013}
6014
Zhi Huange830e682018-03-30 10:48:35 -07006015bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08006016 RTC_DCHECK(network_thread()->IsCurrent());
6017 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07006018 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07006019 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07006020 RTC_DCHECK(dtls_transport);
6021 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006022 RTC_DCHECK(sctp_transport_);
6023 sctp_invoker_.reset(new rtc::AsyncInvoker());
6024 sctp_transport_->SignalReadyToSendData.connect(
6025 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
6026 sctp_transport_->SignalDataReceived.connect(
6027 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006028 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
6029 // another thread. Would be nice if there was a helper class similar to
6030 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
6031 // code.
6032 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
6033 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
6034 sctp_transport_->SignalClosingProcedureComplete.connect(
6035 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07006036 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07006037 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006038 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006039}
6040
6041void PeerConnection::DestroySctpTransport_n() {
6042 RTC_DCHECK(network_thread()->IsCurrent());
6043 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07006044 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08006045 sctp_invoker_.reset(nullptr);
6046 sctp_ready_to_send_data_ = false;
6047}
6048
6049void PeerConnection::OnSctpTransportReadyToSendData_n() {
6050 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6051 RTC_DCHECK(network_thread()->IsCurrent());
6052 // Note: Cannot use rtc::Bind here because it will grab a reference to
6053 // PeerConnection and potentially cause PeerConnection to live longer than
6054 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6055 // be destroyed before PeerConnection is destroyed, and at that point all
6056 // pending tasks will be cleared.
6057 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
6058 OnSctpTransportReadyToSendData_s(true);
6059 });
6060}
6061
6062void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
6063 RTC_DCHECK(signaling_thread()->IsCurrent());
6064 sctp_ready_to_send_data_ = ready;
6065 SignalSctpReadyToSendData(ready);
6066}
6067
6068void PeerConnection::OnSctpTransportDataReceived_n(
6069 const cricket::ReceiveDataParams& params,
6070 const rtc::CopyOnWriteBuffer& payload) {
6071 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6072 RTC_DCHECK(network_thread()->IsCurrent());
6073 // Note: Cannot use rtc::Bind here because it will grab a reference to
6074 // PeerConnection and potentially cause PeerConnection to live longer than
6075 // expected. It is safe not to grab a reference since the sctp_invoker_ will
6076 // be destroyed before PeerConnection is destroyed, and at that point all
6077 // pending tasks will be cleared.
6078 sctp_invoker_->AsyncInvoke<void>(
6079 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
6080 OnSctpTransportDataReceived_s(params, payload);
6081 });
6082}
6083
6084void PeerConnection::OnSctpTransportDataReceived_s(
6085 const cricket::ReceiveDataParams& params,
6086 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006087 RTC_DCHECK_RUN_ON(signaling_thread());
6088 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08006089 SignalSctpDataReceived(params, payload);
6090 }
6091}
6092
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006093void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08006094 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6095 RTC_DCHECK(network_thread()->IsCurrent());
6096 sctp_invoker_->AsyncInvoke<void>(
6097 RTC_FROM_HERE, signaling_thread(),
6098 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07006099 &SignalSctpClosingProcedureStartedRemotely, sid));
6100}
6101
6102void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
6103 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
6104 RTC_DCHECK(network_thread()->IsCurrent());
6105 sctp_invoker_->AsyncInvoke<void>(
6106 RTC_FROM_HERE, signaling_thread(),
6107 rtc::Bind(&sigslot::signal1<int>::operator(),
6108 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08006109}
6110
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006111bool PeerConnection::SetupMediaTransportForDataChannels_n(
6112 const std::string& mid) {
6113 media_transport_ = transport_controller_->GetMediaTransport(mid);
6114 if (!media_transport_) {
6115 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
6116 return false;
6117 }
6118
6119 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
6120 media_transport_->SetDataSink(this);
6121 media_transport_data_mid_ = mid;
6122 transport_controller_->SignalMediaTransportStateChanged.connect(
6123 this, &PeerConnection::OnMediaTransportStateChanged_n);
6124 // Check the initial state right away, in case transport is already writable.
6125 OnMediaTransportStateChanged_n();
6126 return true;
6127}
6128
6129void PeerConnection::TeardownMediaTransportForDataChannels_n() {
6130 if (!media_transport_) {
6131 return;
6132 }
6133 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
6134 media_transport_data_mid_.reset();
6135 media_transport_->SetDataSink(nullptr);
6136 media_transport_invoker_ = nullptr;
6137 media_transport_ = nullptr;
6138}
6139
6140void PeerConnection::OnMediaTransportStateChanged_n() {
6141 if (!media_transport_data_mid_ ||
6142 transport_controller_->GetMediaTransportState(
6143 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6144 return;
6145 }
6146 media_transport_invoker_->AsyncInvoke<void>(
6147 RTC_FROM_HERE, signaling_thread(), [this] {
6148 RTC_DCHECK_RUN_ON(signaling_thread());
6149 media_transport_ready_to_send_data_ = true;
6150 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6151 });
6152}
6153
Steve Anton75737c02017-11-06 10:37:17 -08006154// Returns false if bundle is enabled and rtcp_mux is disabled.
6155bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6156 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6157 if (!bundle_enabled)
6158 return true;
6159
6160 const cricket::ContentGroup* bundle_group =
6161 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6162 RTC_DCHECK(bundle_group != NULL);
6163
6164 const cricket::ContentInfos& contents = desc->contents();
6165 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6166 citer != contents.end(); ++citer) {
6167 const cricket::ContentInfo* content = (&*citer);
6168 RTC_DCHECK(content != NULL);
6169 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006170 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006171 if (!HasRtcpMuxEnabled(content))
6172 return false;
6173 }
6174 }
6175 // RTCP-MUX is enabled in all the contents.
6176 return true;
6177}
6178
6179bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006180 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006181}
6182
Steve Anton06817cd2018-12-18 15:55:30 -08006183static RTCError ValidateMids(const cricket::SessionDescription& description) {
6184 std::set<std::string> mids;
6185 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 11:32:20 -08006186 if (content.name.empty()) {
6187 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6188 "A media section is missing a MID attribute.");
6189 }
Steve Anton06817cd2018-12-18 15:55:30 -08006190 if (!mids.insert(content.name).second) {
6191 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6192 "Duplicate a=mid value '" + content.name + "'.");
6193 }
6194 }
6195 return RTCError::OK();
6196}
6197
Steve Anton8a006912017-12-04 15:25:56 -08006198RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006199 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006200 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006201 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006202 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006203 }
6204
6205 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006207 }
6208
Steve Anton3828c062017-12-06 10:34:51 -08006209 SdpType type = sdesc->GetType();
6210 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6211 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006212 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006213 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006214 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006215 }
6216
Steve Anton06817cd2018-12-18 15:55:30 -08006217 RTCError error = ValidateMids(*sdesc->description());
6218 if (!error.ok()) {
6219 return error;
6220 }
6221
Steve Anton75737c02017-11-06 10:37:17 -08006222 // Verify crypto settings.
6223 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006224 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6225 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006226 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006227 if (!crypto_error.ok()) {
6228 return crypto_error;
6229 }
Steve Anton75737c02017-11-06 10:37:17 -08006230 }
6231
6232 // Verify ice-ufrag and ice-pwd.
6233 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006234 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6235 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006236 }
6237
6238 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006239 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6240 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006241 }
6242
6243 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6244 // m-lines that do not rtcp-mux enabled.
6245
6246 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006247 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006248 // With an answer we want to compare the new answer session description with
6249 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006250 const cricket::SessionDescription* offer_desc =
6251 (source == cricket::CS_LOCAL) ? remote_description()->description()
6252 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006253 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6254 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6255 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6257 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006258 }
6259 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006260 // The re-offers should respect the order of m= sections in current
6261 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006262 // With a re-offer, either the current local or current remote descriptions
6263 // could be the most up to date, so we would like to check against both of
6264 // them if they exist. It could be the case that one of them has a 0 port
6265 // for a media section, but the other does not. This is important to check
6266 // against in the case that we are recycling an m= section.
6267 const cricket::SessionDescription* current_desc = nullptr;
6268 const cricket::SessionDescription* secondary_current_desc = nullptr;
6269 if (local_description()) {
6270 current_desc = local_description()->description();
6271 if (remote_description()) {
6272 secondary_current_desc = remote_description()->description();
6273 }
6274 } else if (remote_description()) {
6275 current_desc = remote_description()->description();
6276 }
Steve Anton75737c02017-11-06 10:37:17 -08006277 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006278 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6279 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006280 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6281 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006282 }
6283 }
6284
Steve Antonba42e992018-04-09 14:10:01 -07006285 if (IsUnifiedPlan()) {
6286 // Ensure that each audio and video media section has at most one
6287 // "StreamParams". This will return an error if receiving a session
6288 // description from a "Plan B" endpoint which adds multiple tracks of the
6289 // same type. With Unified Plan, there can only be at most one track per
6290 // media section.
6291 for (const ContentInfo& content : sdesc->description()->contents()) {
6292 const MediaContentDescription& desc = *content.description;
6293 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6294 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6295 desc.streams().size() > 1u) {
6296 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6297 "Media section has more than one track specified "
6298 "with a=ssrc lines which is not supported with "
6299 "Unified Plan.");
6300 }
6301 }
6302 }
6303
Steve Anton8a006912017-12-04 15:25:56 -08006304 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006305}
6306
Steve Anton3828c062017-12-06 10:34:51 -08006307bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006308 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006309 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006310 return (state == PeerConnectionInterface::kStable) ||
6311 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006312 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006313 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006314 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6315 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6316 }
6317}
6318
Steve Anton3828c062017-12-06 10:34:51 -08006319bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006320 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006321 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006322 return (state == PeerConnectionInterface::kStable) ||
6323 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006324 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006325 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006326 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6327 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6328 }
6329}
6330
Steve Antonf8470812017-12-04 10:46:21 -08006331const char* PeerConnection::SessionErrorToString(SessionError error) const {
6332 switch (error) {
6333 case SessionError::kNone:
6334 return "ERROR_NONE";
6335 case SessionError::kContent:
6336 return "ERROR_CONTENT";
6337 case SessionError::kTransport:
6338 return "ERROR_TRANSPORT";
6339 }
6340 RTC_NOTREACHED();
6341 return "";
6342}
6343
Steve Anton75737c02017-11-06 10:37:17 -08006344std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006345 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006346 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6347 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006348 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006349}
6350
Steve Anton8e20f172018-03-06 10:55:04 -08006351void PeerConnection::ReportSdpFormatReceived(
6352 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006353 int num_audio_mlines = 0;
6354 int num_video_mlines = 0;
6355 int num_audio_tracks = 0;
6356 int num_video_tracks = 0;
6357 for (const ContentInfo& content : remote_offer.description()->contents()) {
6358 cricket::MediaType media_type = content.media_description()->type();
6359 int num_tracks = std::max(
6360 1, static_cast<int>(content.media_description()->streams().size()));
6361 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6362 num_audio_mlines += 1;
6363 num_audio_tracks += num_tracks;
6364 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6365 num_video_mlines += 1;
6366 num_video_tracks += num_tracks;
6367 }
6368 }
6369 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6370 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6371 format = kSdpFormatReceivedComplexUnifiedPlan;
6372 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6373 format = kSdpFormatReceivedComplexPlanB;
6374 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6375 format = kSdpFormatReceivedSimple;
6376 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006377 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6378 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006379}
6380
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006381void PeerConnection::NoteUsageEvent(UsageEvent event) {
6382 RTC_DCHECK_RUN_ON(signaling_thread());
6383 usage_event_accumulator_ |= static_cast<int>(event);
6384}
6385
6386void PeerConnection::ReportUsagePattern() const {
6387 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006388 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6389 usage_event_accumulator_,
6390 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006391 const int bad_bits =
6392 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6393 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6394 const int good_bits =
6395 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6396 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6397 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6398 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6399 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006400 // If called after close(), we can't report, because observer may have
6401 // been deallocated, and therefore pointer is null. Write to log instead.
6402 if (observer_) {
6403 Observer()->OnInterestingUsage(usage_event_accumulator_);
6404 } else {
6405 RTC_LOG(LS_INFO) << "Interesting usage signature "
6406 << usage_event_accumulator_
6407 << " observed after observer shutdown";
6408 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006409 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006410}
6411
Steve Anton0ffaaa22018-02-23 10:31:30 -08006412void PeerConnection::ReportNegotiatedSdpSemantics(
6413 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006414 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006415 switch (answer.description()->msid_signaling()) {
6416 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006417 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006418 break;
6419 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006420 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006421 break;
6422 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006423 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006424 break;
6425 case cricket::kMsidSignalingMediaSection |
6426 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006427 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006428 break;
6429 default:
6430 RTC_NOTREACHED();
6431 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006432 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6433 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006434}
6435
Steve Anton75737c02017-11-06 10:37:17 -08006436// We need to check the local/remote description for the Transport instead of
6437// the session, because a new Transport added during renegotiation may have
6438// them unset while the session has them set from the previous negotiation.
6439// Not doing so may trigger the auto generation of transport description and
6440// mess up DTLS identity information, ICE credential, etc.
6441bool PeerConnection::ReadyToUseRemoteCandidate(
6442 const IceCandidateInterface* candidate,
6443 const SessionDescriptionInterface* remote_desc,
6444 bool* valid) {
6445 *valid = true;
6446
6447 const SessionDescriptionInterface* current_remote_desc =
6448 remote_desc ? remote_desc : remote_description();
6449
6450 if (!current_remote_desc) {
6451 return false;
6452 }
6453
6454 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6455 size_t remote_content_size =
6456 current_remote_desc->description()->contents().size();
6457 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006458 RTC_LOG(LS_ERROR)
6459 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6460 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006461
6462 *valid = false;
6463 return false;
6464 }
6465
6466 cricket::ContentInfo content =
6467 current_remote_desc->description()->contents()[mediacontent_index];
6468
6469 const std::string transport_name = GetTransportName(content.name);
6470 if (transport_name.empty()) {
6471 return false;
6472 }
Zhi Huange830e682018-03-30 10:48:35 -07006473 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006474}
6475
6476bool PeerConnection::SrtpRequired() const {
6477 return dtls_enabled_ ||
6478 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6479}
6480
6481void PeerConnection::OnTransportControllerGatheringState(
6482 cricket::IceGatheringState state) {
6483 RTC_DCHECK(signaling_thread()->IsCurrent());
6484 if (state == cricket::kIceGatheringGathering) {
6485 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6486 } else if (state == cricket::kIceGatheringComplete) {
6487 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6488 }
6489}
6490
6491void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006492 std::map<std::string, std::set<cricket::MediaType>>
6493 media_types_by_transport_name;
6494 for (auto transceiver : transceivers_) {
6495 if (transceiver->internal()->channel()) {
6496 const std::string& transport_name =
6497 transceiver->internal()->channel()->transport_name();
6498 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006499 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006500 }
Steve Anton75737c02017-11-06 10:37:17 -08006501 }
6502 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006503 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6504 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006505 }
Zhi Huange830e682018-03-30 10:48:35 -07006506
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006507 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006508 if (transport_name) {
6509 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006510 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006511 }
Zhi Huange830e682018-03-30 10:48:35 -07006512
Steve Antonc7b964c2018-02-01 14:39:45 -08006513 for (const auto& entry : media_types_by_transport_name) {
6514 const std::string& transport_name = entry.first;
6515 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006516 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006517 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006518 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006519 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006520 }
6521 }
6522}
6523// Walk through the ConnectionInfos to gather best connection usage
6524// for IPv4 and IPv6.
6525void PeerConnection::ReportBestConnectionState(
6526 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006527 for (const cricket::TransportChannelStats& channel_stats :
6528 stats.channel_stats) {
6529 for (const cricket::ConnectionInfo& connection_info :
6530 channel_stats.connection_infos) {
6531 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006532 continue;
6533 }
6534
Steve Antonc7b964c2018-02-01 14:39:45 -08006535 const cricket::Candidate& local = connection_info.local_candidate;
6536 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006537
6538 // Increment the counter for IceCandidatePairType.
6539 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6540 (local.type() == RELAY_PORT_TYPE &&
6541 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006542 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6543 GetIceCandidatePairCounter(local, remote),
6544 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006545 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006546 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6547 GetIceCandidatePairCounter(local, remote),
6548 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006549 } else {
6550 RTC_CHECK(0);
6551 }
Steve Anton75737c02017-11-06 10:37:17 -08006552
6553 // Increment the counter for IP type.
6554 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006555 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6556 kBestConnections_IPv4,
6557 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006558 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006559 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6560 kBestConnections_IPv6,
6561 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006562 } else {
Qingsi Wang1dac6d82018-12-12 15:28:47 -08006563 RTC_CHECK(!local.address().hostname().empty() &&
6564 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 10:37:17 -08006565 }
6566
6567 return;
6568 }
6569 }
6570}
6571
6572void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006573 const cricket::TransportStats& stats,
6574 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006575 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6576 return;
6577 }
6578
6579 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6580 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6581 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6582 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6583 return;
6584 }
6585
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006586 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6587 for (cricket::MediaType media_type : media_types) {
6588 switch (media_type) {
6589 case cricket::MEDIA_TYPE_AUDIO:
6590 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6591 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6592 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6593 break;
6594 case cricket::MEDIA_TYPE_VIDEO:
6595 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6596 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6597 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6598 break;
6599 case cricket::MEDIA_TYPE_DATA:
6600 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6601 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6602 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6603 break;
6604 default:
6605 RTC_NOTREACHED();
6606 continue;
6607 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006608 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006609 }
6610
6611 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6612 for (cricket::MediaType media_type : media_types) {
6613 switch (media_type) {
6614 case cricket::MEDIA_TYPE_AUDIO:
6615 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6616 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6617 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6618 break;
6619 case cricket::MEDIA_TYPE_VIDEO:
6620 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6621 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6622 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6623 break;
6624 case cricket::MEDIA_TYPE_DATA:
6625 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6626 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6627 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6628 break;
6629 default:
6630 RTC_NOTREACHED();
6631 continue;
6632 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006633 }
Steve Anton75737c02017-11-06 10:37:17 -08006634 }
6635}
6636
6637void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6638 RTC_DCHECK(worker_thread()->IsCurrent());
6639 RTC_DCHECK(call_);
6640 call_->OnSentPacket(sent_packet);
6641}
6642
6643const std::string PeerConnection::GetTransportName(
6644 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006645 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006646 if (channel) {
6647 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006648 }
Steve Anton6fec8802017-12-04 10:37:29 -08006649 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006650 RTC_DCHECK(sctp_mid_);
6651 if (content_name == *sctp_mid_) {
6652 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006653 }
6654 }
6655 // Return an empty string if failed to retrieve the transport name.
6656 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006657}
6658
Steve Anton6fec8802017-12-04 10:37:29 -08006659void PeerConnection::DestroyTransceiverChannel(
6660 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6661 transceiver) {
6662 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006663
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006664 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006665 if (channel) {
6666 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006667 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006668 }
6669}
6670
6671void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006672 if (rtp_data_channel_) {
6673 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006674 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006675 rtp_data_channel_ = nullptr;
6676 }
6677
6678 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6679 // grab a reference to this PeerConnection. If this is called from the
6680 // PeerConnection destructor, the RefCountedObject vtable will have already
6681 // been destroyed (since it is a subclass of PeerConnection) and using
6682 // rtc::Bind will cause "Pure virtual function called" error to appear.
6683
6684 if (sctp_transport_) {
6685 OnDataChannelDestroyed();
6686 network_thread()->Invoke<void>(RTC_FROM_HERE,
6687 [this] { DestroySctpTransport_n(); });
6688 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006689
6690 if (media_transport_) {
6691 OnDataChannelDestroyed();
6692 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6693 RTC_DCHECK_RUN_ON(network_thread());
6694 TeardownMediaTransportForDataChannels_n();
6695 });
6696 }
Steve Anton6fec8802017-12-04 10:37:29 -08006697}
6698
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006699void PeerConnection::DestroyChannelInterface(
6700 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006701 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006702 switch (channel->media_type()) {
6703 case cricket::MEDIA_TYPE_AUDIO:
6704 channel_manager()->DestroyVoiceChannel(
6705 static_cast<cricket::VoiceChannel*>(channel));
6706 break;
6707 case cricket::MEDIA_TYPE_VIDEO:
6708 channel_manager()->DestroyVideoChannel(
6709 static_cast<cricket::VideoChannel*>(channel));
6710 break;
6711 case cricket::MEDIA_TYPE_DATA:
6712 channel_manager()->DestroyRtpDataChannel(
6713 static_cast<cricket::RtpDataChannel*>(channel));
6714 break;
6715 default:
6716 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6717 break;
6718 }
Zhi Huange830e682018-03-30 10:48:35 -07006719}
Steve Anton6fec8802017-12-04 10:37:29 -08006720
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006721bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006722 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006723 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006724 cricket::DtlsTransportInternal* dtls_transport,
6725 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006726 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006727 auto base_channel = GetChannel(mid);
6728 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006729 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006730 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006731 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006732 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006733 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006734
6735 call_->MediaTransportChange(media_transport);
6736
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006737 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006738}
6739
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006740PeerConnectionObserver* PeerConnection::Observer() const {
6741 // In earlier production code, the pointer was not cleared on close,
6742 // which might have led to undefined behavior if the observer was not
6743 // deallocated, or strange crashes if it was.
6744 // We use CHECK in order to catch such behavior if it exists.
6745 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6746 RTC_CHECK(observer_);
6747 return observer_;
6748}
6749
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006750CryptoOptions PeerConnection::GetCryptoOptions() {
6751 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6752 // after it has been removed.
6753 return configuration_.crypto_options.has_value()
6754 ? *configuration_.crypto_options
6755 : factory_->options().crypto_options;
6756}
6757
Harald Alvestrand89061872018-01-02 14:08:34 +01006758void PeerConnection::ClearStatsCache() {
6759 if (stats_collector_) {
6760 stats_collector_->ClearCachedStatsReport();
6761 }
6762}
6763
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006764void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006765 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6766 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006767}
6768
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006769} // namespace webrtc