blob: a70ab2e95ab2540bd08b29d405f264356e467fa8 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:361/*
kjellanderb24317b2016-02-10 15:54:432 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:363 *
kjellanderb24317b2016-02-10 15:54:434 * 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:369 */
10
Mirko Bonadei92ea95e2017-09-15 04:47:3111#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:3612
deadbeefeb459812015-12-16 03:24:4313#include <algorithm>
Harald Alvestrand8ebba742018-05-31 12:00:3414#include <limits>
Steve Antondcc3c022017-12-23 00:02:5415#include <queue>
Steve Anton75737c02017-11-06 18:37:1716#include <set>
kwiberg0eb15ed2015-12-17 11:04:1517#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:3619
Karl Wiberg918f50c2018-07-05 09:40:3320#include "absl/memory/memory.h"
Fredrik Solenberg41f3a432018-12-17 20:02:2221#include "absl/strings/match.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3122#include "api/jsepicecandidate.h"
23#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3124#include "api/mediastreamproxy.h"
25#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 13:39:2426#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3127#include "call/call.h"
Qingsi Wang93a84392018-01-31 01:13:0928#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 11:18:2629#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3130#include "logging/rtc_event_log/rtc_event_log.h"
31#include "media/sctp/sctptransport.h"
32#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 18:37:1733#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3134#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 22:30:0939#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3140#include "pc/rtpreceiver.h"
41#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 18:37:1742#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 18:27:4143#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3144#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 09:42:2650#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3151#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 11:41:3052#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 04:47:3153#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 19:54:5356#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:3657
Steve Anton75737c02017-11-06 18:37:1758using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-21 00:34:0062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 18:37:1763using 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 18:21:5770namespace webrtc {
71
Steve Anton75737c02017-11-06 18:37:1772// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 18:37:1776const 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 18:37:1784const 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:3695
Steve Anton75737c02017-11-06 18:37:1796namespace {
henrike@webrtc.org28e20752013-07-10 00:45:3697
Seth Hampson845e8782018-03-02 19:34:1098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 18:20:2299static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 18:33:11101
zhihuang8f65cdf2016-05-07 01:40:30102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40105enum {
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 10:03:50114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40116struct 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 18:33:11142// 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 23:05:28148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 10:09:25150 << " is already added.";
deadbeefab9b2d12015-10-14 18:33:11151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 19:49:08156// 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 22:57:10161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 19:49:08162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 18:33:11166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 21:10:50172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 21:27:39174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 21:10:50176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:37177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 13:50:32179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 21:10:50180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 22:45:38183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 21:10:50184 }
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 08:58:37189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 21:10:50191 }
192 }
zhihuanga77e6bb2017-08-15 01:17:48193 }
zhihuang1c378ed2017-08-17 21:10:50194}
olka3c747662017-08-17 13:50:32195
zhihuang1c378ed2017-08-17 21:10:50196// 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 18:33:11204 // 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 21:10:50209 // 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 18:33:11213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 15:15:11217uint32_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 13:56:46229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 15:15:11230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 20:28:30234// 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 22:59:59242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 17:22:52243 bool ok = error.ok();
Steve Anton038834f2017-07-14 22:59:59244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 17:22:52247 return ok;
Steve Anton038834f2017-07-14 22:59:59248}
249
Steve Antonba818672017-11-06 18:21:57250std::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 18:38:28269
Steve Anton75737c02017-11-06 18:37:17270IceCandidatePairType 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 16:25:54280 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 18:37:17284 bool local_private = IPIsPrivate(local.address().ipaddr());
285 bool remote_private = IPIsPrivate(remote.address().ipaddr());
Jeroen de Borst833979f2018-12-13 16:25:54286 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 18:37:17298 return kIceCandidatePairHostPrivateHostPrivate;
299 } else {
300 return kIceCandidatePairHostPrivateHostPublic;
301 }
302 } else {
Jeroen de Borst833979f2018-12-13 16:25:54303 if (remote_hostname) {
304 return kIceCandidatePairHostPublicHostName;
305 } else if (remote_private) {
Steve Anton75737c02017-11-06 18:37:17306 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 23:33:48343// 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 18:37:17358// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 23:33:48359// |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 18:37:17372 return false;
373 }
374
Seth Hampsonae8a90a2018-02-13 23:33:48375 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-23 00:02:54386 continue;
387 }
Seth Hampsonae8a90a2018-02-13 23:33:48388 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 18:37:17389 return false;
390 }
391 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 23:33:48392 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 18:37:17396 return false;
397 }
398 }
399 return true;
400}
401
Seth Hampsonae8a90a2018-02-13 23:33:48402bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
403 const SessionDescription& desc2) {
404 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 18:37:17405}
406
Qingsi Wang7fc821d2018-07-12 19:54:53407void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
408 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 08:43:20409 // 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 19:54:53431 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
432 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 13:15:26433
Mirko Bonadeiab499822018-09-11 08:43:20434 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 13:15:26440 }
441}
442
Harald Alvestrand76829d72018-07-18 21:24:36443void NoteAddIceCandidateResult(int result) {
444 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
445 kAddIceCandidateMax);
446}
447
Steve Anton75737c02017-11-06 18:37:17448// 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 19:54:53454RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 18:37:17455 const cricket::ContentGroup* bundle =
456 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 23:25:56457 for (const cricket::ContentInfo& content_info : desc->contents()) {
458 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17459 continue;
460 }
Harald Alvestrand2e180612018-03-07 09:56:14461 // 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 19:54:53464 content_info.media_description()->type());
Steve Anton8a006912017-12-04 23:25:56465 const std::string& mid = content_info.name;
466 if (bundle && bundle->HasContentName(mid) &&
467 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17468 // 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 23:14:30476 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 23:25:56477 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17478 if (!media || !tinfo) {
479 // Something is not right.
Steve Anton8a006912017-12-04 23:25:56480 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:17481 }
482 if (dtls_enabled) {
483 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 10:09:25484 RTC_LOG(LS_WARNING)
485 << "Session description must have DTLS fingerprint if "
486 "DTLS enabled.";
Steve Anton8a006912017-12-04 23:25:56487 return RTCError(RTCErrorType::INVALID_PARAMETER,
488 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 18:37:17489 }
490 } else {
491 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25492 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 18:37:17493 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 23:25:56494 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 18:37:17495 }
496 }
497 }
Steve Anton8a006912017-12-04 23:25:56498 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:17499}
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 23:25:56507 for (const cricket::ContentInfo& content_info : desc->contents()) {
508 if (content_info.rejected) {
Steve Anton75737c02017-11-06 18:37:17509 continue;
510 }
Steve Anton8a006912017-12-04 23:25:56511 const std::string& mid = content_info.name;
512 if (bundle && bundle->HasContentName(mid) &&
513 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 18:37:17514 // 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 23:25:56522 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 18:37:17523 if (!tinfo) {
524 // Something is not right.
Mirko Bonadei675513b2017-11-09 10:09:25525 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 18:37:17526 return false;
527 }
528 if (tinfo->description.ice_ufrag.empty() ||
529 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 10:09:25530 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 18:37:17531 return false;
532 }
533 }
534 return true;
535}
536
Steve Anton75737c02017-11-06 18:37:17537// Get the SCTP port out of a SessionDescription.
538// Return -1 if not found.
539int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 23:14:30540 const cricket::DataContentDescription* data_desc =
541 GetFirstDataContentDescription(session_description);
542 RTC_DCHECK(data_desc);
543 if (!data_desc) {
Steve Anton75737c02017-11-06 18:37:17544 return -1;
545 }
Steve Anton75737c02017-11-06 18:37:17546 std::string value;
547 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
548 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 23:14:30549 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 18:37:17550 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 18:37:17560// 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 10:09:25585 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
586 << ".";
Steve Anton75737c02017-11-06 18:37:17587 return true;
588 }
589 return false;
590}
591
Steve Anton80dd7b52018-02-17 01:08:42592// 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 11:41:30597 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-17 01:08:42598 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
599 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 14:59:32600 return oss.Release();
Steve Anton80dd7b52018-02-17 01:08:42601}
602
Seth Hampson5b4f0752018-04-02 23:31:36603std::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 14:47:43614absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-23 00:54:23615 int rtc_configuration_parameter) {
616 if (rtc_configuration_parameter ==
617 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 14:47:43618 return absl::nullopt;
Qingsi Wang866e08d2018-03-23 00:54:23619 }
620 return rtc_configuration_parameter;
621}
622
Bjorn Mellem175aa2e2018-11-08 19:23:22623cricket::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 23:55:30652// 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 18:37:17671} // namespace
672
Henrik Boström31638672017-11-23 16:48:32673// 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 14:18:03694 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 16:48:32695 }
696
697 private:
698 rtc::scoped_refptr<PeerConnection> pc_;
699 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
700};
701
deadbeef293e9262017-01-11 20:28:30702bool PeerConnectionInterface::RTCConfiguration::operator==(
703 const PeerConnectionInterface::RTCConfiguration& o) const {
704 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 17:13:10705 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 20:28:30706 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56707 IceServers servers;
Steve Anton300bf8e2017-07-14 17:13:10708 IceTransportsType type;
deadbeef293e9262017-01-11 20:28:30709 BundlePolicy bundle_policy;
710 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 17:13:10711 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
712 int ice_candidate_pool_size;
713 bool disable_ipv6;
714 bool disable_ipv6_on_wifi;
deadbeefd21eab3e2017-07-26 23:50:11715 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 09:30:22716 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 17:13:10717 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 14:47:43718 absl::optional<int> screencast_min_bitrate;
719 absl::optional<bool> combined_audio_video_bwe;
720 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 20:28:30721 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 14:45:20725 int audio_jitter_buffer_min_delay_ms;
deadbeef293e9262017-01-11 20:28:30726 int ice_connection_receiving_timeout;
727 int ice_backup_candidate_pair_ping_interval;
728 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 20:28:30729 bool prioritize_most_likely_ice_candidate_pairs;
730 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 20:28:30731 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 14:47:43735 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-07 07:30:17740 absl::optional<int> ice_inactive_timeout;
Danil Chapovalov66cadcc2018-06-19 14:47:43741 absl::optional<int> stun_candidate_keepalive_interval;
742 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 12:01:40743 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 18:25:56744 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 14:47:43745 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 18:41:11746 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21747 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:48748 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 17:16:44749 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 09:25:48750 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30751 };
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 14:45:20763 audio_jitter_buffer_min_delay_ms ==
764 o.audio_jitter_buffer_min_delay_ms &&
deadbeef293e9262017-01-11 20:28:30765 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 22:40:51774 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab3e2017-07-26 23:50:11775 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 09:30:22776 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 20:28:30777 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 20:28:30778 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 19:50:14786 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 22:55:14787 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 17:13:10791 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 17:53:57792 ice_unwritable_timeout == o.ice_unwritable_timeout &&
793 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Jiawei Ou9d4fd5552018-12-07 07:30:17794 ice_inactive_timeout == o.ice_inactive_timeout &&
Qingsi Wangdb53f8e2018-02-20 22:45:49795 stun_candidate_keepalive_interval ==
796 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 12:01:40797 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 18:25:56798 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 18:38:40799 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 18:41:11800 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 16:43:21801 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 17:16:44802 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 16:07:48803 use_media_transport_for_data_channels ==
804 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 09:25:48805 crypto_options == o.crypto_options &&
806 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 20:28:30807}
808
809bool PeerConnectionInterface::RTCConfiguration::operator!=(
810 const PeerConnectionInterface::RTCConfiguration& o) const {
811 return !(*this == o);
deadbeef3edec7c2016-12-10 19:44:26812}
813
zhihuang8f65cdf2016-05-07 01:40:30814// 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 10:09:25818 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 10:24:27819 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-07 01:40:30820 }
821 return cname;
822}
823
zhihuang1c378ed2017-08-17 21:10:50824bool 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 13:50:32828}
829
zhihuang1c378ed2017-08-17 21:10:50830// 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-15 01:17:48838
zhihuang38ede132017-06-15 19:52:32839PeerConnection::PeerConnection(PeerConnectionFactory* factory,
840 std::unique_ptr<RtcEventLog> event_log,
841 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36842 : factory_(factory),
zhihuang38ede132017-06-15 19:52:32843 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-07 01:40:30844 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 18:33:11845 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 19:52:32846 remote_streams_(StreamCollection::Create()),
847 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36848
849PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 21:15:17850 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 18:20:22851 RTC_DCHECK_RUN_ON(signaling_thread());
852
Steve Anton8af21862017-12-15 19:20:13853 // 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 18:20:22859
Taylor Brandstettera1c30352016-05-13 15:15:11860 stats_.reset(nullptr);
hbosb78306a2016-12-19 13:06:57861 if (stats_collector_) {
862 stats_collector_->WaitForPendingRequest();
863 stats_collector_ = nullptr;
864 }
Steve Anton75737c02017-11-06 18:37:17865
Steve Anton8af21862017-12-15 19:20:13866 // 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 10:09:25870 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 18:37:17871
872 webrtc_session_desc_factory_.reset();
873 sctp_invoker_.reset();
874 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 19:23:22875 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 18:37:17876 transport_controller_.reset();
877
deadbeef91dd5672016-05-18 23:55:30878 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27879 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 09:23:02880 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 12:18:15881 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 19:15:02882 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:15883 call_.reset();
Qingsi Wang93a84392018-01-31 01:13:09884 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 12:18:15885 event_log_.reset();
886 });
henrike@webrtc.org28e20752013-07-10 00:45:36887}
888
Steve Anton8af21862017-12-15 19:20:13889void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 18:20:08890 // Destroy video channels first since they may have a pointer to a voice
891 // channel.
892 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08893 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 18:20:08894 DestroyTransceiverChannel(transceiver);
895 }
896 }
897 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 19:43:08898 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 18:20:08899 DestroyTransceiverChannel(transceiver);
900 }
901 }
902 DestroyDataChannel();
903}
904
henrike@webrtc.org28e20752013-07-10 00:45:36905bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45906 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab588882018-05-02 22:12:47907 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 21:15:17908 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 22:59:59909
910 RTCError config_error = ValidateConfiguration(configuration);
911 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 10:09:25912 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 22:59:59913 return false;
914 }
915
Benjamin Wrightcab588882018-05-02 22:12:47916 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 10:09:25917 RTC_LOG(LS_ERROR)
918 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 09:37:07919 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 20:28:30920 return false;
921 }
Jonas Orelandbdcee282017-10-10 12:01:40922
Benjamin Wrightcab588882018-05-02 22:12:47923 if (!dependencies.observer) {
deadbeef293e9262017-01-11 20:28:30924 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 10:09:25925 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 09:37:07926 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 20:55:10927 return false;
928 }
Benjamin Wrightd6f86e82018-05-08 20:12:25929
Benjamin Wrightcab588882018-05-02 22:12:47930 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 20:20:15931 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab588882018-05-02 22:12:47932 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 20:12:25933 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 20:55:10934
Harald Alvestrandb2a74782018-06-28 11:54:07935 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 23:55:30944 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 15:15:11945 // there.
Taylor Brandstetter5d97a9a2016-06-10 21:17:27946 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 11:54:07947 RTC_FROM_HERE,
948 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
949 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36950 return false;
951 }
Harald Alvestrandb2a74782018-06-28 11:54:07952 // 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:36960
Qingsi Wang7fc821d2018-07-12 19:54:53961 // 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 17:48:35971 const PeerConnectionFactoryInterface::Options& options = factory_->options();
972
Steve Anton75737c02017-11-06 18:37:17973 // 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 17:48:35978 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 17:16:44985 // 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 23:44:34990 config.transport_observer = this;
Qingsi Wang7685e862018-06-12 03:15:46991 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 17:48:35992#if defined(ENABLE_EXTERNAL_AUTH)
993 config.enable_external_auth = true;
994#endif
Zhi Huangb57e1692018-06-12 18:41:11995 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 20:15:42996
Bjorn Mellema9bbd862018-11-02 16:07:48997 if (configuration.use_media_transport ||
998 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 20:15:42999 if (!factory_->media_transport_factory()) {
1000 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 16:07:481001 << "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 20:15:421004 return false;
1005 }
1006
1007 config.media_transport_factory = factory_->media_transport_factory();
1008 }
1009
Zhi Huange830e682018-03-30 17:48:351010 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 20:20:151011 signaling_thread(), network_thread(), port_allocator_.get(),
1012 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 17:48:351013 transport_controller_->SignalIceConnectionState.connect(
Alex Loiko9289eda2018-11-23 16:18:591014 this, &PeerConnection::OnTransportControllerConnectionState);
1015 transport_controller_->SignalStandardizedIceConnectionState.connect(
1016 this, &PeerConnection::SetStandardizedIceConnectionState);
Jonas Olsson635474e2018-10-18 13:58:171017 transport_controller_->SignalConnectionState.connect(
1018 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 17:48:351019 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 18:37:171020 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 17:48:351021 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 18:37:171022 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 17:48:351023 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 18:37:171024 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1025 transport_controller_->SignalDtlsHandshakeError.connect(
1026 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1027
1028 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 18:07:251029
deadbeefab9b2d12015-10-14 18:33:111030 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-16 06:33:011031 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:361032
Steve Antonba818672017-11-06 18:21:571033 configuration_ = configuration;
1034
Steve Anton75737c02017-11-06 18:37:171035 // 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 22:50:291044 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 18:37:171045
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 Wrightcab588882018-05-02 22:12:471050 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 18:37:171051 // |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 19:23:221057 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 18:37:171069 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 09:53:301083 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 18:37:171084
1085 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 09:53:301086 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 18:37:171087
Jakob Ivarsson10403ae2018-11-27 14:45:201088 audio_options_.audio_jitter_buffer_min_delay_ms =
1089 configuration.audio_jitter_buffer_min_delay_ms;
1090
Steve Anton75737c02017-11-06 18:37:171091 // 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 Wrightcab588882018-05-02 22:12:471095 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171096 certificate = nullptr;
1097 } else if (certificate) {
1098 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab588882018-05-02 22:12:471099 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 18:37:171100 }
1101
1102 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1103 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab588882018-05-02 22:12:471104 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 18:37:171105 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 17:16:441113 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
Steve Anton8f66ddb2018-12-11 00:08:051114 webrtc_session_desc_factory_->set_is_unified_plan(IsUnifiedPlan());
henrike@webrtc.org28e20752013-07-10 00:45:361115
Steve Anton4171afb2017-11-20 18:20:221116 // 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 10:04:411125 int delay_ms =
1126 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:401127 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1128 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:361129 return true;
1130}
1131
Steve Anton038834f2017-07-14 22:59:591132RTCError 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 17:55:211140 auto result =
1141 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1142 return result;
Steve Anton038834f2017-07-14 22:59:591143}
1144
Yves Gerey665174f2018-06-19 13:03:051145rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 21:48:581146 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1147 "Plan SdpSemantics. Please use GetSenders "
1148 "instead.";
deadbeefab9b2d12015-10-14 18:33:111149 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361150}
1151
Yves Gerey665174f2018-06-19 13:03:051152rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 21:48:581153 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1154 "Plan SdpSemantics. Please use GetReceivers "
1155 "instead.";
deadbeefab9b2d12015-10-14 18:33:111156 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:361157}
1158
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:291159bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581160 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1161 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 21:15:171162 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:361163 if (IsClosed()) {
1164 return false;
1165 }
deadbeefab9b2d12015-10-14 18:33:111166 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:361167 return false;
1168 }
deadbeefab9b2d12015-10-14 18:33:111169
1170 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-16 03:24:431171 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 13:47:291180 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 18:33:111181
deadbeefab9b2d12015-10-14 18:33:111182 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251183 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111184 }
1185 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-25 00:00:251186 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 18:33:111187 }
1188
tommi@webrtc.org03505bc2014-07-14 20:15:261189 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:161190 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361191 return true;
1192}
1193
1194void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 21:48:581195 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1196 "Plan SdpSemantics. Please use RemoveTrack "
1197 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171198 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-25 00:00:251199 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 18:33:111206 }
deadbeefab9b2d12015-10-14 18:33:111207 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-16 03:24:431208 stream_observers_.erase(
1209 std::remove_if(
1210 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 13:47:291211 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 23:05:281212 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-16 03:24:431213 }),
1214 stream_observers_.end());
deadbeefab9b2d12015-10-14 18:33:111215
henrike@webrtc.org28e20752013-07-10 00:45:361216 if (IsClosed()) {
1217 return;
1218 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161219 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:361220}
1221
Steve Anton2d6c76a2018-01-06 01:10:521222RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 18:23:571223 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101224 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-06 01:10:521225 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 18:23:571226 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 18:23:571234 if (IsClosed()) {
1235 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1236 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421237 }
Steve Anton4171afb2017-11-20 18:20:221238 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 18:23:571239 LOG_AND_RETURN_ERROR(
1240 RTCErrorType::INVALID_PARAMETER,
1241 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 23:35:421242 }
Steve Antonf9381f02017-12-14 18:23:571243 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 23:31:361244 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1245 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 18:23:571246 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161247 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 23:48:171248 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 18:23:571249 }
1250 return sender_or_error;
1251}
deadbeefe1f9d832016-01-14 23:35:421252
Steve Antonf9381f02017-12-14 18:23:571253RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1254PeerConnection::AddTrackPlanB(
1255 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101256 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 23:31:361257 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-11 00:26:061266 cricket::MediaType media_type =
1267 (track->kind() == MediaStreamTrackInterface::kAudioKind
1268 ? cricket::MEDIA_TYPE_AUDIO
1269 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 20:03:361270 auto new_sender =
Florent Castelli892acf02018-10-01 20:47:201271 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 23:35:421272 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-14 00:26:051273 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:221274 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221275 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181276 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361277 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221278 if (sender_info) {
1279 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421280 }
Steve Antonf9381f02017-12-14 18:23:571281 } else {
1282 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-14 00:26:051283 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:221284 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 18:20:221285 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:181286 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 23:31:361287 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 18:20:221288 if (sender_info) {
1289 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 23:35:421290 }
deadbeefe1f9d832016-01-14 23:35:421291 }
Steve Anton02ee47c2018-01-11 00:26:061292 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 18:23:571293}
deadbeefe1f9d832016-01-14 23:35:421294
Steve Antonf9381f02017-12-14 18:23:571295RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1296PeerConnection::AddTrackUnifiedPlan(
1297 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 19:34:101298 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 18:23:571299 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1300 if (transceiver) {
Steve Anton3d954a62018-04-02 18:27:231301 RTC_LOG(LS_INFO) << "Reusing an existing "
1302 << cricket::MediaTypeToString(transceiver->media_type())
1303 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 18:23:571304 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 23:48:121305 transceiver->internal()->set_direction(
1306 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571307 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 23:48:121308 transceiver->internal()->set_direction(
1309 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 18:23:571310 }
Steve Anton02ee47c2018-01-11 00:26:061311 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 19:34:101312 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 18:23:571313 } 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 18:27:231318 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1319 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 18:13:501320 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 20:47:201327 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-11 00:26:061328 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1329 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 18:23:571330 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 23:48:121331 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 18:23:571332 }
Steve Antonf9381f02017-12-14 18:23:571333 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 19:43:081342 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 18:23:571343 track->kind() &&
Seth Hampson2f0d7022018-02-20 19:54:421344 !transceiver->internal()->has_ever_been_used_to_send() &&
1345 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 18:23:571346 return transceiver;
1347 }
1348 }
1349 return nullptr;
deadbeefe1f9d832016-01-14 23:35:421350}
1351
1352bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1353 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 17:27:331354 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 18:23:571355}
1356
Steve Anton24db5732018-07-23 17:27:331357RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 18:23:571358 rtc::scoped_refptr<RtpSenderInterface> sender) {
1359 if (!sender) {
1360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1361 }
deadbeefe1f9d832016-01-14 23:35:421362 if (IsClosed()) {
Steve Antonf9381f02017-12-14 18:23:571363 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1364 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 23:35:421365 }
Steve Antonf9381f02017-12-14 18:23:571366 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 23:48:121373 transceiver->internal()->set_direction(
1374 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 18:23:571375 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 23:48:121376 transceiver->internal()->set_direction(
1377 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 18:23:571378 }
Steve Anton4171afb2017-11-20 18:20:221379 } else {
Steve Antonf9381f02017-12-14 18:23:571380 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 18:20:221392 }
Harald Alvestrand7a1c7f72018-08-01 08:50:161393 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 18:23:571394 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 23:35:421406}
1407
Steve Anton9158ef62017-11-27 21:01:521408RTCErrorOr<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 21:48:581418 RTC_CHECK(IsUnifiedPlan())
1419 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521420 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 21:48:581443 RTC_CHECK(IsUnifiedPlan())
1444 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 21:01:521445 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 21:58:071457 const RtpTransceiverInit& init,
1458 bool fire_callback) {
Steve Anton9158ef62017-11-27 21:01:521459 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 20:47:201469 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 21:01:521490
Steve Anton3d954a62018-04-02 18:27:231491 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1492 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 18:13:501493 // 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 20:47:201498 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1499 init.send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061500 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 21:58:071504 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161505 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 21:58:071506 }
Steve Antonf9381f02017-12-14 18:23:571507
1508 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1509}
1510
Steve Anton02ee47c2018-01-11 00:26:061511rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1512PeerConnection::CreateSender(
1513 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 20:03:361514 const std::string& id,
Steve Anton02ee47c2018-01-11 00:26:061515 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 20:47:201516 const std::vector<std::string>& stream_ids,
1517 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 21:01:521518 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-11 00:26:061519 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 20:03:361524 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 12:00:341525 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061526 } 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 20:03:361531 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 12:00:341532 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-11 00:26:061533 }
Steve Anton111fdfd2018-06-25 20:03:361534 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 20:47:201537 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-11 00:26:061538 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 21:01:521544 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1545 receiver;
Steve Anton9158ef62017-11-27 21:01:521546 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 21:01:521547 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531548 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1549 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341550 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521551 } else {
Steve Anton02ee47c2018-01-11 00:26:061552 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 21:01:521553 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 18:51:531554 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1555 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 12:00:341556 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 21:01:521557 }
Steve Anton02ee47c2018-01-11 00:26:061558 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 18:13:501566 // 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-11 00:26:061571 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1572 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 21:01:521573 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 23:48:121574 transceiver->internal()->SignalNegotiationNeeded.connect(
1575 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 18:23:571576 return transceiver;
Steve Anton9158ef62017-11-27 21:01:521577}
1578
Steve Anton52d86772018-02-20 23:48:121579void PeerConnection::OnNegotiationNeeded() {
1580 RTC_DCHECK_RUN_ON(signaling_thread());
1581 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 08:50:161582 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 23:48:121583}
1584
deadbeeffac06552015-11-25 19:26:011585rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-19 00:58:441586 const std::string& kind,
1587 const std::string& stream_id) {
Steve Antonfc853712018-03-01 21:48:581588 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1589 "Plan SdpSemantics. Please use AddTransceiver "
1590 "instead.";
Peter Boström1a9d6152015-12-08 21:15:171591 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 18:07:251592 if (IsClosed()) {
1593 return nullptr;
1594 }
Steve Anton4171afb2017-11-20 18:20:221595
Seth Hampson5b4f0752018-04-02 23:31:361596 // 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 19:34:101598 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 23:31:361599 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 19:34:101605 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-11 00:26:061606 }
1607
Steve Anton4171afb2017-11-20 18:20:221608 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 21:27:391609 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 19:26:011610 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 20:03:361611 auto* audio_sender = new AudioRtpSender(
1612 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-14 00:26:051613 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 21:27:391614 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061615 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 18:20:221616 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011617 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 18:49:351618 auto* video_sender =
Steve Anton111fdfd2018-06-25 20:03:361619 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-14 00:26:051620 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 21:27:391621 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-11 00:26:061622 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 18:20:221623 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 19:26:011624 } else {
Mirko Bonadei675513b2017-11-09 10:09:251625 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 18:20:221626 return nullptr;
deadbeeffac06552015-11-25 19:26:011627 }
Steve Anton111fdfd2018-06-25 20:03:361628 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 18:20:221629
deadbeefe1f9d832016-01-14 23:35:421630 return new_sender;
deadbeeffac06552015-11-25 19:26:011631}
1632
deadbeef70ab1a12015-09-28 23:53:551633std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1634 const {
deadbeefa601f5c2016-06-06 21:27:391635 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221636 for (auto sender : GetSendersInternal()) {
1637 ret.push_back(sender);
deadbeefa601f5c2016-06-06 21:27:391638 }
1639 return ret;
deadbeef70ab1a12015-09-28 23:53:551640}
1641
Steve Anton4171afb2017-11-20 18:20:221642std::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 23:53:551653std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1654PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 21:27:391655 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 18:20:221656 for (const auto& receiver : GetReceiversInternal()) {
1657 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 21:27:391658 }
1659 return ret;
deadbeef70ab1a12015-09-28 23:53:551660}
1661
Steve Anton4171afb2017-11-20 18:20:221662std::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 21:01:521676std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1677PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 21:48:581678 RTC_CHECK(IsUnifiedPlan())
1679 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 21:01:521680 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:361687bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:491688 MediaStreamTrackInterface* track,
1689 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 21:15:171690 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 18:38:281691 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 08:57:561692 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251693 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361694 return false;
1695 }
1696
tommi@webrtc.org03505bc2014-07-14 20:15:261697 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 18:38:151698 // 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 10:09:251701 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1702 << track->id();
zhihuange9e94c32016-11-04 18:38:151703 return false;
1704 }
Steve Antonad182762018-09-05 20:22:401705 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1706 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:361707 return true;
1708}
1709
hbos74e1a4f2016-09-16 06:33:011710void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 12:24:201711 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-16 06:33:011712 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 12:24:201713 RTC_DCHECK(callback);
hbos74e1a4f2016-09-16 06:33:011714 stats_collector_->GetStatsReport(callback);
1715}
1716
Henrik Boström1df1bf82018-03-20 12:24:201717void 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 10:29:551737 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 12:24:201738 // 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 10:29:551765 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 12:24:201766 // 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:361773PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1774 return signaling_state_;
1775}
1776
henrike@webrtc.org28e20752013-07-10 00:45:361777PeerConnectionInterface::IceConnectionState
1778PeerConnection::ice_connection_state() {
1779 return ice_connection_state_;
1780}
1781
Alex Loiko9289eda2018-11-23 16:18:591782PeerConnectionInterface::IceConnectionState
1783PeerConnection::standardized_ice_connection_state() {
1784 return standardized_ice_connection_state_;
1785}
1786
Jonas Olsson635474e2018-10-18 13:58:171787PeerConnectionInterface::PeerConnectionState
1788PeerConnection::peer_connection_state() {
1789 return connection_state_;
1790}
1791
henrike@webrtc.org28e20752013-07-10 00:45:361792PeerConnectionInterface::IceGatheringState
1793PeerConnection::ice_gathering_state() {
1794 return ice_gathering_state_;
1795}
1796
Yves Gerey665174f2018-06-19 13:03:051797rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:361798 const std::string& label,
1799 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 21:15:171800 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 18:14:501801
deadbeefab9b2d12015-10-14 18:33:111802 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111803
kwibergd1fe2812016-04-27 13:47:291804 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:581805 if (config) {
1806 internal_config.reset(new InternalDataChannelInit(*config));
1807 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:521808 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 18:33:111809 InternalCreateDataChannel(label, internal_config.get()));
1810 if (!channel.get()) {
1811 return nullptr;
1812 }
henrike@webrtc.org28e20752013-07-10 00:45:361813
jiayl@webrtc.org001fd2d2014-05-29 15:31:111814 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1815 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 18:37:171816 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 08:50:161817 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:111818 }
Harald Alvestrand8ebba742018-05-31 12:00:341819 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:361820 return DataChannelProxy::Create(signaling_thread(), channel.get());
1821}
1822
1823void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161824 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 21:15:171825 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 22:30:511826
nisse7ce109a2017-01-31 08:57:561827 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251828 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:161829 return;
1830 }
deadbeefab9b2d12015-10-14 18:33:111831
Steve Anton8d3444d2017-10-20 22:30:511832 if (IsClosed()) {
1833 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 10:09:251834 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031835 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101836 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511837 return;
1838 }
1839
zhihuang1c378ed2017-08-17 21:10:501840 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 18:33:111841 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 10:09:251842 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031843 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101844 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 18:33:111845 return;
1846 }
1847
Steve Anton22da89f2018-01-25 21:58:071848 // 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 14:18:031853 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 21:58:071854 return;
1855 }
1856 }
1857
zhihuang1c378ed2017-08-17 21:10:501858 cricket::MediaSessionOptions session_options;
1859 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 22:50:291860 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361861}
1862
Steve Anton22da89f2018-01-25 21:58:071863RTCError 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 18:27:231893 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 21:58:071906 }
1907}
1908
1909void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1910 cricket::MediaType media_type) {
1911 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 18:27:231912 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 21:58:071915 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 19:43:081927 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 21:58:071928 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1929 receiving_transceivers.push_back(transceiver);
1930 }
1931 }
1932 return receiving_transceivers;
1933}
1934
htaa2a49d92016-03-04 10:51:391935void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1936 const RTCOfferAnswerOptions& options) {
1937 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 08:57:561938 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251939 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 10:51:391940 return;
1941 }
1942
Steve Antondffead82018-02-06 18:31:291943 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 10:09:251948 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 14:18:031949 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 13:02:101950 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 22:30:511951 return;
1952 }
1953
Steve Antondffead82018-02-06 18:31:291954 // The remote description should be set if we're in the right state.
1955 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 22:30:511956
Steve Anton22da89f2018-01-25 21:58:071957 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 10:51:391970 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 21:10:501971 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 10:51:391972
Steve Antond25da372017-11-06 22:50:291973 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:361974}
1975
1976void PeerConnection::SetLocalDescription(
1977 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-17 01:08:421978 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 21:15:171979 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 23:25:561980
Steve Anton80dd7b52018-02-17 01:08:421981 // 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 08:57:561987 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:251988 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:361989 return;
1990 }
Steve Anton8a006912017-12-04 23:25:561991
henrike@webrtc.org28e20752013-07-10 00:45:361992 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 14:18:031993 PostSetSessionDescriptionFailure(
1994 observer,
1995 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:361996 return;
1997 }
Steve Anton8d3444d2017-10-20 22:30:511998
Steve Anton80dd7b52018-02-17 01:08:421999 // 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 14:18:032004 PostSetSessionDescriptionFailure(
2005 observer,
2006 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422007 return;
2008 }
Steve Anton8d3444d2017-10-20 22:30:512009
Steve Anton80dd7b52018-02-17 01:08:422010 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 14:18:032015 PostSetSessionDescriptionFailure(
2016 observer,
2017 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-17 01:08:422018 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 23:25:562026 // |desc| may be destroyed at this point.
2027
2028 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422029 // 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 14:18:032036 PostSetSessionDescriptionFailure(
2037 observer,
2038 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 22:30:512039 return;
2040 }
Steve Anton8a006912017-12-04 23:25:562041 RTC_DCHECK(local_description());
2042
2043 PostSetSessionDescriptionSuccess(observer);
2044
Steve Antonad182762018-09-05 20:22:402045 // 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 23:25:562048 transport_controller_->MaybeStartGathering();
2049
Steve Antona3a92c22017-12-07 18:27:412050 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562051 // 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 18:31:302056 // Make UMA notes about what was agreed to.
2057 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 23:25:562058 }
Harald Alvestrand8ebba742018-05-31 12:00:342059 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562060}
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:362067 // 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:262069 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562070
Steve Antondcc3c022017-12-23 00:02:542071 // 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 17:48:352079 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 18:34:512080 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-23 00:02:542081 replaced_local_description = pending_local_description_
2082 ? std::move(pending_local_description_)
2083 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 23:25:562084 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-23 00:02:542088 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 23:25:562089 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 18:55:442093 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 18:33:112094
Bjorn Mellem175aa2e2018-11-08 19:23:222095 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 17:48:352105 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2106 if (!error.ok()) {
2107 return error;
2108 }
2109
Steve Antondcc3c022017-12-23 00:02:542110 if (IsUnifiedPlan()) {
2111 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482112 cricket::CS_LOCAL, *local_description(), old_local_description,
2113 remote_description());
Steve Anton8a006912017-12-04 23:25:562114 if (!error.ok()) {
2115 return error;
2116 }
Steve Anton0f5400a2018-07-17 21:25:362117 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2118 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542119 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 21:25:362126 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2127 // the following steps:
Steve Antondcc3c022017-12-23 00:02:542128 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362129 // 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-23 00:02:542142 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 21:25:362143 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-23 00:02:542144 }
Steve Anton0f5400a2018-07-17 21:25:362145 }
Harald Alvestrand7a1c7f72018-08-01 08:50:162146 auto observer = Observer();
Steve Anton0f5400a2018-07-17 21:25:362147 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162148 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 21:25:362149 }
2150 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162151 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-23 00:02:542152 }
2153 } else {
Zhi Huange830e682018-03-30 17:48:352154 // Media channels will be created only when offer is set. These may use new
2155 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542156 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-23 00:02:542164 // Remove unused channels if MediaContentDescription is rejected.
2165 RemoveUnusedChannels(local_description()->description());
2166 }
Steve Anton8a006912017-12-04 23:25:562167
Zhi Huange830e682018-03-30 17:48:352168 error = UpdateSessionState(type, cricket::CS_LOCAL,
2169 local_description()->description());
Steve Anton8a006912017-12-04 23:25:562170 if (!error.ok()) {
2171 return error;
2172 }
Steve Antondcc3c022017-12-23 00:02:542173
Steve Anton8a006912017-12-04 23:25:562174 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 18:33:112184 // If setting the description decided our SSL role, allocate any necessary
2185 // SCTP sids.
2186 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222187 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112188 AllocateSctpSids(role);
2189 }
2190
Steve Antond3679212018-01-18 01:41:022191 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-25 02:32:572198 const auto& streams = content->media_description()->streams();
2199 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-18 01:41:022200 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 19:34:102201 streams[0].stream_ids());
Steve Antond3679212018-01-18 01:41:022202 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-25 02:32:572203 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 18:32:272204 } 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-18 01:41:022210 }
2211 }
2212 } else {
2213 // Plan B semantics.
2214
Steve Antondcc3c022017-12-23 00:02:542215 // 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 23:33:072227 }
deadbeefab9b2d12015-10-14 18:33:112228
Steve Antondcc3c022017-12-23 00:02:542229 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 23:33:072239 }
deadbeefab9b2d12015-10-14 18:33:112240 }
2241
2242 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 18:55:442243 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 18:33:112244 if (data_content) {
2245 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 23:14:302246 data_content->media_description()->as_data();
Steve Anton68586e82018-12-14 01:41:252247 if (absl::StartsWith(data_desc->protocol(),
deadbeefab9b2d12015-10-14 18:33:112248 cricket::kMediaProtocolRtpPrefix)) {
2249 UpdateLocalRtpDataChannels(data_desc->streams());
2250 }
2251 }
2252
Steve Anton8a006912017-12-04 23:25:562253 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:362254}
2255
Steve Anton06817cd2018-12-18 23:55:302256// 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:362306void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:072307 SetSessionDescriptionObserver* observer,
2308 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 16:48:322309 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 21:15:172318 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 23:25:562319
nisse7ce109a2017-01-31 08:57:562320 if (!observer) {
Mirko Bonadei675513b2017-11-09 10:09:252321 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:362322 return;
2323 }
Steve Anton8a006912017-12-04 23:25:562324
henrike@webrtc.org28e20752013-07-10 00:45:362325 if (!desc) {
Henrik Boström31638672017-11-23 16:48:322326 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 23:25:562327 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:362328 return;
2329 }
Steve Anton8d3444d2017-10-20 22:30:512330
Steve Anton80dd7b52018-02-17 01:08:422331 // 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 19:53:062340
Steve Antonba42e992018-04-09 21:10:012341 if (desc->GetType() == SdpType::kOffer) {
2342 // Report to UMA the format of the received offer.
2343 ReportSdpFormatReceived(*desc);
2344 }
2345
Steve Anton06817cd2018-12-18 23:55:302346 // Handle remote descriptions missing a=mid lines for interop with legacy end
2347 // points.
2348 FillInMissingRemoteMids(desc->description());
2349
Steve Anton80dd7b52018-02-17 01:08:422350 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 19:53:062351 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:422352 std::string error_message = GetSetDescriptionErrorMessage(
2353 cricket::CS_REMOTE, desc->GetType(), error);
2354 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 19:53:062355 observer->OnSetRemoteDescriptionComplete(
2356 RTCError(error.type(), std::move(error_message)));
2357 return;
2358 }
Steve Anton71439a62018-02-15 19:53:062359
Steve Anton80dd7b52018-02-17 01:08:422360 // 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 23:25:562382 // 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 22:48:002387 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 18:31:302388 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 23:25:562389 }
2390
2391 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 12:00:342392 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 23:25:562393}
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:362400 // 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:262402 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 23:25:562403
Steve Antondcc3c022017-12-23 00:02:542404 // 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 23:25:562409 const SessionDescriptionInterface* old_remote_description =
2410 remote_description();
Steve Anton8a006912017-12-04 23:25:562411 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 18:34:512412 SdpType type = desc->GetType();
2413 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 23:25:562414 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:362423 }
Steve Anton8a006912017-12-04 23:25:562424 // The session description to apply now must be accessed by
2425 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 18:55:442426 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:362427
Zhi Huange830e682018-03-30 17:48:352428 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2429 if (!error.ok()) {
2430 return error;
2431 }
Steve Anton8a006912017-12-04 23:25:562432 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-23 00:02:542433 if (IsUnifiedPlan()) {
2434 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 23:33:482435 cricket::CS_REMOTE, *remote_description(), local_description(),
2436 old_remote_description);
Steve Anton8a006912017-12-04 23:25:562437 if (!error.ok()) {
2438 return error;
2439 }
Steve Antondcc3c022017-12-23 00:02:542440 } else {
Zhi Huange830e682018-03-30 17:48:352441 // Media channels will be created only when offer is set. These may use new
2442 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-23 00:02:542443 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 17:48:352444 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-23 00:02:542445 // 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-23 00:02:542451 // Remove unused channels if MediaContentDescription is rejected.
2452 RemoveUnusedChannels(remote_description()->description());
2453 }
Steve Anton8a006912017-12-04 23:25:562454
Zhi Huange830e682018-03-30 17:48:352455 // 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 23:25:562459 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 18:34:512478 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 23:25:562479 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 18:27:412507 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 21:32:172508 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 23:25:562509 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2510 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2511 }
2512
deadbeefab9b2d12015-10-14 18:33:112513 // If setting the description decided our SSL role, allocate any necessary
2514 // SCTP sids.
2515 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 19:23:222516 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 18:33:112517 AllocateSctpSids(role);
2518 }
2519
Steve Antondcc3c022017-12-23 00:02:542520 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-17 00:14:422521 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 22:30:182522 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 21:25:362523 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 22:28:132524 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 22:30:182525 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-23 00:02:542526 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 10:06:022535 // 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-11 01:15:202544 }
Henrik Boströmafa07dd2018-12-20 10:06:022545 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 10:25:052560 }
Steve Antondcc3c022017-12-23 00:02:542561 }
Steve Anton0f5400a2018-07-17 21:25:362562 // 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-23 00:02:542566 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 21:25:362567 (transceiver->fired_direction() &&
2568 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2569 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2570 &removed_streams);
Steve Antondcc3c022017-12-23 00:02:542571 }
Steve Anton0f5400a2018-07-17 21:25:362572 // 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-23 00:02:542576 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 21:25:362577 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2578 // direction.
Steve Antondcc3c022017-12-23 00:02:542579 transceiver->internal()->set_current_direction(local_direction);
2580 }
Steve Anton0f5400a2018-07-17 21:25:362581 // 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-23 00:02:542583 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 18:27:232584 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2585 << " since the media section was rejected.";
Steve Antondcc3c022017-12-23 00:02:542586 transceiver->Stop();
2587 }
Seth Hampson2f0d7022018-02-20 19:54:422588 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 18:16:332592 if (!media_desc->streams().empty() &&
2593 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 19:54:422594 ssrc = media_desc->streams()[0].first_ssrc();
2595 }
2596 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-18 01:41:022597 }
Steve Antondcc3c022017-12-23 00:02:542598 }
Steve Antonc49bcd92018-02-14 22:28:132599 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 08:50:162600 auto observer = Observer();
Steve Anton3172c032018-05-03 22:30:182601 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 20:59:162602 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 08:50:162603 observer->OnTrack(transceiver);
2604 observer->OnAddTrack(transceiver->receiver(),
2605 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-11 01:15:202606 }
Steve Antonc49bcd92018-02-14 22:28:132607 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162608 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 22:28:132609 }
Steve Anton0f5400a2018-07-17 21:25:362610 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162611 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 22:30:182612 }
2613 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 08:50:162614 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 22:30:182615 }
Steve Antondcc3c022017-12-23 00:02:542616 }
2617
Henrik Boströmfdb92012017-11-09 18:55:442618 const cricket::ContentInfo* audio_content =
2619 GetFirstAudioContent(remote_description()->description());
2620 const cricket::ContentInfo* video_content =
2621 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402622 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 18:55:442623 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402624 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 18:55:442625 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402626 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 18:55:442627 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-09 01:13:402628
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 18:55:442631 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-09 01:13:402632 (audio_desc && !audio_desc->streams().empty()) ||
2633 (video_desc && !video_desc->streams().empty())) {
2634 remote_peer_supports_msid_ = true;
2635 }
deadbeefab9b2d12015-10-14 18:33:112636
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-23 00:02:542641 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 22:30:512649
Steve Antondcc3c022017-12-23 00:02:542650 // 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 23:33:072663 }
deadbeefab9b2d12015-10-14 18:33:112664
Steve Antondcc3c022017-12-23 00:02:542665 // 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 23:33:072678 }
deadbeefab9b2d12015-10-14 18:33:112679
Steve Antondcc3c022017-12-23 00:02:542680 // Update the DataChannels with the information from the remote peer.
2681 if (data_desc) {
Steve Anton68586e82018-12-14 01:41:252682 if (absl::StartsWith(data_desc->protocol(),
Steve Antondcc3c022017-12-23 00:02:542683 cricket::kMediaProtocolRtpPrefix)) {
2684 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2685 }
deadbeefab9b2d12015-10-14 18:33:112686 }
deadbeefab9b2d12015-10-14 18:33:112687
Steve Antondcc3c022017-12-23 00:02:542688 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 08:50:162689 auto observer = Observer();
Steve Antondcc3c022017-12-23 00:02:542690 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 08:50:162693 observer->OnAddStream(
Steve Antondcc3c022017-12-23 00:02:542694 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2695 }
deadbeefab9b2d12015-10-14 18:33:112696
Steve Antondcc3c022017-12-23 00:02:542697 UpdateEndedRemoteMediaStreams();
2698 }
deadbeefab9b2d12015-10-14 18:33:112699
Steve Anton8a006912017-12-04 23:25:562700 return RTCError::OK();
deadbeeffc648b62015-10-13 23:42:332701}
2702
Henrik Boströmafa07dd2018-12-20 10:06:022703void 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 21:25:362743void 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 10:06:022751 std::vector<rtc::scoped_refptr<MediaStreamInterface>> previous_streams =
Steve Anton0f5400a2018-07-17 21:25:362752 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 10:06:022756 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 21:25:362770 }
2771 }
2772}
2773
Steve Antondcc3c022017-12-23 00:02:542774RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2775 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482776 const SessionDescriptionInterface& new_session,
2777 const SessionDescriptionInterface* old_local_description,
2778 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-23 00:02:542779 RTC_DCHECK(IsUnifiedPlan());
2780
Steve Anton7464fca2018-01-19 19:10:372781 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-23 00:02:542789 }
Steve Antondcc3c022017-12-23 00:02:542790
Steve Antondcc3c022017-12-23 00:02:542791 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-23 00:02:542792 for (size_t i = 0; i < new_contents.size(); ++i) {
2793 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-23 00:02:542794 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 23:33:482798 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-23 00:02:542810 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 23:33:482811 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2812 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-23 00:02:542813 if (!transceiver_or_error.ok()) {
2814 return transceiver_or_error.MoveError();
2815 }
2816 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-23 00:02:542817 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-29 00:38:232823 if (GetDataMid() && new_content.name != *GetDataMid()) {
2824 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 18:27:232825 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2826 << new_content.name;
Steve Antonfa2260d2017-12-29 00:38:232827 continue;
2828 }
2829 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2830 if (!error.ok()) {
2831 return error;
2832 }
Steve Antondcc3c022017-12-23 00:02:542833 } 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-14 00:26:052849 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:542850 if (content.rejected) {
2851 if (channel) {
2852 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:052853 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-23 00:02:542854 }
2855 } else {
2856 if (!channel) {
Steve Anton69470252018-02-09 19:43:082857 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 17:48:352858 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542859 } else {
Steve Anton69470252018-02-09 19:43:082860 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 17:48:352861 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-23 00:02:542862 }
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-29 00:38:232874RTCError 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 23:23:402879 // If data channels are disabled, ignore this media section. CreateAnswer
2880 // will take care of rejecting it.
2881 return RTCError::OK();
Steve Antonfa2260d2017-12-29 00:38:232882 }
2883 if (content.rejected) {
2884 DestroyDataChannel();
2885 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:222886 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:352887 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-29 00:38:232888 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-23 00:02:542902RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2903PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 23:33:482904 SdpType type,
Steve Antondcc3c022017-12-23 00:02:542905 size_t mline_index,
2906 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 23:33:482907 const ContentInfo* old_local_content,
2908 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-23 00:02:542909 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 23:33:482910 // 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-23 00:02:542923 if (old_transceiver) {
Steve Anton3d954a62018-04-02 18:27:232924 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2925 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 14:47:432926 old_transceiver->internal()->set_mid(absl::nullopt);
2927 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-23 00:02:542928 }
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 18:27:232954 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 20:03:362959 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 20:47:202960 auto sender =
2961 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 18:58:302962 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-11 00:26:062969 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-23 00:02:542970 transceiver->internal()->set_direction(
2971 RtpTransceiverDirection::kRecvOnly);
2972 }
2973 }
2974 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 19:43:082975 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-23 00:02:542976 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 19:43:083021 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-23 00:02:543022 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
3023 !transceiver->stopped()) {
3024 return transceiver;
3025 }
3026 }
3027 return nullptr;
3028}
3029
Steve Antoned10bd92017-12-05 18:52:593030const 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 19:43:083047 transceiver->media_type());
Steve Antoned10bd92017-12-05 18:52:593048 }
3049}
3050
deadbeef46c73892016-11-17 03:42:043051PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
3052 return configuration_;
3053}
3054
deadbeef293e9262017-01-11 20:28:303055bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
3056 RTCError* error) {
Peter Boström1a9d6152015-12-08 21:15:173057 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 16:54:103058 if (IsClosed()) {
3059 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
3060 return SafeSetError(RTCErrorType::INVALID_STATE, error);
3061 }
3062
Qingsi Wanga2d60672018-04-11 23:57:453063 // 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 18:37:173066 if (local_description() && configuration.ice_candidate_pool_size !=
3067 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 10:09:253068 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
3069 "SetLocalDescription.";
deadbeef293e9262017-01-11 20:28:303070 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:453071 }
Taylor Brandstettera1c30352016-05-13 15:15:113072
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453073 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 17:16:443087 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 16:07:483088 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 17:16:443104 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 15:42:223110 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 20:28:303116 // 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-04 00:54:053126 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 22:55:143127 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 17:53:573131 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-07 07:30:173134 modified_config.ice_inactive_timeout = configuration.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:493135 modified_config.stun_candidate_keepalive_interval =
3136 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 12:01:403137 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 18:38:403138 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 18:41:113139 modified_config.active_reset_srtp_params =
3140 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 17:04:453141 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 16:07:483142 modified_config.use_media_transport_for_data_channels =
3143 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 20:28:303144 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 10:09:253145 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 20:28:303146 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3147 }
3148
Steve Anton038834f2017-07-14 22:59:593149 // 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 20:28:303155 // 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 10:34:173158 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 20:28:303159 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 12:00:343170 // 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 20:28:303177
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 12:01:403184 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:493185 modified_config.turn_customizer,
3186 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 10:09:253187 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 20:28:303188 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3189 }
Honghai Zhang4cedf2b2016-08-31 15:18:113190
deadbeefd1a38b52016-12-10 21:15:333191 // 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 20:28:303194 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 22:50:293197 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 21:15:333198 }
skvladd1f5fda2017-02-04 00:54:053199
Qingsi Wang9c98f0c2018-02-15 23:10:593200 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 19:57:593201 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 16:07:483202 modified_config.use_media_transport ||
3203 modified_config.use_media_transport_for_data_channels
3204 ? factory_->media_transport_factory()
3205 : nullptr);
skvladd1f5fda2017-02-04 00:54:053206
Zhi Huangb57e1692018-06-12 18:41:113207 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 20:28:303213 configuration_ = modified_config;
3214 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:453215}
3216
henrike@webrtc.org28e20752013-07-10 00:45:363217bool PeerConnection::AddIceCandidate(
3218 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 21:15:173219 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 18:07:253220 if (IsClosed()) {
Steve Antonc79268f2018-04-24 16:54:103221 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 21:24:363222 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 18:07:253223 return false;
3224 }
Steve Antond25da372017-11-06 22:50:293225
3226 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103227 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 09:37:073228 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 21:24:363229 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 22:50:293230 return false;
3231 }
3232
3233 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 16:54:103234 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 21:24:363235 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 22:50:293236 return false;
3237 }
3238
3239 bool valid = false;
3240 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3241 if (!valid) {
Harald Alvestrand76829d72018-07-18 21:24:363242 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 22:50:293243 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 16:54:103248 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 21:24:363249 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 22:50:293250 return false;
3251 }
3252
3253 if (ready) {
Harald Alvestrand76829d72018-07-18 21:24:363254 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 22:50:293262 } else {
Steve Antonc79268f2018-04-24 16:54:103263 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 21:24:363264 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 22:50:293265 return true;
3266 }
henrike@webrtc.org28e20752013-07-10 00:45:363267}
3268
Honghai Zhang7fb69db2016-03-14 18:59:183269bool PeerConnection::RemoveIceCandidates(
3270 const std::vector<cricket::Candidate>& candidates) {
3271 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 16:54:103272 if (IsClosed()) {
3273 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3274 return false;
3275 }
3276
Steve Antond25da372017-11-06 22:50:293277 if (!remote_description()) {
Steve Antonc79268f2018-04-24 16:54:103278 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3279 "without any remote session description.";
Steve Antond25da372017-11-06 22:50:293280 return false;
3281 }
3282
3283 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 16:54:103284 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 22:50:293285 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 10:09:253291 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 16:54:103292 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 09:37:073293 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 10:09:253294 << " are removed.";
Steve Antond25da372017-11-06 22:50:293295 }
3296
3297 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 17:48:353298 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3299 if (!error.ok()) {
Steve Antonc79268f2018-04-24 16:54:103300 RTC_LOG(LS_ERROR)
3301 << "RemoveIceCandidates: Error when removing remote candidates: "
3302 << error.message();
Steve Antond25da372017-11-06 22:50:293303 }
3304 return true;
Honghai Zhang7fb69db2016-03-14 18:59:183305}
3306
Niels Möller0c4f7be2018-05-07 12:01:373307RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 19:15:023308 if (!worker_thread()->IsCurrent()) {
3309 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 13:03:053310 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 21:37:373311 }
3312
Niels Möller0c4f7be2018-05-07 12:01:373313 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 21:37:373316 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 12:01:373320 if (has_start) {
3321 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 21:37:373322 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373323 "start_bitrate_bps < min_bitrate_bps");
3324 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 21:37:373325 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3326 "curent_bitrate_bps < 0");
3327 }
3328 }
3329 if (has_max) {
Yves Gerey665174f2018-06-19 13:03:053330 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 21:37:373331 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 12:01:373332 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 21:37:373333 } 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 21:37:373342 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 12:01:373343 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 21:37:373344
3345 return RTCError::OK();
3346}
3347
Alex Narest78609d52017-10-20 08:37:473348void 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 09:40:333357 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 08:37:473358 };
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 10:06:563366void 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 10:29:553374 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563375 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 10:29:553386 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 10:06:563387 audio_state->SetRecording(recording);
3388}
3389
Steve Anton8c0f7a72017-10-03 17:03:103390std::unique_ptr<rtc::SSLCertificate>
3391PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 21:04:513392 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3393 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 17:03:103394 return nullptr;
3395 }
Steve Antonf25303e2018-10-16 22:23:313396 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 17:03:103397}
3398
Zhi Huang70b820f2018-01-27 22:16:153399std::unique_ptr<rtc::SSLCertChain>
3400PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 19:35:373401 auto audio_transceiver = GetFirstAudioTransceiver();
3402 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 22:16:153403 return nullptr;
3404 }
Zhi Huang70b820f2018-01-27 22:16:153405 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 19:35:373406 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 22:16:153417}
3418
ivoc14d5dbe2016-07-04 14:06:553419bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3420 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 14:29:403421 // 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 14:43:013425 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 14:29:403429 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 09:40:333430 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Terelius8b556022018-11-27 14:43:013431 output_period_ms);
Elad Alon99c3fe52017-10-13 14:29:403432}
3433
Bjorn Tereliusde939432017-11-20 16:38:143434bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3435 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 21:01:063436 // TODO(eladalon): In C++14, this can be done with a lambda.
3437 struct Functor {
Bjorn Tereliusde939432017-11-20 16:38:143438 bool operator()() {
3439 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3440 }
Karl Wibergd6b48192017-10-16 21:01:063441 PeerConnection* const pc;
3442 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 16:38:143443 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 14:29:403444 };
Bjorn Tereliusde939432017-11-20 16:38:143445 return worker_thread()->Invoke<bool>(
3446 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 14:06:553447}
3448
3449void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 19:15:023450 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 14:06:553451 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3452}
3453
Harald Alvestrandad88c882018-11-28 15:47:463454rtc::scoped_refptr<DtlsTransportInterface>
3455PeerConnection::LookupDtlsTransportByMid(const std::string& mid) {
3456 return transport_controller_->LookupDtlsTransportByMid(mid);
3457}
3458
henrike@webrtc.org28e20752013-07-10 00:45:363459const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 18:37:173460 return pending_local_description_ ? pending_local_description_.get()
3461 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363462}
3463
3464const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 18:37:173465 return pending_remote_description_ ? pending_remote_description_.get()
3466 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:363467}
3468
deadbeeffe4a8a42016-12-21 01:56:173469const SessionDescriptionInterface* PeerConnection::current_local_description()
3470 const {
Steve Anton75737c02017-11-06 18:37:173471 return current_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173472}
3473
3474const SessionDescriptionInterface* PeerConnection::current_remote_description()
3475 const {
Steve Anton75737c02017-11-06 18:37:173476 return current_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173477}
3478
3479const SessionDescriptionInterface* PeerConnection::pending_local_description()
3480 const {
Steve Anton75737c02017-11-06 18:37:173481 return pending_local_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173482}
3483
3484const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3485 const {
Steve Anton75737c02017-11-06 18:37:173486 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-21 01:56:173487}
3488
henrike@webrtc.org28e20752013-07-10 00:45:363489void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 21:15:173490 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:363491 // 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:263493 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:363494
Steve Anton75737c02017-11-06 18:37:173495 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 12:00:343496 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 18:20:083497
Steve Anton8af21862017-12-15 19:20:133498 for (auto transceiver : transceivers_) {
3499 transceiver->Stop();
3500 }
Steve Anton25cfeb92018-04-26 18:44:003501
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 19:20:133510 DestroyAllChannels();
Steve Anton75737c02017-11-06 18:37:173511
Qingsi Wang93a84392018-01-31 01:13:093512 // 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 23:18:003520 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 13:03:053521 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3522 port_allocator_.get()));
nisseeaabdf62017-05-05 09:23:023523
Steve Anton978b8762017-09-29 19:15:023524 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 12:18:153525 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 12:00:343529 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 08:50:163530 // 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:363533}
3534
Steve Antonad182762018-09-05 20:22:403535void 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 19:35:373580cricket::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 18:20:223602void PeerConnection::CreateAudioReceiver(
3603 MediaStreamInterface* stream,
3604 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513605 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3606 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533607 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3608 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023609 auto* audio_receiver = new AudioRtpReceiver(
3610 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053611 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-18 01:41:023612 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3613 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3614 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 18:20:223615 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163616 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343617 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363618}
3619
Steve Anton4171afb2017-11-20 18:20:223620void PeerConnection::CreateVideoReceiver(
3621 MediaStreamInterface* stream,
3622 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 12:41:513623 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3624 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 18:51:533625 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3626 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-18 01:41:023627 auto* video_receiver = new VideoRtpReceiver(
3628 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-14 00:26:053629 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-18 01:41:023630 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3631 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3632 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 18:20:223633 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 08:50:163634 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 12:00:343635 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:363636}
3637
deadbeef70ab1a12015-09-28 23:53:553638// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3639// description.
Henrik Boström933d8b02017-10-10 17:05:163640rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 18:20:223641 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 17:05:163646 return nullptr;
deadbeef70ab1a12015-09-28 23:53:553647 }
Steve Anton4171afb2017-11-20 18:20:223648 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 17:05:163653 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:363654}
3655
korniltsev.anatolyec390b52017-07-25 00:00:253656void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3657 MediaStreamInterface* stream) {
3658 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363659 RTC_DCHECK(track);
3660 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253661 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223662 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253663 // 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 23:31:363665 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253666 return;
3667 }
3668
3669 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363670 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:203671 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:053672 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 18:20:223673 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-25 00:00:253674 // 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 18:20:223680 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183681 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223682 if (sender_info) {
3683 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253684 }
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 18:20:223693 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253694 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3695 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253696 return;
3697 }
Steve Anton4171afb2017-11-20 18:20:223698 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253699}
3700
3701void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3702 MediaStreamInterface* stream) {
3703 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 20:03:363704 RTC_DCHECK(track);
3705 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-25 00:00:253706 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223707 if (sender) {
korniltsev.anatolyec390b52017-07-25 00:00:253708 // 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 23:31:363710 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-25 00:00:253711 return;
3712 }
3713
3714 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 20:03:363715 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 20:47:203716 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-14 00:26:053717 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 18:20:223718 GetVideoTransceiver()->internal()->AddSender(new_sender);
3719 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:183720 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 18:20:223721 if (sender_info) {
3722 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-25 00:00:253723 }
3724}
3725
3726void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3727 MediaStreamInterface* stream) {
3728 RTC_DCHECK(!IsClosed());
3729 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 18:20:223730 if (!sender) {
Mirko Bonadei675513b2017-11-09 10:09:253731 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3732 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-25 00:00:253733 return;
3734 }
Steve Anton4171afb2017-11-20 18:20:223735 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-25 00:00:253736}
3737
Steve Antonba818672017-11-06 18:21:573738void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283739 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 18:21:573740 if (ice_connection_state_ == new_state) {
3741 return;
3742 }
3743
deadbeefcbecd352015-09-23 18:50:273744 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 18:21:573745 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 18:33:113746 if (IsClosed()) {
deadbeefcbecd352015-09-23 18:50:273747 return;
3748 }
Steve Antonba818672017-11-06 18:21:573749
Mirko Bonadei675513b2017-11-09 10:09:253750 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3751 << " => " << new_state;
Steve Antonba818672017-11-06 18:21:573752 RTC_DCHECK(ice_connection_state_ !=
3753 PeerConnectionInterface::kIceConnectionClosed);
3754
henrike@webrtc.org28e20752013-07-10 00:45:363755 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163756 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363757}
3758
Alex Loiko9289eda2018-11-23 16:18:593759void 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 10:25:143767 Observer()->OnStandardizedIceConnectionChange(new_state);
Alex Loiko9289eda2018-11-23 16:18:593768}
3769
Jonas Olsson635474e2018-10-18 13:58:173770void 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:363781void PeerConnection::OnIceGatheringChange(
3782 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 18:38:283783 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:363784 if (IsClosed()) {
3785 return;
3786 }
3787 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 08:50:163788 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363789}
3790
jbauch81bf7b02017-03-25 15:31:123791void PeerConnection::OnIceCandidate(
3792 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 18:38:283793 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253794 if (IsClosed()) {
3795 return;
3796 }
Harald Alvestrand8ebba742018-05-31 12:00:343797 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 17:18:583798 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3799 candidate->candidate().address().IsPrivateIP()) {
3800 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3801 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163802 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:363803}
3804
Honghai Zhang7fb69db2016-03-14 18:59:183805void PeerConnection::OnIceCandidatesRemoved(
3806 const std::vector<cricket::Candidate>& candidates) {
3807 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 18:07:253808 if (IsClosed()) {
3809 return;
3810 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163811 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 18:59:183812}
3813
henrike@webrtc.org28e20752013-07-10 00:45:363814void PeerConnection::ChangeSignalingState(
3815 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 18:21:573816 RTC_DCHECK(signaling_thread()->IsCurrent());
3817 if (signaling_state_ == signaling_state) {
3818 return;
3819 }
Mirko Bonadei675513b2017-11-09 10:09:253820 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:363824 signaling_state_ = signaling_state;
3825 if (signaling_state == kClosed) {
3826 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 08:50:163827 Observer()->OnIceConnectionChange(ice_connection_state_);
Alex Loiko9289eda2018-11-23 16:18:593828 standardized_ice_connection_state_ =
3829 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
Jonas Olsson635474e2018-10-18 13:58:173830 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3831 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363832 if (ice_gathering_state_ != kIceGatheringComplete) {
3833 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 08:50:163834 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363835 }
3836 }
Harald Alvestrand7a1c7f72018-08-01 08:50:163837 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:363838}
3839
deadbeefeb459812015-12-16 03:24:433840void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3841 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253842 if (IsClosed()) {
3843 return;
3844 }
korniltsev.anatolyec390b52017-07-25 00:00:253845 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163846 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433847}
3848
deadbeefeb459812015-12-16 03:24:433849void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3850 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253851 if (IsClosed()) {
3852 return;
3853 }
korniltsev.anatolyec390b52017-07-25 00:00:253854 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163855 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433856}
3857
3858void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3859 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253860 if (IsClosed()) {
3861 return;
3862 }
korniltsev.anatolyec390b52017-07-25 00:00:253863 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163864 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433865}
3866
3867void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3868 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 18:07:253869 if (IsClosed()) {
3870 return;
3871 }
korniltsev.anatolyec390b52017-07-25 00:00:253872 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:163873 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-16 03:24:433874}
3875
Henrik Boström31638672017-11-23 16:48:323876void PeerConnection::PostSetSessionDescriptionSuccess(
3877 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:403878 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3879 signaling_thread()->Post(RTC_FROM_HERE, this,
3880 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 16:48:323881}
3882
deadbeefab9b2d12015-10-14 18:33:113883void PeerConnection::PostSetSessionDescriptionFailure(
3884 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:403885 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 14:18:033886 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403887 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 18:33:113891}
3892
3893void PeerConnection::PostCreateSessionDescriptionFailure(
3894 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 14:18:033895 RTCError error) {
3896 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:403897 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 18:33:113901}
3902
zhihuang1c378ed2017-08-17 21:10:503903void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-23 00:02:543904 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 18:33:113905 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-23 00:02:543906 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 21:10:503907
Steve Antondcc3c022017-12-23 00:02:543908 if (IsUnifiedPlan()) {
3909 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3910 } else {
3911 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3912 }
3913
Steve Antonfa2260d2017-12-29 00:38:233914 // 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-23 00:02:543923 // 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 17:16:443931 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:123932 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 09:25:483937 session_options->offer_extmap_allow_mixed =
3938 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-23 00:02:543939}
3940
3941void PeerConnection::GetOptionsForPlanBOffer(
3942 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3943 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:503944 // 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-23 00:02:543958 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 21:10:503961 offer_new_audio_description =
Steve Antondcc3c022017-12-23 00:02:543962 offer_new_audio_description ||
3963 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 21:10:503964 }
Steve Antondcc3c022017-12-23 00:02:543965 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 21:10:503968 offer_new_video_description =
Steve Antondcc3c022017-12-23 00:02:543969 offer_new_video_description ||
3970 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 21:10:503971 }
3972
Danil Chapovalov66cadcc2018-06-19 14:47:433973 absl::optional<size_t> audio_index;
3974 absl::optional<size_t> video_index;
3975 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 21:10:503976 // 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 18:37:173979 if (local_description()) {
zhihuang1c378ed2017-08-17 21:10:503980 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 18:37:173981 local_description(),
Steve Anton1d03a752017-11-27 22:30:093982 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3983 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3984 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 18:33:113985 }
3986
zhihuang1c378ed2017-08-17 21:10:503987 // 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 22:30:093992 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3993 false));
Oskar Sundbom9b28a032017-11-16 09:53:303994 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:453995 }
zhihuang1c378ed2017-08-17 21:10:503996 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 22:30:094000 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
4001 false));
Oskar Sundbom9b28a032017-11-16 09:53:304002 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 20:14:454003 }
zhihuang1c378ed2017-08-17 21:10:504004 if (!data_index && offer_new_data_description) {
4005 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234006 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 09:53:304007 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504008 }
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 21:10:504016
Steve Anton4171afb2017-11-20 18:20:224017 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:374018 video_media_description_options,
4019 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:544020}
4021
Steve Antondcc3c022017-12-23 00:02:544022static 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 19:43:084028 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-23 00:02:544029 transceiver->stopped());
Steve Anton5f94aa22018-02-01 18:58:304030 // 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 20:47:204041 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 18:58:304045 media_description_options.sender_options.push_back(sender_options);
4046 }
Steve Antondcc3c022017-12-23 00:02:544047 return media_description_options;
4048}
4049
Steve Anton5c72e712018-12-10 22:25:304050// 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-23 00:02:544061void 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 22:25:304088 const ContentInfo* current_local_content =
4089 GetContentByIndex(current_local_description(), i);
Steve Antondcc3c022017-12-23 00:02:544090 const ContentInfo* remote_content =
4091 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
Steve Anton5c72e712018-12-10 22:25:304092 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-23 00:02:544097 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 22:25:304107 // rejected in either the current local or current remote description.
Seth Hampsonae8a90a2018-02-13 23:33:484108 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-23 00:02:544109 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 19:43:084110 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
4111 RtpTransceiverDirection::kInactive,
4112 /*stopped=*/true));
Steve Antondcc3c022017-12-23 00:02:544113 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-29 00:38:234126 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-23 00:02:544134 }
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-29 00:38:234160 // 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-23 00:02:544166}
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-29 00:38:234179 // 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-23 00:02:544187 // 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-07 01:40:304192
4193 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 17:16:444194 session_options->crypto_options = GetCryptoOptions();
Jonas Oreland1cd39fa2018-10-11 05:47:124195 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 18:33:114200}
4201
Steve Antondcc3c022017-12-23 00:02:544202void PeerConnection::GetOptionsForPlanBAnswer(
4203 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 15:18:114204 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504205 // 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-23 00:02:544215 if (offer_answer_options.offer_to_receive_audio !=
4216 RTCOfferAnswerOptions::kUndefined) {
4217 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-24 01:24:524218 }
Steve Antondcc3c022017-12-23 00:02:544219 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 21:10:504222 }
4223
Danil Chapovalov66cadcc2018-06-19 14:47:434224 absl::optional<size_t> audio_index;
4225 absl::optional<size_t> video_index;
4226 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 18:31:294227
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 21:10:504236
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 21:10:504243
Steve Anton4171afb2017-11-20 18:20:224244 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 08:58:374245 video_media_description_options,
4246 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-23 00:02:544247}
zhihuangaf388472016-11-02 23:49:484248
Steve Antondcc3c022017-12-23 00:02:544249void 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 23:23:404267 // 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-29 00:38:234272 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-23 00:02:544278 }
4279 }
htaa2a49d92016-03-04 10:51:394280}
4281
zhihuang1c378ed2017-08-17 21:10:504282void PeerConnection::GenerateMediaDescriptionOptions(
4283 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 22:30:094284 RtpTransceiverDirection audio_direction,
4285 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 14:47:434286 absl::optional<size_t>* audio_index,
4287 absl::optional<size_t>* video_index,
4288 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 10:51:394289 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 21:10:504290 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 22:25:304298 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:504299 } else {
Steve Anton5c72e712018-12-10 22:25:304300 bool stopped = (audio_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:504301 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:304302 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_AUDIO,
4303 content.name, audio_direction,
4304 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:304305 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504306 }
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 22:25:304313 RtpTransceiverDirection::kInactive, /*stopped=*/true));
zhihuang1c378ed2017-08-17 21:10:504314 } else {
Steve Anton5c72e712018-12-10 22:25:304315 bool stopped = (video_direction == RtpTransceiverDirection::kInactive);
zhihuang1c378ed2017-08-17 21:10:504316 session_options->media_description_options.push_back(
Steve Anton5c72e712018-12-10 22:25:304317 cricket::MediaDescriptionOptions(cricket::MEDIA_TYPE_VIDEO,
4318 content.name, video_direction,
4319 stopped));
Oskar Sundbom9b28a032017-11-16 09:53:304320 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504321 }
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-29 00:38:234327 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 21:10:504328 } else {
4329 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-29 00:38:234330 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 09:53:304331 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 21:10:504332 }
4333 }
htaa2a49d92016-03-04 10:51:394334 }
deadbeefab9b2d12015-10-14 18:33:114335}
4336
Steve Antonfa2260d2017-12-29 00:38:234337cricket::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 14:47:434359absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-29 00:38:234360 switch (data_channel_type_) {
4361 case cricket::DCT_RTP:
4362 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 14:47:434363 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234364 }
4365 return rtp_data_channel_->content_name();
4366 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 17:48:354367 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 19:23:224368 case cricket::DCT_MEDIA_TRANSPORT:
4369 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-29 00:38:234370 default:
Danil Chapovalov66cadcc2018-06-19 14:47:434371 return absl::nullopt;
Steve Antonfa2260d2017-12-29 00:38:234372 }
4373}
4374
Steve Anton4171afb2017-11-20 18:20:224375void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4376 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4377 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-09 01:13:404378 media_type, nullptr);
deadbeeffaac4972015-11-12 23:33:074379}
4380
Steve Anton4171afb2017-11-20 18:20:224381void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 18:33:114382 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 18:20:224383 bool default_sender_needed,
deadbeefab9b2d12015-10-14 18:33:114384 cricket::MediaType media_type,
4385 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 23:31:364386 RTC_DCHECK(!IsUnifiedPlan());
4387
Steve Anton4171afb2017-11-20 18:20:224388 std::vector<RtpSenderInfo>* current_senders =
4389 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114390
Steve Anton4171afb2017-11-20 18:20:224391 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 19:26:014392 // the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224393 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 18:33:114397 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224398 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-06 01:12:094399 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 23:31:364405 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-06 01:12:094406 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-09 01:13:404407 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 19:34:104408 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 18:20:224409 sender_exists) {
4410 ++sender_it;
deadbeefbda7e0b2015-12-09 01:13:404411 } else {
Steve Anton4171afb2017-11-20 18:20:224412 OnRemoteSenderRemoved(info, media_type);
4413 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114414 }
4415 }
4416
Steve Anton4171afb2017-11-20 18:20:224417 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114418 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 18:16:334419 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 19:34:104427 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 23:31:364428 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 18:16:334429 // 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 19:34:104432 const std::string& stream_id =
Seth Hampson83d676b2018-04-06 01:12:094433 (!params.first_stream_id().empty() ? params.first_stream_id()
4434 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 18:20:224435 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114436 uint32_t ssrc = params.first_ssrc();
4437
4438 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 19:34:104439 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 18:33:114440 if (!stream) {
4441 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 10:16:194442 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 19:34:104443 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 18:33:114444 remote_streams_->AddStream(stream);
4445 new_streams->AddStream(stream);
4446 }
4447
Steve Anton4171afb2017-11-20 18:20:224448 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184449 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224450 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104451 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224452 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114453 }
4454 }
deadbeefbda7e0b2015-12-09 01:13:404455
Steve Anton4171afb2017-11-20 18:20:224456 // Add default sender if necessary.
4457 if (default_sender_needed) {
deadbeefbda7e0b2015-12-09 01:13:404458 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 19:34:104459 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-09 01:13:404460 if (!default_stream) {
4461 // Create the new default MediaStream.
perkjd61bf802016-03-24 10:16:194462 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 19:34:104463 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-09 01:13:404464 remote_streams_->AddStream(default_stream);
4465 new_streams->AddStream(default_stream);
4466 }
Steve Anton4171afb2017-11-20 18:20:224467 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4468 ? kDefaultAudioSenderId
4469 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 19:34:104470 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184471 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 18:20:224472 if (!default_sender_info) {
4473 current_senders->push_back(
Seth Hampson845e8782018-03-02 19:34:104474 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 18:20:224475 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-09 01:13:404476 }
4477 }
deadbeefab9b2d12015-10-14 18:33:114478}
4479
Steve Anton4171afb2017-11-20 18:20:224480void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4481 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 18:27:234482 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 18:33:114485
Steve Anton3d954a62018-04-02 18:27:234486 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114487 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224488 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114489 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224490 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 18:33:114491 } else {
nisseeb4ca4e2017-01-12 10:24:274492 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114493 }
4494}
4495
Steve Anton4171afb2017-11-20 18:20:224496void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4497 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-06 01:12:094498 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 19:34:104502 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 18:33:114503
Henrik Boström933d8b02017-10-10 17:05:164504 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 18:33:114505 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 10:16:194506 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4507 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224508 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114509 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 18:20:224510 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114511 if (audio_track) {
deadbeefab9b2d12015-10-14 18:33:114512 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 18:33:114513 }
4514 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 10:16:194515 // Stopping or destroying a VideoRtpReceiver will end the
4516 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 18:20:224517 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 18:33:114518 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 18:20:224519 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 18:33:114520 if (video_track) {
perkjd61bf802016-03-24 10:16:194521 // 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 18:33:114523 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 18:33:114524 }
4525 } else {
nisseede5da42017-01-12 13:15:364526 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 18:33:114527 }
Henrik Boström933d8b02017-10-10 17:05:164528 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 08:50:164529 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 17:05:164530 }
deadbeefab9b2d12015-10-14 18:33:114531}
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 20:02:214542 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 18:33:114543 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 08:50:164544 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 18:33:114545 }
4546}
4547
Steve Anton4171afb2017-11-20 18:20:224548void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 18:33:114549 const std::vector<cricket::StreamParams>& streams,
4550 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 18:20:224551 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 18:33:114552
Seth Hampson845e8782018-03-02 19:34:104553 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 18:33:114554 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 18:20:224555 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 18:33:114559 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 18:20:224560 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4561 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 19:34:104562 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 18:20:224563 OnLocalSenderRemoved(info, media_type);
4564 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 18:33:114565 } else {
Steve Anton4171afb2017-11-20 18:20:224566 ++sender_it;
deadbeefab9b2d12015-10-14 18:33:114567 }
4568 }
4569
Steve Anton4171afb2017-11-20 18:20:224570 // Find new and active senders.
deadbeefab9b2d12015-10-14 18:33:114571 for (const cricket::StreamParams& params : streams) {
4572 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 18:20:224573 // sender id.
Seth Hampson845e8782018-03-02 19:34:104574 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 18:20:224575 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 18:33:114576 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 18:20:224577 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609eaa2018-03-27 21:57:184578 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 18:20:224579 if (!sender_info) {
Seth Hampson845e8782018-03-02 19:34:104580 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 18:20:224581 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 18:33:114582 }
4583 }
4584}
4585
Steve Anton4171afb2017-11-20 18:20:224586void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4587 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 23:31:364588 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 18:20:224589 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014590 if (!sender) {
Steve Anton4171afb2017-11-20 18:20:224591 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4592 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 10:09:254593 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 18:33:114594 return;
4595 }
4596
deadbeeffac06552015-11-25 19:26:014597 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 10:09:254598 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074599 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014600 return;
deadbeefab9b2d12015-10-14 18:33:114601 }
deadbeeffac06552015-11-25 19:26:014602
Seth Hampson5b4f0752018-04-02 23:31:364603 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 18:20:224604 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 18:33:114605}
4606
Steve Anton4171afb2017-11-20 18:20:224607void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4608 cricket::MediaType media_type) {
4609 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 19:26:014610 if (!sender) {
4611 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 18:33:114612 // SessionDescriptions has been renegotiated.
4613 return;
4614 }
deadbeeffac06552015-11-25 19:26:014615
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 10:09:254620 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 09:37:074621 " description with an unexpected media type.";
deadbeeffac06552015-11-25 19:26:014622 return;
deadbeefab9b2d12015-10-14 18:33:114623 }
deadbeeffac06552015-11-25 19:26:014624
Steve Anton4171afb2017-11-20 18:20:224625 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 18:33:114626}
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 19:34:104639 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114640 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 08:57:564641 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 10:09:254642 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 18:33:114643 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 19:34:104661 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 18:33:114662 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 19:34:104663 : params.first_stream_id();
deadbeefab9b2d12015-10-14 18:33:114664 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 10:09:254709 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 09:37:074710 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 18:33:114711 return;
4712 }
4713 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 21:27:394714 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4715 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164716 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 18:33:114717}
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 18:37:174725 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 10:09:254726 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 18:33:114727 << "InternalCreateDataChannel: Data is not supported in this call.";
4728 return nullptr;
4729 }
4730 InternalDataChannelInit new_config =
4731 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 19:23:224732 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 18:33:114733 if (new_config.id < 0) {
4734 rtc::SSLRole role;
Steve Anton75737c02017-11-06 18:37:174735 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 18:33:114736 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254737 RTC_LOG(LS_ERROR)
4738 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 18:33:114739 return nullptr;
4740 }
4741 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 10:09:254742 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 09:37:074743 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 18:33:114744 return nullptr;
4745 }
4746 }
4747
Steve Anton75737c02017-11-06 18:37:174748 rtc::scoped_refptr<DataChannel> channel(
4749 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 18:33:114750 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 10:09:254757 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4758 << " already exists.";
deadbeefab9b2d12015-10-14 18:33:114759 return nullptr;
4760 }
4761 rtp_data_channels_[channel->label()] = channel;
4762 } else {
Bjorn Mellem175aa2e2018-11-08 19:23:224763 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 18:33:114764 sctp_data_channels_.push_back(channel);
4765 channel->SignalClosed.connect(this,
4766 &PeerConnection::OnSctpDataChannelClosed);
4767 }
4768
Steve Anton2d8609c2018-01-24 00:38:464769 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 18:33:114770 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 10:09:254782 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 18:33:114783 continue;
4784 }
4785 channel->SetSctpSid(sid);
4786 }
4787 }
4788}
4789
4790void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-15 02:15:294791 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 18:33:114792 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 20:23:324796 // After the closing procedure is done, it's safe to use this ID for
4797 // another data channel.
deadbeefab9b2d12015-10-14 18:33:114798 sid_allocator_.ReleaseSid(channel->id());
4799 }
deadbeefbd292462015-12-15 02:15:294800 // 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 18:33:114803 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:404804 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4805 nullptr);
deadbeefab9b2d12015-10-14 18:33:114806 return;
4807 }
4808 }
4809}
4810
deadbeefab9b2d12015-10-14 18:33:114811void 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 10:09:254833 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 18:33:114834 return;
4835 }
4836
deadbeefa601f5c2016-06-06 21:27:394837 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4838 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 08:50:164839 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 10:04:414840 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 18:33:114841}
4842
Bjorn Mellem175aa2e2018-11-08 19:23:224843bool 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 18:20:224864rtc::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 19:43:084870 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 18:20:224871 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 19:43:084884 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 18:20:224885 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 21:10:504894bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 18:20:224895 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 21:10:504905}
4906
Steve Anton4171afb2017-11-20 18:20:224907rtc::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 19:26:014917}
4918
Steve Anton4171afb2017-11-20 18:20:224919rtc::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 23:53:554929}
4930
Steve Anton4171afb2017-11-20 18:20:224931rtc::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 23:53:554941}
4942
Steve Anton4171afb2017-11-20 18:20:224943std::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 18:33:114953 cricket::MediaType media_type) {
4954 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4955 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 18:20:224956 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4957 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 18:33:114958}
4959
Steve Anton4171afb2017-11-20 18:20:224960const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4961 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609eaa2018-03-27 21:57:184962 const std::string& stream_id,
Steve Anton4171afb2017-11-20 18:20:224963 const std::string sender_id) const {
4964 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609eaa2018-03-27 21:57:184965 if (sender_info.stream_id == stream_id &&
4966 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 18:20:224967 return &sender_info;
deadbeefab9b2d12015-10-14 18:33:114968 }
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 23:55:304982bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 11:54:074983 const cricket::ServerAddresses& stun_servers,
4984 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 15:15:114985 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-28 00:20:154986 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 15:15:114987 // To handle both internal and externally created port allocator, we will
4988 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 23:57:454989 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 15:15:114993 // If the disable-IPv6 flag was specified, we'll not override it
4994 // by experiment.
4995 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 23:57:454996 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 16:50:474997 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4998 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 23:57:454999 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 15:15:115000 }
5001
zhihuangb09b3f92017-03-07 22:40:515002 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 23:57:455003 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 10:09:255004 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 22:40:515005 }
5006
Taylor Brandstettera1c30352016-05-13 15:15:115007 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 23:57:455008 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 10:09:255009 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 15:15:115010 }
5011
honghaiz60347052016-06-01 01:29:125012 if (configuration.candidate_network_policy ==
5013 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 23:57:455014 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 10:09:255015 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-06-01 01:29:125016 }
5017
Daniel Lazarenko2870b0a2018-01-25 09:30:225018 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 23:57:455019 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 09:30:225020 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
5021 }
5022
Qingsi Wanga2d60672018-04-11 23:57:455023 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 15:15:115024 // 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));
deadbeefd21eab3e2017-07-26 23:50:115028 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 15:15:115029
Harald Alvestrandb2a74782018-06-28 11:54:075030 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-14 00:06:265031 for (auto& turn_server : turn_servers_copy) {
5032 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 20:12:255033 }
Taylor Brandstettera1c30352016-05-13 15:15:115034 // Call this last since it may create pooled allocator sessions using the
5035 // properties set above.
Qingsi Wangdb53f8e2018-02-20 22:45:495036 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:265037 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 22:45:495040 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:115041 return true;
5042}
5043
deadbeef91dd5672016-05-18 23:55:305044bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 20:28:305045 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 12:01:405049 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 22:45:495050 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 14:47:435051 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 15:15:115052 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 20:28:305053 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 23:57:455054 // 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-14 00:06:265060 // 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 15:15:115065 // Call this last since it may create pooled allocator sessions using the
5066 // candidate filter set above.
deadbeef6de92f92016-12-13 02:49:325067 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-14 00:06:265068 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
5069 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 15:15:115070}
5071
Steve Antonba818672017-11-06 18:21:575072cricket::ChannelManager* PeerConnection::channel_manager() const {
5073 return factory_->channel_manager();
5074}
5075
Elad Alon99c3fe52017-10-13 14:29:405076bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 16:38:145077 std::unique_ptr<RtcEventLogOutput> output,
5078 int64_t output_period_ms) {
zhihuang77985012017-02-07 23:45:165079 if (!event_log_) {
5080 return false;
5081 }
Bjorn Tereliusde939432017-11-20 16:38:145082 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 14:06:555083}
5084
5085void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 23:45:165086 if (event_log_) {
5087 event_log_->StopLogging();
5088 }
ivoc14d5dbe2016-07-04 14:06:555089}
nisseeaabdf62017-05-05 09:23:025090
Amit Hilbuchdd9390c2018-11-14 00:26:055091cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 18:37:175092 const std::string& content_name) {
Steve Antondcc3c022017-12-23 00:02:545093 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055094 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-23 00:02:545095 if (channel && channel->content_name() == content_name) {
5096 return channel;
5097 }
Steve Anton75737c02017-11-06 18:37:175098 }
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 19:23:225107 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175108 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:255109 RTC_LOG(LS_INFO)
5110 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:075111 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175112 return false;
5113 }
Bjorn Mellem175aa2e2018-11-08 19:23:225114 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255115 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 09:37:075116 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 18:37:175117 return false;
5118 }
5119
Bjorn Mellem175aa2e2018-11-08 19:23:225120 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 17:48:355126 if (dtls_role) {
5127 *role = *dtls_role;
5128 return true;
5129 }
5130 return false;
Steve Anton75737c02017-11-06 18:37:175131}
5132
5133bool PeerConnection::GetSslRole(const std::string& content_name,
5134 rtc::SSLRole* role) {
5135 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 10:09:255136 RTC_LOG(LS_INFO)
5137 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 09:37:075138 "SSL Role of the session.";
Steve Anton75737c02017-11-06 18:37:175139 return false;
5140 }
5141
Zhi Huange830e682018-03-30 17:48:355142 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 18:37:175148}
5149
Steve Antonf8470812017-12-04 18:46:215150void 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 18:37:175156 }
5157}
5158
Zhi Huange830e682018-03-30 17:48:355159RTCError PeerConnection::UpdateSessionState(
5160 SdpType type,
5161 cricket::ContentSource source,
5162 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 23:25:565163 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175164
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 18:46:215167 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-05 01:19:475168
Steve Anton6d6a2ae2017-12-05 01:19:475169 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 18:34:515170 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 18:52:595171 EnableSending();
Steve Anton6d6a2ae2017-12-05 01:19:475172 }
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 18:34:515176 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-05 01:19:475177 ChangeSignalingState(source == cricket::CS_LOCAL
5178 ? PeerConnectionInterface::kHaveLocalOffer
5179 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 18:34:515180 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-05 01:19:475181 ChangeSignalingState(source == cricket::CS_LOCAL
5182 ? PeerConnectionInterface::kHaveLocalPrAnswer
5183 : PeerConnectionInterface::kHaveRemotePrAnswer);
5184 } else {
Steve Anton3828c062017-12-06 18:34:515185 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-05 01:19:475186 ChangeSignalingState(PeerConnectionInterface::kStable);
5187 }
5188
5189 // Update internal objects according to the session description's media
5190 // descriptions.
Zhi Huange830e682018-03-30 17:48:355191 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-05 01:19:475192 if (!error.ok()) {
Steve Anton80dd7b52018-02-17 01:08:425193 return error;
Steve Anton6d6a2ae2017-12-05 01:19:475194 }
5195
Steve Anton8a006912017-12-04 23:25:565196 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175197}
5198
Steve Anton8a006912017-12-04 23:25:565199RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 18:34:515200 SdpType type,
Steve Anton8a006912017-12-04 23:25:565201 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 18:52:595202 const SessionDescriptionInterface* sdesc =
5203 (source == cricket::CS_LOCAL ? local_description()
5204 : remote_description());
Steve Anton75737c02017-11-06 18:37:175205 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 18:52:595206
5207 // Push down the new SDP media section for each audio/video transceiver.
5208 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 18:37:175209 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 18:52:595210 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-14 00:26:055211 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:595212 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 18:37:175213 continue;
5214 }
5215 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 23:14:305216 content_info->media_description();
Steve Antoned10bd92017-12-05 18:52:595217 if (!content_desc) {
5218 continue;
5219 }
5220 std::string error;
Yves Gerey665174f2018-06-19 13:03:055221 bool success = (source == cricket::CS_LOCAL)
5222 ? channel->SetLocalContent(content_desc, type, &error)
5223 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595224 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 23:14:305235 data_content->media_description();
Steve Antoned10bd92017-12-05 18:52:595236 if (data_desc) {
5237 std::string error;
5238 bool success =
5239 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 18:34:515240 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 13:03:055241 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 18:52:595242 if (!success) {
5243 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5244 std::move(error));
5245 }
Steve Anton75737c02017-11-06 18:37:175246 }
5247 }
5248 }
Steve Antoned10bd92017-12-05 18:52:595249
Steve Anton75737c02017-11-06 18:37:175250 // 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 23:25:565255 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 18:37:175256 RTC_FROM_HERE,
5257 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 23:25:565258 if (!success) {
5259 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5260 "Failed to push down SCTP parameters.");
5261 }
Steve Anton75737c02017-11-06 18:37:175262 }
Steve Antoned10bd92017-12-05 18:52:595263
Steve Anton8a006912017-12-04 23:25:565264 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175265}
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 23:25:565278RTCError PeerConnection::PushdownTransportDescription(
5279 cricket::ContentSource source,
Steve Anton3828c062017-12-06 18:34:515280 SdpType type) {
Steve Anton8a006912017-12-04 23:25:565281 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175282
Zhi Huange830e682018-03-30 17:48:355283 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 18:37:175293 }
Steve Anton75737c02017-11-06 18:37:175294}
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 18:37:175312cricket::IceConfig PeerConnection::ParseIceConfig(
5313 const PeerConnectionInterface::RTCConfiguration& config) const {
5314 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 18:37:175315 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 18:38:405326
Steve Anton75737c02017-11-06 18:37:175327 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-23 00:54:235328 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5329 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 18:37:175330 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-23 00:54:235333 RTCConfigurationToIceConfigOptionalInt(
5334 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 18:37:175335 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 22:55:145338 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 18:37:175342 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Jiawei Oucc887372018-11-30 07:08:515343 ice_config.ice_unwritable_timeout = config.ice_unwritable_timeout;
5344 ice_config.ice_unwritable_min_checks = config.ice_unwritable_min_checks;
Jiawei Ou9d4fd5552018-12-07 07:30:175345 ice_config.ice_inactive_timeout = config.ice_inactive_timeout;
Qingsi Wangdb53f8e2018-02-20 22:45:495346 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 18:37:175347 ice_config.regather_all_networks_interval_range =
5348 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 18:38:405349 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 18:37:175350 return ice_config;
5351}
5352
Steve Antona41959e2018-11-28 19:15:335353static absl::string_view GetTrackIdBySsrc(
5354 const SessionDescriptionInterface* session_description,
5355 uint32_t ssrc) {
5356 if (!session_description) {
5357 return {};
Steve Anton75737c02017-11-06 18:37:175358 }
Steve Antona41959e2018-11-28 19:15:335359 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 18:37:175373}
5374
Steve Antona41959e2018-11-28 19:15:335375absl::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 18:37:175381}
5382
5383bool PeerConnection::SendData(const cricket::SendDataParams& params,
5384 const rtc::CopyOnWriteBuffer& payload,
5385 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 19:23:225386 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 18:37:175389 return false;
5390 }
Bjorn Mellem175aa2e2018-11-08 19:23:225391 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 18:37:175402 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 19:23:225411 RTC_DCHECK_RUN_ON(signaling_thread());
5412 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 18:37:175413 // 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 19:23:225418 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 18:37:175428 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 20:23:325437 SignalSctpClosingProcedureStartedRemotely.connect(
5438 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5439 SignalSctpClosingProcedureComplete.connect(
5440 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 18:37:175441 }
5442 return true;
5443}
5444
5445void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 19:23:225446 RTC_DCHECK_RUN_ON(signaling_thread());
5447 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255448 RTC_LOG(LS_ERROR)
5449 << "DisconnectDataChannel called when rtp_data_channel_ and "
5450 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 18:37:175451 return;
5452 }
Bjorn Mellem175aa2e2018-11-08 19:23:225453 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 18:37:175459 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 20:23:325464 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5465 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 18:37:175466 }
5467}
5468
5469void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225470 if (media_transport_) {
5471 // No-op. Media transport does not need to add streams.
5472 return;
5473 }
Steve Anton75737c02017-11-06 18:37:175474 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255475 RTC_LOG(LS_ERROR)
5476 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 18:37:175477 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 19:23:225485 if (media_transport_) {
5486 media_transport_->CloseChannel(sid);
5487 return;
5488 }
Steve Anton75737c02017-11-06 18:37:175489 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 10:09:255490 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 09:37:075491 "NULL.";
Steve Anton75737c02017-11-06 18:37:175492 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 19:23:225500 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 18:37:175501 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 19:23:225502 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 18:37:175503 sctp_ready_to_send_data_;
5504}
5505
Bjorn Mellem175aa2e2018-11-08 19:23:225506void 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 14:47:435537absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 17:48:355538 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 14:47:435543 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355544 }
Danil Chapovalov66cadcc2018-06-19 14:47:435545 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 17:48:355546}
5547
Qingsi Wang72a43a12018-02-21 00:03:185548cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5549 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 23:57:455550 network_thread()->Invoke<void>(
5551 RTC_FROM_HERE,
5552 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5553 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-21 00:03:185554 return candidate_states_list;
5555}
5556
Steve Anton5dfde182018-02-06 18:34:405557std::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-14 00:26:055561 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 18:34:405562 if (channel) {
5563 transport_names_by_mid[channel->content_name()] =
5564 channel->transport_name();
5565 }
Steve Anton75737c02017-11-06 18:37:175566 }
Steve Anton5dfde182018-02-06 18:34:405567 if (rtp_data_channel_) {
5568 transport_names_by_mid[rtp_data_channel_->content_name()] =
5569 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 18:37:175570 }
5571 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 14:47:435572 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:355573 RTC_DCHECK(transport_name);
5574 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 18:37:175575 }
Steve Anton5dfde182018-02-06 18:34:405576 return transport_names_by_mid;
Steve Anton75737c02017-11-06 18:37:175577}
5578
Steve Anton5dfde182018-02-06 18:34:405579std::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 18:37:175587 }
Steve Anton5dfde182018-02-06 18:34:405588 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 18:37:175601}
5602
5603bool PeerConnection::GetLocalCertificate(
5604 const std::string& transport_name,
5605 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 17:48:355606 if (!certificate) {
5607 return false;
5608 }
5609 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5610 return *certificate != nullptr;
Steve Anton75737c02017-11-06 18:37:175611}
5612
Taylor Brandstetterc3928662018-02-23 21:04:515613std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 18:37:175614 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 21:04:515615 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 18:37:175616}
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 18:37:175627bool 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 18:46:215637 SetSessionError(SessionError::kTransport,
5638 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 18:37:175639}
5640
Alex Loiko9289eda2018-11-23 16:18:595641void 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 18:37:175686void 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 10:09:255692 RTC_LOG(LS_ERROR)
5693 << "OnTransportControllerCandidatesGathered: content name "
5694 << transport_name << " not found";
Steve Anton75737c02017-11-06 18:37:175695 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 10:09:255716 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 09:37:075717 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 10:09:255718 << candidate.ToString();
Steve Anton75737c02017-11-06 18:37:175719 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 19:54:535731 RTC_HISTOGRAM_ENUMERATION(
5732 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5733 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 18:37:175734}
5735
Steve Antoned10bd92017-12-05 18:52:595736void PeerConnection::EnableSending() {
5737 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-14 00:26:055738 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 18:52:595739 if (channel && !channel->enabled()) {
5740 channel->Enable(true);
5741 }
Steve Anton75737c02017-11-06 18:37:175742 }
5743
Steve Anton4171afb2017-11-20 18:20:225744 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 18:37:175745 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 18:20:225746 }
Steve Anton75737c02017-11-06 18:37:175747}
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 10:09:255783 RTC_LOG(LS_INFO)
5784 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 09:37:075785 "candidate.";
Steve Anton75737c02017-11-06 18:37:175786 }
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 10:09:255803 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 18:37:175804 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 17:48:355812 RTCError error =
5813 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:505814 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 08:07:075830 } else {
Zhi Huange830e682018-03-30 17:48:355831 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 18:37:175832 }
5833 return true;
5834}
5835
5836void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 18:37:175837 // 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 18:37:295840 if (!video_info || video_info->rejected) {
5841 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 18:37:175842 }
5843
Steve Anton6fec8802017-12-04 18:37:295844 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5845 if (!audio_info || audio_info->rejected) {
5846 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 18:37:175847 }
5848
5849 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5850 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 18:37:295851 DestroyDataChannel();
Steve Anton75737c02017-11-06 18:37:175852 }
5853}
5854
Steve Antondcc3c022017-12-23 00:02:545855RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5856 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 18:37:175857 const cricket::ContentGroup* bundle_group = nullptr;
5858 if (configuration_.bundle_policy ==
5859 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-23 00:02:545860 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 18:37:175861 if (!bundle_group) {
Steve Anton8a006912017-12-04 23:25:565862 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5863 "max-bundle configured but session description "
5864 "has no BUNDLE group");
Steve Anton75737c02017-11-06 18:37:175865 }
5866 }
Steve Antondcc3c022017-12-23 00:02:545867 return std::move(bundle_group);
5868}
5869
5870RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 17:48:355871 // Creating the media channels. Transports should already have been created
5872 // at this point.
Steve Antondcc3c022017-12-23 00:02:545873 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555874 if (voice && !voice->rejected &&
5875 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355876 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 18:21:555877 if (!voice_channel) {
Steve Anton8a006912017-12-04 23:25:565878 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5879 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 18:21:555880 }
5881 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5882 }
5883
Steve Antondcc3c022017-12-23 00:02:545884 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 18:21:555885 if (video && !video->rejected &&
5886 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 17:48:355887 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 18:21:555888 if (!video_channel) {
Steve Anton8a006912017-12-04 23:25:565889 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5890 "Failed to create video channel.");
Steve Anton75737c02017-11-06 18:37:175891 }
Steve Antoneda6ccd2017-12-04 18:21:555892 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 18:37:175893 }
5894
Steve Antondcc3c022017-12-23 00:02:545895 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 18:37:175896 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 19:23:225897 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 17:48:355898 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 23:25:565899 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5900 "Failed to create data channel.");
Steve Anton75737c02017-11-06 18:37:175901 }
5902 }
5903
Steve Anton8a006912017-12-04 23:25:565904 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:175905}
5906
Steve Anton4171afb2017-11-20 18:20:225907// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555908cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 17:48:355909 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:425910 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 16:07:485911 MediaTransportInterface* media_transport = nullptr;
5912 if (configuration_.use_media_transport) {
5913 media_transport = GetMediaTransport(mid);
5914 }
Anton Sukhanov98a462c2018-10-17 20:15:425915
Steve Anton75737c02017-11-06 18:37:175916 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 20:15:425917 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 17:16:445918 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5919 audio_options_);
Steve Anton75737c02017-11-06 18:37:175920 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555921 return nullptr;
Steve Anton75737c02017-11-06 18:37:175922 }
Steve Anton75737c02017-11-06 18:37:175923 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5924 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175925 voice_channel->SignalSentPacket.connect(this,
5926 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355927 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225928
Steve Antoneda6ccd2017-12-04 18:21:555929 return voice_channel;
Steve Anton75737c02017-11-06 18:37:175930}
5931
Steve Anton4171afb2017-11-20 18:20:225932// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 18:21:555933cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355934 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 20:15:425935 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5936
5937 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 18:37:175938 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 17:48:355939 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 17:16:445940 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5941 video_options_);
Steve Anton75737c02017-11-06 18:37:175942 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 18:21:555943 return nullptr;
Steve Anton75737c02017-11-06 18:37:175944 }
Steve Anton75737c02017-11-06 18:37:175945 video_channel->SignalDtlsSrtpSetupFailure.connect(
5946 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 18:37:175947 video_channel->SignalSentPacket.connect(this,
5948 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 17:48:355949 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 18:20:225950
Steve Antoneda6ccd2017-12-04 18:21:555951 return video_channel;
Steve Anton75737c02017-11-06 18:37:175952}
5953
Zhi Huange830e682018-03-30 17:48:355954bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 19:23:225955 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 18:37:175966 return false;
Bjorn Mellem175aa2e2018-11-08 19:23:225967 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 18:37:175998 }
5999
Steve Anton75737c02017-11-06 18:37:176000 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 17:48:356015bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 18:37:176016 RTC_DCHECK(network_thread()->IsCurrent());
6017 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-03 02:16:266018 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 17:48:356019 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-03 02:16:266020 RTC_DCHECK(dtls_transport);
6021 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176022 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 20:23:326028 // 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 17:48:356036 sctp_mid_ = mid;
Zhi Huang644fde42018-04-03 02:16:266037 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 17:48:356038 return true;
Steve Anton75737c02017-11-06 18:37:176039}
6040
6041void PeerConnection::DestroySctpTransport_n() {
6042 RTC_DCHECK(network_thread()->IsCurrent());
6043 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 17:48:356044 sctp_mid_.reset();
Steve Anton75737c02017-11-06 18:37:176045 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 19:23:226087 RTC_DCHECK_RUN_ON(signaling_thread());
6088 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 18:37:176089 SignalSctpDataReceived(params, payload);
6090 }
6091}
6092
Taylor Brandstettercdd05f02018-05-31 20:23:326093void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 18:37:176094 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 20:23:326099 &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 18:37:176109}
6110
Bjorn Mellem175aa2e2018-11-08 19:23:226111bool 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 18:37:176154// 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-21 00:34:006170 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 18:37:176171 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 23:14:306180 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 18:37:176181}
6182
Steve Anton06817cd2018-12-18 23:55:306183static RTCError ValidateMids(const cricket::SessionDescription& description) {
6184 std::set<std::string> mids;
6185 for (const cricket::ContentInfo& content : description.contents()) {
Steve Antonceac0152018-12-19 19:32:206186 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 23:55:306190 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 23:25:566198RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 18:37:176199 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 23:25:566200 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 18:46:216201 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 23:25:566202 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 18:37:176203 }
6204
6205 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 23:25:566206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 18:37:176207 }
6208
Steve Anton3828c062017-12-06 18:34:516209 SdpType type = sdesc->GetType();
6210 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6211 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 23:25:566212 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 14:18:036213 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 23:25:566214 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 18:37:176215 }
6216
Steve Anton06817cd2018-12-18 23:55:306217 RTCError error = ValidateMids(*sdesc->description());
6218 if (!error.ok()) {
6219 return error;
6220 }
6221
Steve Anton75737c02017-11-06 18:37:176222 // Verify crypto settings.
6223 std::string crypto_error;
Steve Anton8a006912017-12-04 23:25:566224 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6225 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 19:54:536226 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 23:25:566227 if (!crypto_error.ok()) {
6228 return crypto_error;
6229 }
Steve Anton75737c02017-11-06 18:37:176230 }
6231
6232 // Verify ice-ufrag and ice-pwd.
6233 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566234 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6235 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 18:37:176236 }
6237
6238 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 23:25:566239 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6240 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 18:37:176241 }
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 18:34:516247 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 23:33:486248 // 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 18:37:176250 const cricket::SessionDescription* offer_desc =
6251 (source == cricket::CS_LOCAL) ? remote_description()->description()
6252 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 23:33:486253 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6254 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6255 type)) {
Steve Anton8a006912017-12-04 23:25:566256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6257 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 18:37:176258 }
6259 } else {
Steve Anton75737c02017-11-06 18:37:176260 // 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 23:33:486262 // 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 18:37:176277 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 23:33:486278 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6279 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 23:25:566280 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6281 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 18:37:176282 }
6283 }
6284
Steve Antonba42e992018-04-09 21:10:016285 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 23:25:566304 return RTCError::OK();
Steve Anton75737c02017-11-06 18:37:176305}
6306
Steve Anton3828c062017-12-06 18:34:516307bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176308 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516309 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176310 return (state == PeerConnectionInterface::kStable) ||
6311 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-05 00:24:526312 } else {
Steve Anton3828c062017-12-06 18:34:516313 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176314 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6315 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6316 }
6317}
6318
Steve Anton3828c062017-12-06 18:34:516319bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 18:37:176320 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 18:34:516321 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 18:37:176322 return (state == PeerConnectionInterface::kStable) ||
6323 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-05 00:24:526324 } else {
Steve Anton3828c062017-12-06 18:34:516325 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 18:37:176326 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6327 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6328 }
6329}
6330
Steve Antonf8470812017-12-04 18:46:216331const 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 18:37:176344std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 11:41:306345 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 18:46:216346 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6347 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 14:59:326348 return desc.Release();
Steve Anton75737c02017-11-06 18:37:176349}
6350
Steve Anton8e20f172018-03-06 18:55:046351void PeerConnection::ReportSdpFormatReceived(
6352 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 18:55:046353 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 19:54:536377 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6378 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 18:55:046379}
6380
Harald Alvestrand8ebba742018-05-31 12:00:346381void 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 19:54:536388 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6389 usage_event_accumulator_,
6390 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 08:39:556391 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 08:50:166400 // 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 08:39:556409 }
Harald Alvestrand8ebba742018-05-31 12:00:346410}
6411
Steve Anton0ffaaa22018-02-23 18:31:306412void PeerConnection::ReportNegotiatedSdpSemantics(
6413 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 19:54:536414 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 18:31:306415 switch (answer.description()->msid_signaling()) {
6416 case 0:
Qingsi Wang7fc821d2018-07-12 19:54:536417 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 18:31:306418 break;
6419 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 19:54:536420 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 18:31:306421 break;
6422 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536423 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 18:31:306424 break;
6425 case cricket::kMsidSignalingMediaSection |
6426 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 19:54:536427 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 18:31:306428 break;
6429 default:
6430 RTC_NOTREACHED();
6431 }
Qingsi Wang7fc821d2018-07-12 19:54:536432 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6433 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 18:31:306434}
6435
Steve Anton75737c02017-11-06 18:37:176436// 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 10:09:256458 RTC_LOG(LS_ERROR)
6459 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6460 << mediacontent_index;
Steve Anton75737c02017-11-06 18:37:176461
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 17:48:356473 return true;
Steve Anton75737c02017-11-06 18:37:176474}
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 22:39:456492 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 19:43:086499 transceiver->media_type());
Steve Antonc7b964c2018-02-01 22:39:456500 }
Steve Anton75737c02017-11-06 18:37:176501 }
6502 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 22:39:456503 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6504 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176505 }
Zhi Huange830e682018-03-30 17:48:356506
Danil Chapovalov66cadcc2018-06-19 14:47:436507 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 17:48:356508 if (transport_name) {
6509 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 22:39:456510 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 18:37:176511 }
Zhi Huange830e682018-03-30 17:48:356512
Steve Antonc7b964c2018-02-01 22:39:456513 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 18:37:176516 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 22:39:456517 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 18:37:176518 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 22:39:456519 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 18:37:176520 }
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 22:39:456527 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 18:37:176532 continue;
6533 }
6534
Steve Antonc7b964c2018-02-01 22:39:456535 const cricket::Candidate& local = connection_info.local_candidate;
6536 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 18:37:176537
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 19:54:536542 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6543 GetIceCandidatePairCounter(local, remote),
6544 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176545 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 19:54:536546 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6547 GetIceCandidatePairCounter(local, remote),
6548 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 18:37:176549 } else {
6550 RTC_CHECK(0);
6551 }
Steve Anton75737c02017-11-06 18:37:176552
6553 // Increment the counter for IP type.
6554 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 19:54:536555 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6556 kBestConnections_IPv4,
6557 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176558 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 19:54:536559 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6560 kBestConnections_IPv6,
6561 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 18:37:176562 } else {
Qingsi Wang1dac6d82018-12-12 23:28:476563 RTC_CHECK(!local.address().hostname().empty() &&
6564 local.address().IsUnresolvedIP());
Steve Anton75737c02017-11-06 18:37:176565 }
6566
6567 return;
6568 }
6569 }
6570}
6571
6572void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 22:39:456573 const cricket::TransportStats& stats,
6574 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 18:37:176575 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 19:54:536586 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 22:39:456608 }
Qingsi Wang7fc821d2018-07-12 19:54:536609 }
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 22:39:456633 }
Steve Anton75737c02017-11-06 18:37:176634 }
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-14 00:26:056645 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 18:37:296646 if (channel) {
6647 return channel->transport_name();
Steve Anton75737c02017-11-06 18:37:176648 }
Steve Anton6fec8802017-12-04 18:37:296649 if (sctp_transport_) {
Zhi Huange830e682018-03-30 17:48:356650 RTC_DCHECK(sctp_mid_);
6651 if (content_name == *sctp_mid_) {
6652 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 18:37:296653 }
6654 }
6655 // Return an empty string if failed to retrieve the transport name.
6656 return "";
Steve Anton75737c02017-11-06 18:37:176657}
6658
Steve Anton6fec8802017-12-04 18:37:296659void PeerConnection::DestroyTransceiverChannel(
6660 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6661 transceiver) {
6662 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 18:37:176663
Amit Hilbuchdd9390c2018-11-14 00:26:056664 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 18:37:296665 if (channel) {
6666 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-14 00:26:056667 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 18:37:176668 }
6669}
6670
6671void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 18:37:296672 if (rtp_data_channel_) {
6673 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-14 00:26:056674 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 18:37:296675 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 19:23:226689
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 18:37:296697}
6698
Amit Hilbuchdd9390c2018-11-14 00:26:056699void PeerConnection::DestroyChannelInterface(
6700 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 18:37:296701 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 18:37:296702 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 17:48:356719}
Steve Anton6fec8802017-12-04 18:37:296720
Taylor Brandstettercbaa2542018-04-16 23:42:146721bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 17:48:356722 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 23:42:146723 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:196724 cricket::DtlsTransportInternal* dtls_transport,
6725 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 23:42:146726 bool ret = true;
Zhi Huange830e682018-03-30 17:48:356727 auto base_channel = GetChannel(mid);
6728 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 23:42:146729 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 17:48:356730 }
Taylor Brandstettercbaa2542018-04-16 23:42:146731 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-03 02:16:266732 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 18:37:176733 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 16:26:196734
6735 call_->MediaTransportChange(media_transport);
6736
Taylor Brandstettercbaa2542018-04-16 23:42:146737 return ret;
Steve Anton75737c02017-11-06 18:37:176738}
6739
Harald Alvestrand7a1c7f72018-08-01 08:50:166740PeerConnectionObserver* 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 17:16:446750CryptoOptions 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 13:08:346758void PeerConnection::ClearStatsCache() {
6759 if (stats_collector_) {
6760 stats_collector_->ClearCachedStatsReport();
6761 }
6762}
6763
Harald Alvestrand7a1c7f72018-08-01 08:50:166764void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:406765 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6766 nullptr);
Harald Alvestrand7a1c7f72018-08-01 08:50:166767}
6768
henrike@webrtc.org28e20752013-07-10 00:45:366769} // namespace webrtc