blob: 6a2e3703814cdd635e2370126da5c56a9cc278a9 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 10:37:17 -0800342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800389}
390
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100417
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100424 }
425}
426
Harald Alvestrand76829d72018-07-18 23:24:36 +0200427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 10:37:17 -0800432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800443 continue;
444 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800479 }
480 }
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 continue;
494 }
Steve Anton8a006912017-12-04 15:25:56 -0800495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800515 return false;
516 }
517 }
518 return true;
519}
520
521bool GetTrackIdBySsrc(const SessionDescription* session_description,
522 uint32_t ssrc,
523 std::string* track_id) {
524 RTC_DCHECK(track_id != NULL);
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::AudioContentDescription* audio_desc =
527 cricket::GetFirstAudioContentDescription(session_description);
528 if (audio_desc) {
529 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535
Steve Antonb1c1de12017-12-21 15:14:30 -0800536 const cricket::VideoContentDescription* video_desc =
537 cricket::GetFirstVideoContentDescription(session_description);
538 if (video_desc) {
539 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800540 if (found) {
541 *track_id = found->id;
542 return true;
543 }
544 }
545 return false;
546}
547
548// Get the SCTP port out of a SessionDescription.
549// Return -1 if not found.
550int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800551 const cricket::DataContentDescription* data_desc =
552 GetFirstDataContentDescription(session_description);
553 RTC_DCHECK(data_desc);
554 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800555 return -1;
556 }
Steve Anton75737c02017-11-06 10:37:17 -0800557 std::string value;
558 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
559 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800560 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800561 if (!codec.Matches(match_pattern)) {
562 continue;
563 }
564 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
565 return rtc::FromString<int>(value);
566 }
567 }
568 return -1;
569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800634cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
635 switch (type) {
636 case DataMessageType::kText:
637 return cricket::DMT_TEXT;
638 case DataMessageType::kBinary:
639 return cricket::DMT_BINARY;
640 case DataMessageType::kControl:
641 return cricket::DMT_CONTROL;
642 default:
643 return cricket::DMT_NONE;
644 }
645 return cricket::DMT_NONE;
646}
647
648DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
649 switch (type) {
650 case cricket::DMT_TEXT:
651 return DataMessageType::kText;
652 case cricket::DMT_BINARY:
653 return DataMessageType::kBinary;
654 case cricket::DMT_CONTROL:
655 return DataMessageType::kControl;
656 case cricket::DMT_NONE:
657 default:
658 RTC_NOTREACHED();
659 }
660 return DataMessageType::kControl;
661}
662
Steve Anton75737c02017-11-06 10:37:17 -0800663} // namespace
664
Henrik Boström31638672017-11-23 17:48:32 +0100665// Upon completion, posts a task to execute the callback of the
666// SetSessionDescriptionObserver asynchronously on the same thread. At this
667// point, the state of the peer connection might no longer reflect the effects
668// of the SetRemoteDescription operation, as the peer connection could have been
669// modified during the post.
670// TODO(hbos): Remove this class once we remove the version of
671// PeerConnectionInterface::SetRemoteDescription() that takes a
672// SetSessionDescriptionObserver as an argument.
673class PeerConnection::SetRemoteDescriptionObserverAdapter
674 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
675 public:
676 SetRemoteDescriptionObserverAdapter(
677 rtc::scoped_refptr<PeerConnection> pc,
678 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
679 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
680
681 // SetRemoteDescriptionObserverInterface implementation.
682 void OnSetRemoteDescriptionComplete(RTCError error) override {
683 if (error.ok())
684 pc_->PostSetSessionDescriptionSuccess(wrapper_);
685 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100686 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100687 }
688
689 private:
690 rtc::scoped_refptr<PeerConnection> pc_;
691 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
692};
693
deadbeef293e9262017-01-11 12:28:30 -0800694bool PeerConnectionInterface::RTCConfiguration::operator==(
695 const PeerConnectionInterface::RTCConfiguration& o) const {
696 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800698 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000699 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800701 BundlePolicy bundle_policy;
702 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700703 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
704 int ice_candidate_pool_size;
705 bool disable_ipv6;
706 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700707 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100708 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700709 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200710 absl::optional<int> screencast_min_bitrate;
711 absl::optional<bool> combined_audio_video_bwe;
712 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800713 TcpCandidatePolicy tcp_candidate_policy;
714 CandidateNetworkPolicy candidate_network_policy;
715 int audio_jitter_buffer_max_packets;
716 bool audio_jitter_buffer_fast_accelerate;
717 int ice_connection_receiving_timeout;
718 int ice_backup_candidate_pair_ping_interval;
719 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800720 bool prioritize_most_likely_ice_candidate_pairs;
721 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800722 bool prune_turn_ports;
723 bool presume_writable_when_fully_relayed;
724 bool enable_ice_renomination;
725 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200726 absl::optional<int> ice_check_interval_strong_connectivity;
727 absl::optional<int> ice_check_interval_weak_connectivity;
728 absl::optional<int> ice_check_min_interval;
729 absl::optional<int> ice_unwritable_timeout;
730 absl::optional<int> ice_unwritable_min_checks;
731 absl::optional<int> stun_candidate_keepalive_interval;
732 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200733 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800734 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700736 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700737 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700738 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700739 absl::optional<CryptoOptions> crypto_options;
Johannes Kron89f874e2018-11-12 10:25:48 +0100740 bool offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800741 };
742 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
743 "Did you add something to RTCConfiguration and forget to "
744 "update operator==?");
745 return type == o.type && servers == o.servers &&
746 bundle_policy == o.bundle_policy &&
747 rtcp_mux_policy == o.rtcp_mux_policy &&
748 tcp_candidate_policy == o.tcp_candidate_policy &&
749 candidate_network_policy == o.candidate_network_policy &&
750 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
751 audio_jitter_buffer_fast_accelerate ==
752 o.audio_jitter_buffer_fast_accelerate &&
753 ice_connection_receiving_timeout ==
754 o.ice_connection_receiving_timeout &&
755 ice_backup_candidate_pair_ping_interval ==
756 o.ice_backup_candidate_pair_ping_interval &&
757 continual_gathering_policy == o.continual_gathering_policy &&
758 certificates == o.certificates &&
759 prioritize_most_likely_ice_candidate_pairs ==
760 o.prioritize_most_likely_ice_candidate_pairs &&
761 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800762 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700763 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100764 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800765 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800766 screencast_min_bitrate == o.screencast_min_bitrate &&
767 combined_audio_video_bwe == o.combined_audio_video_bwe &&
768 enable_dtls_srtp == o.enable_dtls_srtp &&
769 ice_candidate_pool_size == o.ice_candidate_pool_size &&
770 prune_turn_ports == o.prune_turn_ports &&
771 presume_writable_when_fully_relayed ==
772 o.presume_writable_when_fully_relayed &&
773 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800774 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800775 ice_check_interval_strong_connectivity ==
776 o.ice_check_interval_strong_connectivity &&
777 ice_check_interval_weak_connectivity ==
778 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700779 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700780 ice_unwritable_timeout == o.ice_unwritable_timeout &&
781 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800782 stun_candidate_keepalive_interval ==
783 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200784 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800785 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800786 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700787 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700788 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700789 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700790 use_media_transport_for_data_channels ==
791 o.use_media_transport_for_data_channels &&
Johannes Kron89f874e2018-11-12 10:25:48 +0100792 crypto_options == o.crypto_options &&
793 offer_extmap_allow_mixed == o.offer_extmap_allow_mixed;
deadbeef293e9262017-01-11 12:28:30 -0800794}
795
796bool PeerConnectionInterface::RTCConfiguration::operator!=(
797 const PeerConnectionInterface::RTCConfiguration& o) const {
798 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800799}
800
zhihuang8f65cdf2016-05-06 18:40:30 -0700801// Generate a RTCP CNAME when a PeerConnection is created.
802std::string GenerateRtcpCname() {
803 std::string cname;
804 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100805 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800806 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700807 }
808 return cname;
809}
810
zhihuang1c378ed2017-08-17 14:10:50 -0700811bool ValidateOfferAnswerOptions(
812 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
813 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
814 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700815}
816
zhihuang1c378ed2017-08-17 14:10:50 -0700817// From |rtc_options|, fill parts of |session_options| shared by all generated
818// m= sections (in other words, nothing that involves a map/array).
819void ExtractSharedMediaSessionOptions(
820 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
821 cricket::MediaSessionOptions* session_options) {
822 session_options->vad_enabled = rtc_options.voice_activity_detection;
823 session_options->bundle_enabled = rtc_options.use_rtp_mux;
824}
zhihuanga77e6bb2017-08-14 18:17:48 -0700825
zhihuang38ede132017-06-15 12:52:32 -0700826PeerConnection::PeerConnection(PeerConnectionFactory* factory,
827 std::unique_ptr<RtcEventLog> event_log,
828 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000829 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700830 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700831 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700832 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700833 remote_streams_(StreamCollection::Create()),
834 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835
836PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100837 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800838 RTC_DCHECK_RUN_ON(signaling_thread());
839
Steve Anton8af21862017-12-15 11:20:13 -0800840 // Need to stop transceivers before destroying the stats collector because
841 // AudioRtpSender has a reference to the StatsCollector it will update when
842 // stopping.
843 for (auto transceiver : transceivers_) {
844 transceiver->Stop();
845 }
Steve Anton4171afb2017-11-20 10:20:22 -0800846
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700847 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800848 if (stats_collector_) {
849 stats_collector_->WaitForPendingRequest();
850 stats_collector_ = nullptr;
851 }
Steve Anton75737c02017-11-06 10:37:17 -0800852
Steve Anton8af21862017-12-15 11:20:13 -0800853 // Don't destroy BaseChannels until after stats has been cleaned up so that
854 // the last stats request can still read from the channels.
855 DestroyAllChannels();
856
Mirko Bonadei675513b2017-11-09 11:09:25 +0100857 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800858
859 webrtc_session_desc_factory_.reset();
860 sctp_invoker_.reset();
861 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800862 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800863 transport_controller_.reset();
864
deadbeef91dd5672016-05-18 16:55:30 -0700865 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700866 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700867 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700868 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700869 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700870 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800871 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700872 event_log_.reset();
873 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000874}
875
Steve Anton8af21862017-12-15 11:20:13 -0800876void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800877 // Destroy video channels first since they may have a pointer to a voice
878 // channel.
879 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800880 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800881 DestroyTransceiverChannel(transceiver);
882 }
883 }
884 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800885 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800886 DestroyTransceiverChannel(transceiver);
887 }
888 }
889 DestroyDataChannel();
890}
891
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000892bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000893 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700894 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100895 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700896
897 RTCError config_error = ValidateConfiguration(configuration);
898 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100899 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700900 return false;
901 }
902
Benjamin Wrightcab58882018-05-02 15:12:47 -0700903 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100904 RTC_LOG(LS_ERROR)
905 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100906 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800907 return false;
908 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200909
Benjamin Wrightcab58882018-05-02 15:12:47 -0700910 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800911 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100912 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100913 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800914 return false;
915 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700916
Benjamin Wrightcab58882018-05-02 15:12:47 -0700917 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700918 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700919 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700920 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800921
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200922 cricket::ServerAddresses stun_servers;
923 std::vector<cricket::RelayServerConfig> turn_servers;
924
925 RTCErrorType parse_error =
926 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
927 if (parse_error != RTCErrorType::NONE) {
928 return false;
929 }
930
deadbeef91dd5672016-05-18 16:55:30 -0700931 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700932 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700933 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200934 RTC_FROM_HERE,
935 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
936 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000937 return false;
938 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200939 // If initialization was successful, note if STUN or TURN servers
940 // were supplied.
941 if (!stun_servers.empty()) {
942 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
943 }
944 if (!turn_servers.empty()) {
945 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
946 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700948 // Send information about IPv4/IPv6 status.
949 PeerConnectionAddressFamilyCounter address_family;
950 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
951 address_family = kPeerConnection_IPv6;
952 } else {
953 address_family = kPeerConnection_IPv4;
954 }
955 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
956 kPeerConnectionAddressFamilyCounter_Max);
957
Zhi Huange830e682018-03-30 10:48:35 -0700958 const PeerConnectionFactoryInterface::Options& options = factory_->options();
959
Steve Anton75737c02017-11-06 10:37:17 -0800960 // RFC 3264: The numeric value of the session id and version in the
961 // o line MUST be representable with a "64 bit signed integer".
962 // Due to this constraint session id |session_id_| is max limited to
963 // LLONG_MAX.
964 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700965 JsepTransportController::Config config;
966 config.redetermine_role_on_ice_restart =
967 configuration.redetermine_role_on_ice_restart;
968 config.ssl_max_version = factory_->options().ssl_max_version;
969 config.disable_encryption = options.disable_encryption;
970 config.bundle_policy = configuration.bundle_policy;
971 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700972 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
973 // stub.
974 config.crypto_options = configuration.crypto_options.has_value()
975 ? *configuration.crypto_options
976 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700977 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700978 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700979#if defined(ENABLE_EXTERNAL_AUTH)
980 config.enable_external_auth = true;
981#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700982 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700983
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700984 if (configuration.use_media_transport ||
985 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700986 if (!factory_->media_transport_factory()) {
987 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700988 << "PeerConnecton is initialized with use_media_transport = true or "
989 << "use_media_transport_for_data_channels = true "
990 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700991 return false;
992 }
993
994 config.media_transport_factory = factory_->media_transport_factory();
995 }
996
Zhi Huange830e682018-03-30 10:48:35 -0700997 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700998 signaling_thread(), network_thread(), port_allocator_.get(),
999 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -07001000 transport_controller_->SignalIceConnectionState.connect(
Jonas Olsson1e87b4f2018-11-22 16:50:37 +01001001 this, &PeerConnection::SetIceConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001002 transport_controller_->SignalConnectionState.connect(
1003 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001004 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001005 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001006 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001007 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001008 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001009 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1010 transport_controller_->SignalDtlsHandshakeError.connect(
1011 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1012
1013 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001014
deadbeefab9b2d12015-10-14 11:33:11 -07001015 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001016 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017
Steve Antonba818672017-11-06 10:21:57 -08001018 configuration_ = configuration;
1019
Steve Anton75737c02017-11-06 10:37:17 -08001020 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1021 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1022 if (!configuration.certificates.empty()) {
1023 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1024 // just picking the first one. The decision should be made based on the DTLS
1025 // handshake. The DTLS negotiations need to know about all certificates.
1026 certificate = configuration.certificates[0];
1027 }
1028
Steve Antond25da372017-11-06 14:50:29 -08001029 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001030
1031 if (options.disable_encryption) {
1032 dtls_enabled_ = false;
1033 } else {
1034 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001035 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001036 // |configuration| can override the default |dtls_enabled_| value.
1037 if (configuration.enable_dtls_srtp) {
1038 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1039 }
1040 }
1041
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001042 if (configuration.use_media_transport_for_data_channels) {
1043 if (configuration.enable_rtp_data_channel) {
1044 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1045 "use_media_transport_for_data_channels are "
1046 "incompatible and cannot both be set to true";
1047 return false;
1048 }
1049 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1050 } else if (configuration.enable_rtp_data_channel) {
1051 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1052 // set. It takes precendence over the disable_sctp_data_channels
1053 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001054 data_channel_type_ = cricket::DCT_RTP;
1055 } else {
1056 // DTLS has to be enabled to use SCTP.
1057 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1058 data_channel_type_ = cricket::DCT_SCTP;
1059 }
1060 }
1061
1062 video_options_.screencast_min_bitrate_kbps =
1063 configuration.screencast_min_bitrate;
1064 audio_options_.combined_audio_video_bwe =
1065 configuration.combined_audio_video_bwe;
1066
1067 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001068 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001069
1070 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001071 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001072
1073 // Whether the certificate generator/certificate is null or not determines
1074 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1075 // the right instructions by clearing the variables if needed.
1076 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001077 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001078 certificate = nullptr;
1079 } else if (certificate) {
1080 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001081 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001082 }
1083
1084 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1085 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001086 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001087 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1088 this, &PeerConnection::OnCertificateReady);
1089
1090 if (options.disable_encryption) {
1091 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1092 }
1093
1094 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001095 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096
Steve Anton4171afb2017-11-20 10:20:22 -08001097 // Add default audio/video transceivers for Plan B SDP.
1098 if (!IsUnifiedPlan()) {
1099 transceivers_.push_back(
1100 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1101 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1102 transceivers_.push_back(
1103 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1104 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1105 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001106 int delay_ms =
1107 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001108 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1109 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 return true;
1111}
1112
Steve Anton038834f2017-07-14 15:59:59 -07001113RTCError PeerConnection::ValidateConfiguration(
1114 const RTCConfiguration& config) const {
1115 if (config.ice_regather_interval_range &&
1116 config.continual_gathering_policy == GATHER_ONCE) {
1117 return RTCError(RTCErrorType::INVALID_PARAMETER,
1118 "ice_regather_interval_range specified but continual "
1119 "gathering policy is GATHER_ONCE");
1120 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001121 auto result =
1122 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1123 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001124}
1125
Yves Gerey665174f2018-06-19 15:03:05 +02001126rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001127 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1128 "Plan SdpSemantics. Please use GetSenders "
1129 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001130 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001131}
1132
Yves Gerey665174f2018-06-19 15:03:05 +02001133rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001134 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1135 "Plan SdpSemantics. Please use GetReceivers "
1136 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001137 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001138}
1139
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001140bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001141 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1142 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001143 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001144 if (IsClosed()) {
1145 return false;
1146 }
deadbeefab9b2d12015-10-14 11:33:11 -07001147 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148 return false;
1149 }
deadbeefab9b2d12015-10-14 11:33:11 -07001150
1151 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001152 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1153 observer->SignalAudioTrackAdded.connect(this,
1154 &PeerConnection::OnAudioTrackAdded);
1155 observer->SignalAudioTrackRemoved.connect(
1156 this, &PeerConnection::OnAudioTrackRemoved);
1157 observer->SignalVideoTrackAdded.connect(this,
1158 &PeerConnection::OnVideoTrackAdded);
1159 observer->SignalVideoTrackRemoved.connect(
1160 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001161 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001162
deadbeefab9b2d12015-10-14 11:33:11 -07001163 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001164 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001165 }
1166 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001167 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001168 }
1169
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001170 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001171 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172 return true;
1173}
1174
1175void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001176 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1177 "Plan SdpSemantics. Please use RemoveTrack "
1178 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001179 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001180 if (!IsClosed()) {
1181 for (const auto& track : local_stream->GetAudioTracks()) {
1182 RemoveAudioTrack(track.get(), local_stream);
1183 }
1184 for (const auto& track : local_stream->GetVideoTracks()) {
1185 RemoveVideoTrack(track.get(), local_stream);
1186 }
deadbeefab9b2d12015-10-14 11:33:11 -07001187 }
deadbeefab9b2d12015-10-14 11:33:11 -07001188 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001189 stream_observers_.erase(
1190 std::remove_if(
1191 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001192 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001193 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001194 }),
1195 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 if (IsClosed()) {
1198 return;
1199 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001200 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201}
1202
Steve Anton2d6c76a2018-01-05 17:10:52 -08001203RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001204 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001205 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001206 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001207 if (!track) {
1208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1209 }
1210 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1211 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1213 "Track has invalid kind: " + track->kind());
1214 }
Steve Antonf9381f02017-12-14 10:23:57 -08001215 if (IsClosed()) {
1216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1217 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001218 }
Steve Anton4171afb2017-11-20 10:20:22 -08001219 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001220 LOG_AND_RETURN_ERROR(
1221 RTCErrorType::INVALID_PARAMETER,
1222 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Antonf9381f02017-12-14 10:23:57 -08001224 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001225 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1226 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001227 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001228 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001229 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001230 }
1231 return sender_or_error;
1232}
deadbeefe1f9d832016-01-14 15:35:42 -08001233
Steve Antonf9381f02017-12-14 10:23:57 -08001234RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1235PeerConnection::AddTrackPlanB(
1236 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001237 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001238 if (stream_ids.size() > 1u) {
1239 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1240 "AddTrack with more than one stream is not "
1241 "supported with Plan B semantics.");
1242 }
1243 std::vector<std::string> adjusted_stream_ids = stream_ids;
1244 if (adjusted_stream_ids.empty()) {
1245 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1246 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001247 cricket::MediaType media_type =
1248 (track->kind() == MediaStreamTrackInterface::kAudioKind
1249 ? cricket::MEDIA_TYPE_AUDIO
1250 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001251 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001252 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001253 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001254 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001255 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001256 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001257 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001258 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001259 if (sender_info) {
1260 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001261 }
Steve Antonf9381f02017-12-14 10:23:57 -08001262 } else {
1263 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001264 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001265 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001266 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001267 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001268 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001269 if (sender_info) {
1270 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001271 }
deadbeefe1f9d832016-01-14 15:35:42 -08001272 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001273 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001274}
deadbeefe1f9d832016-01-14 15:35:42 -08001275
Steve Antonf9381f02017-12-14 10:23:57 -08001276RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1277PeerConnection::AddTrackUnifiedPlan(
1278 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001279 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001280 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1281 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001282 RTC_LOG(LS_INFO) << "Reusing an existing "
1283 << cricket::MediaTypeToString(transceiver->media_type())
1284 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001285 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001286 transceiver->internal()->set_direction(
1287 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001288 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001289 transceiver->internal()->set_direction(
1290 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001291 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001292 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001293 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001294 } else {
1295 cricket::MediaType media_type =
1296 (track->kind() == MediaStreamTrackInterface::kAudioKind
1297 ? cricket::MEDIA_TYPE_AUDIO
1298 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001299 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1300 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001301 std::string sender_id = track->id();
1302 // Avoid creating a sender with an existing ID by generating a random ID.
1303 // This can happen if this is the second time AddTrack has created a sender
1304 // for this track.
1305 if (FindSenderById(sender_id)) {
1306 sender_id = rtc::CreateRandomUuid();
1307 }
Florent Castelli892acf02018-10-01 22:47:20 +02001308 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001309 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1310 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001312 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 }
Steve Antonf9381f02017-12-14 10:23:57 -08001314 return transceiver->sender();
1315}
1316
1317rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1318PeerConnection::FindFirstTransceiverForAddedTrack(
1319 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1320 RTC_DCHECK(track);
1321 for (auto transceiver : transceivers_) {
1322 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001323 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001324 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001325 !transceiver->internal()->has_ever_been_used_to_send() &&
1326 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001327 return transceiver;
1328 }
1329 }
1330 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001331}
1332
1333bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1334 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001335 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001336}
1337
Steve Anton24db5732018-07-23 10:27:33 -07001338RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001339 rtc::scoped_refptr<RtpSenderInterface> sender) {
1340 if (!sender) {
1341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1342 }
deadbeefe1f9d832016-01-14 15:35:42 -08001343 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1345 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001346 }
Steve Antonf9381f02017-12-14 10:23:57 -08001347 if (IsUnifiedPlan()) {
1348 auto transceiver = FindTransceiverBySender(sender);
1349 if (!transceiver || !sender->track()) {
1350 return RTCError::OK();
1351 }
1352 sender->SetTrack(nullptr);
1353 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001354 transceiver->internal()->set_direction(
1355 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001356 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001357 transceiver->internal()->set_direction(
1358 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001359 }
Steve Anton4171afb2017-11-20 10:20:22 -08001360 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001361 bool removed;
1362 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1363 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1364 } else {
1365 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1366 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1367 }
1368 if (!removed) {
1369 LOG_AND_RETURN_ERROR(
1370 RTCErrorType::INVALID_PARAMETER,
1371 "Couldn't find sender " + sender->id() + " to remove.");
1372 }
Steve Anton4171afb2017-11-20 10:20:22 -08001373 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001374 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001375 return RTCError::OK();
1376}
1377
1378rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1379PeerConnection::FindTransceiverBySender(
1380 rtc::scoped_refptr<RtpSenderInterface> sender) {
1381 for (auto transceiver : transceivers_) {
1382 if (transceiver->sender() == sender) {
1383 return transceiver;
1384 }
1385 }
1386 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001387}
1388
Steve Anton9158ef62017-11-27 13:01:52 -08001389RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1390PeerConnection::AddTransceiver(
1391 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1392 return AddTransceiver(track, RtpTransceiverInit());
1393}
1394
1395RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1396PeerConnection::AddTransceiver(
1397 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1398 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001399 RTC_CHECK(IsUnifiedPlan())
1400 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001401 if (!track) {
1402 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1403 }
1404 cricket::MediaType media_type;
1405 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1406 media_type = cricket::MEDIA_TYPE_AUDIO;
1407 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1408 media_type = cricket::MEDIA_TYPE_VIDEO;
1409 } else {
1410 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1411 "Track kind is not audio or video");
1412 }
1413 return AddTransceiver(media_type, track, init);
1414}
1415
1416RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1417PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1418 return AddTransceiver(media_type, RtpTransceiverInit());
1419}
1420
1421RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1422PeerConnection::AddTransceiver(cricket::MediaType media_type,
1423 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001424 RTC_CHECK(IsUnifiedPlan())
1425 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001426 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1427 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1429 "media type is not audio or video");
1430 }
1431 return AddTransceiver(media_type, nullptr, init);
1432}
1433
1434RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1435PeerConnection::AddTransceiver(
1436 cricket::MediaType media_type,
1437 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001438 const RtpTransceiverInit& init,
1439 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001440 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1441 media_type == cricket::MEDIA_TYPE_VIDEO));
1442 if (track) {
1443 RTC_DCHECK_EQ(media_type,
1444 (track->kind() == MediaStreamTrackInterface::kAudioKind
1445 ? cricket::MEDIA_TYPE_AUDIO
1446 : cricket::MEDIA_TYPE_VIDEO));
1447 }
1448
1449 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001450 if (init.send_encodings.size() > 1) {
1451 LOG_AND_RETURN_ERROR(
1452 RTCErrorType::UNSUPPORTED_PARAMETER,
1453 "Attempted to create an encoder with more than 1 encoding parameter.");
1454 }
1455
1456 for (const auto& encoding : init.send_encodings) {
1457 if (encoding.ssrc.has_value()) {
1458 LOG_AND_RETURN_ERROR(
1459 RTCErrorType::UNSUPPORTED_PARAMETER,
1460 "Attempted to set an unimplemented parameter of RtpParameters.");
1461 }
1462 }
1463
1464 RtpParameters parameters;
1465 parameters.encodings = init.send_encodings;
1466 if (UnimplementedRtpParameterHasValue(parameters)) {
1467 LOG_AND_RETURN_ERROR(
1468 RTCErrorType::UNSUPPORTED_PARAMETER,
1469 "Attempted to set an unimplemented parameter of RtpParameters.");
1470 }
Steve Anton9158ef62017-11-27 13:01:52 -08001471
Steve Anton3d954a62018-04-02 11:27:23 -07001472 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1473 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001474 // Set the sender ID equal to the track ID if the track is specified unless
1475 // that sender ID is already in use.
1476 std::string sender_id =
1477 (track && !FindSenderById(track->id()) ? track->id()
1478 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001479 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1480 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001481 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1482 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1483 transceiver->internal()->set_direction(init.direction);
1484
Steve Anton22da89f2018-01-25 13:58:07 -08001485 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001486 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001487 }
Steve Antonf9381f02017-12-14 10:23:57 -08001488
1489 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1490}
1491
Steve Anton02ee47c2018-01-10 16:26:06 -08001492rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1493PeerConnection::CreateSender(
1494 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001495 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001496 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001497 const std::vector<std::string>& stream_ids,
1498 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001499 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001500 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1501 RTC_DCHECK(!track ||
1502 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1503 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1504 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001505 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001506 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001507 } else {
1508 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1509 RTC_DCHECK(!track ||
1510 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1511 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001512 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001513 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001514 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001515 bool set_track_succeeded = sender->SetTrack(track);
1516 RTC_DCHECK(set_track_succeeded);
1517 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001518 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 return sender;
1520}
1521
1522rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1523PeerConnection::CreateReceiver(cricket::MediaType media_type,
1524 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001525 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1526 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001527 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001528 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001529 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1530 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001531 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001532 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001533 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001534 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001535 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1536 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001537 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001538 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001539 return receiver;
1540}
1541
1542rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1543PeerConnection::CreateAndAddTransceiver(
1544 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1545 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1546 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001547 // Ensure that the new sender does not have an ID that is already in use by
1548 // another sender.
1549 // Allow receiver IDs to conflict since those come from remote SDP (which
1550 // could be invalid, but should not cause a crash).
1551 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001552 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1553 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001554 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001555 transceiver->internal()->SignalNegotiationNeeded.connect(
1556 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001557 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001558}
1559
Steve Anton52d86772018-02-20 15:48:12 -08001560void PeerConnection::OnNegotiationNeeded() {
1561 RTC_DCHECK_RUN_ON(signaling_thread());
1562 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001563 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001564}
1565
deadbeeffac06552015-11-25 11:26:01 -08001566rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001567 const std::string& kind,
1568 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001569 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1570 "Plan SdpSemantics. Please use AddTransceiver "
1571 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001572 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001573 if (IsClosed()) {
1574 return nullptr;
1575 }
Steve Anton4171afb2017-11-20 10:20:22 -08001576
Seth Hampson5b4f0752018-04-02 16:31:36 -07001577 // Internally we need to have one stream with Plan B semantics, so we
1578 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001579 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001580 if (stream_id.empty()) {
1581 stream_ids.push_back(rtc::CreateRandomUuid());
1582 RTC_LOG(LS_INFO)
1583 << "No stream_id specified for sender. Generated stream ID: "
1584 << stream_ids[0];
1585 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001586 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001587 }
1588
Steve Anton4171afb2017-11-20 10:20:22 -08001589 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001590 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001591 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001592 auto* audio_sender = new AudioRtpSender(
1593 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001594 audio_sender->SetMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001595 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001596 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001597 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001598 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001599 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001600 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08001601 video_sender->SetMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001602 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001603 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001604 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001605 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001606 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001607 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001608 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001609 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001610
deadbeefe1f9d832016-01-14 15:35:42 -08001611 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001612}
1613
deadbeef70ab1a12015-09-28 16:53:55 -07001614std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1615 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001616 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001617 for (auto sender : GetSendersInternal()) {
1618 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001619 }
1620 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001621}
1622
Steve Anton4171afb2017-11-20 10:20:22 -08001623std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1624PeerConnection::GetSendersInternal() const {
1625 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1626 all_senders;
1627 for (auto transceiver : transceivers_) {
1628 auto senders = transceiver->internal()->senders();
1629 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1630 }
1631 return all_senders;
1632}
1633
deadbeef70ab1a12015-09-28 16:53:55 -07001634std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1635PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001636 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001637 for (const auto& receiver : GetReceiversInternal()) {
1638 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001639 }
1640 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001641}
1642
Steve Anton4171afb2017-11-20 10:20:22 -08001643std::vector<
1644 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1645PeerConnection::GetReceiversInternal() const {
1646 std::vector<
1647 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1648 all_receivers;
1649 for (auto transceiver : transceivers_) {
1650 auto receivers = transceiver->internal()->receivers();
1651 all_receivers.insert(all_receivers.end(), receivers.begin(),
1652 receivers.end());
1653 }
1654 return all_receivers;
1655}
1656
Steve Anton9158ef62017-11-27 13:01:52 -08001657std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1658PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001659 RTC_CHECK(IsUnifiedPlan())
1660 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001661 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1662 for (auto transceiver : transceivers_) {
1663 all_transceivers.push_back(transceiver);
1664 }
1665 return all_transceivers;
1666}
1667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001668bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001669 MediaStreamTrackInterface* track,
1670 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001671 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001672 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001673 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001674 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001675 return false;
1676 }
1677
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001678 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001679 // The StatsCollector is used to tell if a track is valid because it may
1680 // remember tracks that the PeerConnection previously removed.
1681 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001682 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1683 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001684 return false;
1685 }
Steve Antonad182762018-09-05 20:22:40 +00001686 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1687 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688 return true;
1689}
1690
hbos74e1a4f2016-09-15 23:33:01 -07001691void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001692 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001693 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001694 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001695 stats_collector_->GetStatsReport(callback);
1696}
1697
Henrik Boström1df1bf82018-03-20 13:24:20 +01001698void PeerConnection::GetStats(
1699 rtc::scoped_refptr<RtpSenderInterface> selector,
1700 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1701 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1702 RTC_DCHECK(callback);
1703 RTC_DCHECK(stats_collector_);
1704 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1705 if (selector) {
1706 for (const auto& proxy_transceiver : transceivers_) {
1707 for (const auto& proxy_sender :
1708 proxy_transceiver->internal()->senders()) {
1709 if (proxy_sender == selector) {
1710 internal_sender = proxy_sender->internal();
1711 break;
1712 }
1713 }
1714 if (internal_sender)
1715 break;
1716 }
1717 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001718 // If there is no |internal_sender| then |selector| is either null or does not
Henrik Boström1df1bf82018-03-20 13:24:20 +01001719 // belong to the PeerConnection (in Plan B, senders can be removed from the
1720 // PeerConnection). This means that "all the stats objects representing the
1721 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1722 // produces an empty stats report.
1723 stats_collector_->GetStatsReport(internal_sender, callback);
1724}
1725
1726void PeerConnection::GetStats(
1727 rtc::scoped_refptr<RtpReceiverInterface> selector,
1728 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1729 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1730 RTC_DCHECK(callback);
1731 RTC_DCHECK(stats_collector_);
1732 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1733 if (selector) {
1734 for (const auto& proxy_transceiver : transceivers_) {
1735 for (const auto& proxy_receiver :
1736 proxy_transceiver->internal()->receivers()) {
1737 if (proxy_receiver == selector) {
1738 internal_receiver = proxy_receiver->internal();
1739 break;
1740 }
1741 }
1742 if (internal_receiver)
1743 break;
1744 }
1745 }
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01001746 // If there is no |internal_receiver| then |selector| is either null or does
Henrik Boström1df1bf82018-03-20 13:24:20 +01001747 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1748 // the PeerConnection). This means that "all the stats objects representing
1749 // the selector" is an empty set. Invoking GetStatsReport() with a null
1750 // selector produces an empty stats report.
1751 stats_collector_->GetStatsReport(internal_receiver, callback);
1752}
1753
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1755 return signaling_state_;
1756}
1757
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001758PeerConnectionInterface::IceConnectionState
1759PeerConnection::ice_connection_state() {
1760 return ice_connection_state_;
1761}
1762
Jonas Olsson635474e2018-10-18 15:58:17 +02001763PeerConnectionInterface::PeerConnectionState
1764PeerConnection::peer_connection_state() {
1765 return connection_state_;
1766}
1767
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001768PeerConnectionInterface::IceGatheringState
1769PeerConnection::ice_gathering_state() {
1770 return ice_gathering_state_;
1771}
1772
Yves Gerey665174f2018-06-19 15:03:05 +02001773rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001774 const std::string& label,
1775 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001776 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001777
deadbeefab9b2d12015-10-14 11:33:11 -07001778 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001779
kwibergd1fe2812016-04-27 06:47:29 -07001780 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001781 if (config) {
1782 internal_config.reset(new InternalDataChannelInit(*config));
1783 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001784 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001785 InternalCreateDataChannel(label, internal_config.get()));
1786 if (!channel.get()) {
1787 return nullptr;
1788 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001789
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001790 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1791 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001792 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001793 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001794 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001795 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001796 return DataChannelProxy::Create(signaling_thread(), channel.get());
1797}
1798
1799void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001800 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001801 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001802
nisse7ce109a2017-01-31 00:57:56 -08001803 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001804 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001805 return;
1806 }
deadbeefab9b2d12015-10-14 11:33:11 -07001807
Steve Anton8d3444d2017-10-20 15:30:51 -07001808 if (IsClosed()) {
1809 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001810 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001811 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001812 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001813 return;
1814 }
1815
zhihuang1c378ed2017-08-17 14:10:50 -07001816 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001817 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001818 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001819 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001820 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001821 return;
1822 }
1823
Steve Anton22da89f2018-01-25 13:58:07 -08001824 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1825 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1826 if (IsUnifiedPlan()) {
1827 RTCError error = HandleLegacyOfferOptions(options);
1828 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001829 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001830 return;
1831 }
1832 }
1833
zhihuang1c378ed2017-08-17 14:10:50 -07001834 cricket::MediaSessionOptions session_options;
1835 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001836 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001837}
1838
Steve Anton22da89f2018-01-25 13:58:07 -08001839RTCError PeerConnection::HandleLegacyOfferOptions(
1840 const RTCOfferAnswerOptions& options) {
1841 RTC_DCHECK(IsUnifiedPlan());
1842
1843 if (options.offer_to_receive_audio == 0) {
1844 RemoveRecvDirectionFromReceivingTransceiversOfType(
1845 cricket::MEDIA_TYPE_AUDIO);
1846 } else if (options.offer_to_receive_audio == 1) {
1847 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1848 } else if (options.offer_to_receive_audio > 1) {
1849 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1850 "offer_to_receive_audio > 1 is not supported.");
1851 }
1852
1853 if (options.offer_to_receive_video == 0) {
1854 RemoveRecvDirectionFromReceivingTransceiversOfType(
1855 cricket::MEDIA_TYPE_VIDEO);
1856 } else if (options.offer_to_receive_video == 1) {
1857 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1858 } else if (options.offer_to_receive_video > 1) {
1859 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1860 "offer_to_receive_video > 1 is not supported.");
1861 }
1862
1863 return RTCError::OK();
1864}
1865
1866void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1867 cricket::MediaType media_type) {
1868 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001869 RtpTransceiverDirection new_direction =
1870 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1871 if (new_direction != transceiver->direction()) {
1872 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1873 << " transceiver (MID="
1874 << transceiver->mid().value_or("<not set>") << ") from "
1875 << RtpTransceiverDirectionToString(
1876 transceiver->direction())
1877 << " to "
1878 << RtpTransceiverDirectionToString(new_direction)
1879 << " since CreateOffer specified offer_to_receive=0";
1880 transceiver->internal()->set_direction(new_direction);
1881 }
Steve Anton22da89f2018-01-25 13:58:07 -08001882 }
1883}
1884
1885void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1886 cricket::MediaType media_type) {
1887 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001888 RTC_LOG(LS_INFO)
1889 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1890 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001891 RtpTransceiverInit init;
1892 init.direction = RtpTransceiverDirection::kRecvOnly;
1893 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1894 }
1895}
1896
1897std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1898PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1899 std::vector<
1900 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1901 receiving_transceivers;
1902 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001903 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001904 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1905 receiving_transceivers.push_back(transceiver);
1906 }
1907 }
1908 return receiving_transceivers;
1909}
1910
htaa2a49d92016-03-04 02:51:39 -08001911void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1912 const RTCOfferAnswerOptions& options) {
1913 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001914 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001915 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001916 return;
1917 }
1918
Steve Antondffead82018-02-06 10:31:29 -08001919 if (!(signaling_state_ == kHaveRemoteOffer ||
1920 signaling_state_ == kHaveLocalPrAnswer)) {
1921 std::string error =
1922 "PeerConnection cannot create an answer in a state other than "
1923 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001924 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001925 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001926 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001927 return;
1928 }
1929
Steve Antondffead82018-02-06 10:31:29 -08001930 // The remote description should be set if we're in the right state.
1931 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001932
Steve Anton22da89f2018-01-25 13:58:07 -08001933 if (IsUnifiedPlan()) {
1934 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1935 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1936 "supported with Unified Plan semantics. Use the "
1937 "RtpTransceiver API instead.";
1938 }
1939 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1940 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1941 "supported with Unified Plan semantics. Use the "
1942 "RtpTransceiver API instead.";
1943 }
1944 }
1945
htaa2a49d92016-03-04 02:51:39 -08001946 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001947 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001948
Steve Antond25da372017-11-06 14:50:29 -08001949 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001950}
1951
1952void PeerConnection::SetLocalDescription(
1953 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001954 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001955 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001956
Steve Anton80dd7b52018-02-16 17:08:42 -08001957 // The SetLocalDescription contract is that we take ownership of the session
1958 // description regardless of the outcome, so wrap it in a unique_ptr right
1959 // away. Ideally, SetLocalDescription's signature will be changed to take the
1960 // description as a unique_ptr argument to formalize this agreement.
1961 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1962
nisse7ce109a2017-01-31 00:57:56 -08001963 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001964 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001965 return;
1966 }
Steve Anton8a006912017-12-04 15:25:56 -08001967
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001968 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001969 PostSetSessionDescriptionFailure(
1970 observer,
1971 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001972 return;
1973 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001974
Steve Anton80dd7b52018-02-16 17:08:42 -08001975 // If a session error has occurred the PeerConnection is in a possibly
1976 // inconsistent state so fail right away.
1977 if (session_error() != SessionError::kNone) {
1978 std::string error_message = GetSessionErrorMsg();
1979 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001980 PostSetSessionDescriptionFailure(
1981 observer,
1982 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001983 return;
1984 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001985
Steve Anton80dd7b52018-02-16 17:08:42 -08001986 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1987 if (!error.ok()) {
1988 std::string error_message = GetSetDescriptionErrorMessage(
1989 cricket::CS_LOCAL, desc->GetType(), error);
1990 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001991 PostSetSessionDescriptionFailure(
1992 observer,
1993 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001994 return;
1995 }
1996
1997 // Grab the description type before moving ownership to ApplyLocalDescription,
1998 // which may destroy it before returning.
1999 const SdpType type = desc->GetType();
2000
2001 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002002 // |desc| may be destroyed at this point.
2003
2004 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002005 // If ApplyLocalDescription fails, the PeerConnection could be in an
2006 // inconsistent state, so act conservatively here and set the session error
2007 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2008 SetSessionError(SessionError::kContent, error.message());
2009 std::string error_message =
2010 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2011 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002012 PostSetSessionDescriptionFailure(
2013 observer,
2014 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002015 return;
2016 }
Steve Anton8a006912017-12-04 15:25:56 -08002017 RTC_DCHECK(local_description());
2018
2019 PostSetSessionDescriptionSuccess(observer);
2020
Steve Antonad182762018-09-05 20:22:40 +00002021 // MaybeStartGathering needs to be called after posting
2022 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2023 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002024 transport_controller_->MaybeStartGathering();
2025
Steve Antona3a92c22017-12-07 10:27:41 -08002026 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002027 // TODO(deadbeef): We already had to hop to the network thread for
2028 // MaybeStartGathering...
2029 network_thread()->Invoke<void>(
2030 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2031 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002032 // Make UMA notes about what was agreed to.
2033 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002034 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002035 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002036}
2037
2038RTCError PeerConnection::ApplyLocalDescription(
2039 std::unique_ptr<SessionDescriptionInterface> desc) {
2040 RTC_DCHECK_RUN_ON(signaling_thread());
2041 RTC_DCHECK(desc);
2042
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002043 // Update stats here so that we have the most recent stats for tracks and
2044 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002045 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002046
Steve Antondcc3c022017-12-22 16:02:54 -08002047 // Take a reference to the old local description since it's used below to
2048 // compare against the new local description. When setting the new local
2049 // description, grab ownership of the replaced session description in case it
2050 // is the same as |old_local_description|, to keep it alive for the duration
2051 // of the method.
2052 const SessionDescriptionInterface* old_local_description =
2053 local_description();
2054 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002055 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002056 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002057 replaced_local_description = pending_local_description_
2058 ? std::move(pending_local_description_)
2059 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002060 current_local_description_ = std::move(desc);
2061 pending_local_description_ = nullptr;
2062 current_remote_description_ = std::move(pending_remote_description_);
2063 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002064 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002065 pending_local_description_ = std::move(desc);
2066 }
2067 // The session description to apply now must be accessed by
2068 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002069 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002070
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002071 if (!is_caller_) {
2072 if (remote_description()) {
2073 // Remote description was applied first, so this PC is the callee.
2074 is_caller_ = false;
2075 } else {
2076 // Local description is applied first, so this PC is the caller.
2077 is_caller_ = true;
2078 }
2079 }
2080
Zhi Huange830e682018-03-30 10:48:35 -07002081 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2082 if (!error.ok()) {
2083 return error;
2084 }
2085
Steve Antondcc3c022017-12-22 16:02:54 -08002086 if (IsUnifiedPlan()) {
2087 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002088 cricket::CS_LOCAL, *local_description(), old_local_description,
2089 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002090 if (!error.ok()) {
2091 return error;
2092 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002093 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2094 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002095 for (auto transceiver : transceivers_) {
2096 const ContentInfo* content =
2097 FindMediaSectionForTransceiver(transceiver, local_description());
2098 if (!content) {
2099 continue;
2100 }
2101 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002102 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2103 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002104 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002105 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2106 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2107 // "recvonly", process the removal of a remote track for the media
2108 // description, given transceiver, removeList, and muteTracks.
2109 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2110 (transceiver->internal()->fired_direction() &&
2111 RtpTransceiverDirectionHasRecv(
2112 *transceiver->internal()->fired_direction()))) {
2113 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2114 &removed_streams);
2115 }
2116 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2117 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002118 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002119 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002120 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002121 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002122 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002123 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002124 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002125 }
2126 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002127 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002128 }
2129 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002130 // Media channels will be created only when offer is set. These may use new
2131 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002132 if (type == SdpType::kOffer) {
2133 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2134 // description is applied. Restore back to old description.
2135 RTCError error = CreateChannels(*local_description()->description());
2136 if (!error.ok()) {
2137 return error;
2138 }
2139 }
Steve Antondcc3c022017-12-22 16:02:54 -08002140 // Remove unused channels if MediaContentDescription is rejected.
2141 RemoveUnusedChannels(local_description()->description());
2142 }
Steve Anton8a006912017-12-04 15:25:56 -08002143
Zhi Huange830e682018-03-30 10:48:35 -07002144 error = UpdateSessionState(type, cricket::CS_LOCAL,
2145 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002146 if (!error.ok()) {
2147 return error;
2148 }
Steve Antondcc3c022017-12-22 16:02:54 -08002149
Steve Anton8a006912017-12-04 15:25:56 -08002150 if (remote_description()) {
2151 // Now that we have a local description, we can push down remote candidates.
2152 UseCandidatesInSessionDescription(remote_description());
2153 }
2154
2155 pending_ice_restarts_.clear();
2156 if (session_error() != SessionError::kNone) {
2157 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2158 }
2159
deadbeefab9b2d12015-10-14 11:33:11 -07002160 // If setting the description decided our SSL role, allocate any necessary
2161 // SCTP sids.
2162 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002163 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002164 AllocateSctpSids(role);
2165 }
2166
Steve Antond3679212018-01-17 17:41:02 -08002167 if (IsUnifiedPlan()) {
2168 for (auto transceiver : transceivers_) {
2169 const ContentInfo* content =
2170 FindMediaSectionForTransceiver(transceiver, local_description());
2171 if (!content) {
2172 continue;
2173 }
Steve Anton74255ff2018-01-24 18:32:57 -08002174 const auto& streams = content->media_description()->streams();
2175 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002176 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002177 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002178 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002179 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002180 } else {
2181 // 0 is a special value meaning "this sender has no associated send
2182 // stream". Need to call this so the sender won't attempt to configure
2183 // a no longer existing stream and run into DCHECKs in the lower
2184 // layers.
2185 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002186 }
2187 }
2188 } else {
2189 // Plan B semantics.
2190
Steve Antondcc3c022017-12-22 16:02:54 -08002191 // Update state and SSRC of local MediaStreams and DataChannels based on the
2192 // local session description.
2193 const cricket::ContentInfo* audio_content =
2194 GetFirstAudioContent(local_description()->description());
2195 if (audio_content) {
2196 if (audio_content->rejected) {
2197 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2198 } else {
2199 const cricket::AudioContentDescription* audio_desc =
2200 audio_content->media_description()->as_audio();
2201 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2202 }
deadbeeffaac4972015-11-12 15:33:07 -08002203 }
deadbeefab9b2d12015-10-14 11:33:11 -07002204
Steve Antondcc3c022017-12-22 16:02:54 -08002205 const cricket::ContentInfo* video_content =
2206 GetFirstVideoContent(local_description()->description());
2207 if (video_content) {
2208 if (video_content->rejected) {
2209 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2210 } else {
2211 const cricket::VideoContentDescription* video_desc =
2212 video_content->media_description()->as_video();
2213 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2214 }
deadbeeffaac4972015-11-12 15:33:07 -08002215 }
deadbeefab9b2d12015-10-14 11:33:11 -07002216 }
2217
2218 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002219 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002220 if (data_content) {
2221 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002222 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002223 if (rtc::starts_with(data_desc->protocol().data(),
2224 cricket::kMediaProtocolRtpPrefix)) {
2225 UpdateLocalRtpDataChannels(data_desc->streams());
2226 }
2227 }
2228
Steve Anton8a006912017-12-04 15:25:56 -08002229 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002230}
2231
2232void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002233 SetSessionDescriptionObserver* observer,
2234 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002235 SetRemoteDescription(
2236 std::unique_ptr<SessionDescriptionInterface>(desc),
2237 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2238 new SetRemoteDescriptionObserverAdapter(this, observer)));
2239}
2240
2241void PeerConnection::SetRemoteDescription(
2242 std::unique_ptr<SessionDescriptionInterface> desc,
2243 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002244 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002245
nisse7ce109a2017-01-31 00:57:56 -08002246 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002247 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002248 return;
2249 }
Steve Anton8a006912017-12-04 15:25:56 -08002250
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002251 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002252 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002253 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002254 return;
2255 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002256
Steve Anton80dd7b52018-02-16 17:08:42 -08002257 // If a session error has occurred the PeerConnection is in a possibly
2258 // inconsistent state so fail right away.
2259 if (session_error() != SessionError::kNone) {
2260 std::string error_message = GetSessionErrorMsg();
2261 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2262 observer->OnSetRemoteDescriptionComplete(
2263 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2264 return;
2265 }
Steve Anton71439a62018-02-15 11:53:06 -08002266
Steve Antonba42e992018-04-09 14:10:01 -07002267 if (desc->GetType() == SdpType::kOffer) {
2268 // Report to UMA the format of the received offer.
2269 ReportSdpFormatReceived(*desc);
2270 }
2271
Steve Anton80dd7b52018-02-16 17:08:42 -08002272 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002273 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002274 std::string error_message = GetSetDescriptionErrorMessage(
2275 cricket::CS_REMOTE, desc->GetType(), error);
2276 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002277 observer->OnSetRemoteDescriptionComplete(
2278 RTCError(error.type(), std::move(error_message)));
2279 return;
2280 }
Steve Anton71439a62018-02-15 11:53:06 -08002281
Steve Anton80dd7b52018-02-16 17:08:42 -08002282 // Grab the description type before moving ownership to
2283 // ApplyRemoteDescription, which may destroy it before returning.
2284 const SdpType type = desc->GetType();
2285
2286 error = ApplyRemoteDescription(std::move(desc));
2287 // |desc| may be destroyed at this point.
2288
2289 if (!error.ok()) {
2290 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2291 // inconsistent state, so act conservatively here and set the session error
2292 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2293 SetSessionError(SessionError::kContent, error.message());
2294 std::string error_message =
2295 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2296 RTC_LOG(LS_ERROR) << error_message;
2297 observer->OnSetRemoteDescriptionComplete(
2298 RTCError(error.type(), std::move(error_message)));
2299 return;
2300 }
2301 RTC_DCHECK(remote_description());
2302
2303 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002304 // TODO(deadbeef): We already had to hop to the network thread for
2305 // MaybeStartGathering...
2306 network_thread()->Invoke<void>(
2307 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2308 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002309 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002310 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002311 }
2312
2313 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002314 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002315}
2316
2317RTCError PeerConnection::ApplyRemoteDescription(
2318 std::unique_ptr<SessionDescriptionInterface> desc) {
2319 RTC_DCHECK_RUN_ON(signaling_thread());
2320 RTC_DCHECK(desc);
2321
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002322 // Update stats here so that we have the most recent stats for tracks and
2323 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002324 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002325
Steve Antondcc3c022017-12-22 16:02:54 -08002326 // Take a reference to the old remote description since it's used below to
2327 // compare against the new remote description. When setting the new remote
2328 // description, grab ownership of the replaced session description in case it
2329 // is the same as |old_remote_description|, to keep it alive for the duration
2330 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002331 const SessionDescriptionInterface* old_remote_description =
2332 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002333 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002334 SdpType type = desc->GetType();
2335 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002336 replaced_remote_description = pending_remote_description_
2337 ? std::move(pending_remote_description_)
2338 : std::move(current_remote_description_);
2339 current_remote_description_ = std::move(desc);
2340 pending_remote_description_ = nullptr;
2341 current_local_description_ = std::move(pending_local_description_);
2342 } else {
2343 replaced_remote_description = std::move(pending_remote_description_);
2344 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002345 }
Steve Anton8a006912017-12-04 15:25:56 -08002346 // The session description to apply now must be accessed by
2347 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002348 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002349
Zhi Huange830e682018-03-30 10:48:35 -07002350 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2351 if (!error.ok()) {
2352 return error;
2353 }
Steve Anton8a006912017-12-04 15:25:56 -08002354 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002355 if (IsUnifiedPlan()) {
2356 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002357 cricket::CS_REMOTE, *remote_description(), local_description(),
2358 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002359 if (!error.ok()) {
2360 return error;
2361 }
Steve Antondcc3c022017-12-22 16:02:54 -08002362 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002363 // Media channels will be created only when offer is set. These may use new
2364 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002365 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002366 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002367 // description is applied. Restore back to old description.
2368 RTCError error = CreateChannels(*remote_description()->description());
2369 if (!error.ok()) {
2370 return error;
2371 }
2372 }
Steve Antondcc3c022017-12-22 16:02:54 -08002373 // Remove unused channels if MediaContentDescription is rejected.
2374 RemoveUnusedChannels(remote_description()->description());
2375 }
Steve Anton8a006912017-12-04 15:25:56 -08002376
Zhi Huange830e682018-03-30 10:48:35 -07002377 // NOTE: Candidates allocation will be initiated only when
2378 // SetLocalDescription is called.
2379 error = UpdateSessionState(type, cricket::CS_REMOTE,
2380 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002381 if (!error.ok()) {
2382 return error;
2383 }
2384
2385 if (local_description() &&
2386 !UseCandidatesInSessionDescription(remote_description())) {
2387 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2388 }
2389
2390 if (old_remote_description) {
2391 for (const cricket::ContentInfo& content :
2392 old_remote_description->description()->contents()) {
2393 // Check if this new SessionDescription contains new ICE ufrag and
2394 // password that indicates the remote peer requests an ICE restart.
2395 // TODO(deadbeef): When we start storing both the current and pending
2396 // remote description, this should reset pending_ice_restarts and compare
2397 // against the current description.
2398 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2399 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002400 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002401 pending_ice_restarts_.insert(content.name);
2402 }
2403 } else {
2404 // We retain all received candidates only if ICE is not restarted.
2405 // When ICE is restarted, all previous candidates belong to an old
2406 // generation and should not be kept.
2407 // TODO(deadbeef): This goes against the W3C spec which says the remote
2408 // description should only contain candidates from the last set remote
2409 // description plus any candidates added since then. We should remove
2410 // this once we're sure it won't break anything.
2411 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2412 old_remote_description, content.name, mutable_remote_description());
2413 }
2414 }
2415 }
2416
2417 if (session_error() != SessionError::kNone) {
2418 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2419 }
2420
2421 // Set the the ICE connection state to connecting since the connection may
2422 // become writable with peer reflexive candidates before any remote candidate
2423 // is signaled.
2424 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2425 // is to have a new signal the indicates a change in checking state from the
2426 // transport and expose a new checking() member from transport that can be
2427 // read to determine the current checking state. The existing SignalConnecting
2428 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002429 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002430 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002431 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2432 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2433 }
2434
deadbeefab9b2d12015-10-14 11:33:11 -07002435 // If setting the description decided our SSL role, allocate any necessary
2436 // SCTP sids.
2437 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002438 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002439 AllocateSctpSids(role);
2440 }
2441
Steve Antondcc3c022017-12-22 16:02:54 -08002442 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002443 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002444 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002445 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002446 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002447 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002448 for (auto transceiver : transceivers_) {
2449 const ContentInfo* content =
2450 FindMediaSectionForTransceiver(transceiver, remote_description());
2451 if (!content) {
2452 continue;
2453 }
2454 const MediaContentDescription* media_desc = content->media_description();
2455 RtpTransceiverDirection local_direction =
2456 RtpTransceiverDirectionReversed(media_desc->direction());
2457 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2458 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2459 // transceiver's current direction is neither sendrecv nor recvonly,
2460 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002461 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002462 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002463 // The remote description has signaled the stream IDs.
2464 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002465 }
Steve Antondcc3c022017-12-22 16:02:54 -08002466 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002467 (!transceiver->fired_direction() ||
2468 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002469 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002470 << content->name << " (added to "
2471 << GetStreamIdsString(stream_ids) << ").";
2472
2473 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2474 for (const std::string& stream_id : stream_ids) {
2475 rtc::scoped_refptr<MediaStreamInterface> stream =
2476 remote_streams_->find(stream_id);
2477 if (!stream) {
2478 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2479 MediaStream::Create(stream_id));
2480 remote_streams_->AddStream(stream);
2481 added_streams.push_back(stream);
2482 }
2483 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002484 }
Steve Anton3172c032018-05-03 15:30:18 -07002485 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002486 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2487 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002488 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002489 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002490 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002491 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2492 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2493 // removal of a remote track for the media description, given transceiver,
2494 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002495 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002496 (transceiver->fired_direction() &&
2497 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2498 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2499 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002500 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002501 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2502 transceiver->internal()->set_fired_direction(local_direction);
2503 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2504 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002505 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002506 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2507 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002508 transceiver->internal()->set_current_direction(local_direction);
2509 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002510 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2511 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002512 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002513 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2514 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002515 transceiver->Stop();
2516 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002517 if (!content->rejected &&
2518 RtpTransceiverDirectionHasRecv(local_direction)) {
2519 // Set ssrc to 0 in the case of an unsignalled ssrc.
2520 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002521 if (!media_desc->streams().empty() &&
2522 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002523 ssrc = media_desc->streams()[0].first_ssrc();
2524 }
2525 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002526 }
Steve Antondcc3c022017-12-22 16:02:54 -08002527 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002528 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002529 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002530 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002531 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002532 observer->OnTrack(transceiver);
2533 observer->OnAddTrack(transceiver->receiver(),
2534 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002535 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002536 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002537 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002538 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002539 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002540 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002541 }
2542 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002543 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002544 }
Steve Antondcc3c022017-12-22 16:02:54 -08002545 }
2546
Henrik Boströmfdb92012017-11-09 19:55:44 +01002547 const cricket::ContentInfo* audio_content =
2548 GetFirstAudioContent(remote_description()->description());
2549 const cricket::ContentInfo* video_content =
2550 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002551 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002552 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002553 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002554 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002555 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002556 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002557
2558 // Check if the descriptions include streams, just in case the peer supports
2559 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002560 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002561 (audio_desc && !audio_desc->streams().empty()) ||
2562 (video_desc && !video_desc->streams().empty())) {
2563 remote_peer_supports_msid_ = true;
2564 }
deadbeefab9b2d12015-10-14 11:33:11 -07002565
2566 // We wait to signal new streams until we finish processing the description,
2567 // since only at that point will new streams have all their tracks.
2568 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2569
Steve Antondcc3c022017-12-22 16:02:54 -08002570 if (!IsUnifiedPlan()) {
2571 // TODO(steveanton): When removing RTP senders/receivers in response to a
2572 // rejected media section, there is some cleanup logic that expects the
2573 // voice/ video channel to still be set. But in this method the voice/video
2574 // channel would have been destroyed by the SetRemoteDescription caller
2575 // above so the cleanup that relies on them fails to run. The RemoveSenders
2576 // calls should be moved to right before the DestroyChannel calls to fix
2577 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002578
Steve Antondcc3c022017-12-22 16:02:54 -08002579 // Find all audio rtp streams and create corresponding remote AudioTracks
2580 // and MediaStreams.
2581 if (audio_content) {
2582 if (audio_content->rejected) {
2583 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2584 } else {
2585 bool default_audio_track_needed =
2586 !remote_peer_supports_msid_ &&
2587 RtpTransceiverDirectionHasSend(audio_desc->direction());
2588 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2589 default_audio_track_needed, audio_desc->type(),
2590 new_streams);
2591 }
deadbeeffaac4972015-11-12 15:33:07 -08002592 }
deadbeefab9b2d12015-10-14 11:33:11 -07002593
Steve Antondcc3c022017-12-22 16:02:54 -08002594 // Find all video rtp streams and create corresponding remote VideoTracks
2595 // and MediaStreams.
2596 if (video_content) {
2597 if (video_content->rejected) {
2598 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2599 } else {
2600 bool default_video_track_needed =
2601 !remote_peer_supports_msid_ &&
2602 RtpTransceiverDirectionHasSend(video_desc->direction());
2603 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2604 default_video_track_needed, video_desc->type(),
2605 new_streams);
2606 }
deadbeeffaac4972015-11-12 15:33:07 -08002607 }
deadbeefab9b2d12015-10-14 11:33:11 -07002608
Steve Antondcc3c022017-12-22 16:02:54 -08002609 // Update the DataChannels with the information from the remote peer.
2610 if (data_desc) {
2611 if (rtc::starts_with(data_desc->protocol().data(),
2612 cricket::kMediaProtocolRtpPrefix)) {
2613 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2614 }
deadbeefab9b2d12015-10-14 11:33:11 -07002615 }
deadbeefab9b2d12015-10-14 11:33:11 -07002616
Steve Antondcc3c022017-12-22 16:02:54 -08002617 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002618 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002619 for (size_t i = 0; i < new_streams->count(); ++i) {
2620 MediaStreamInterface* new_stream = new_streams->at(i);
2621 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002622 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002623 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2624 }
deadbeefab9b2d12015-10-14 11:33:11 -07002625
Steve Antondcc3c022017-12-22 16:02:54 -08002626 UpdateEndedRemoteMediaStreams();
2627 }
deadbeefab9b2d12015-10-14 11:33:11 -07002628
Steve Anton8a006912017-12-04 15:25:56 -08002629 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002630}
2631
Steve Anton0f5400a2018-07-17 14:25:36 -07002632void PeerConnection::ProcessRemovalOfRemoteTrack(
2633 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2634 transceiver,
2635 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2636 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2637 RTC_DCHECK(transceiver->mid());
2638 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2639 << *transceiver->mid();
2640 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2641 transceiver->internal()->receiver_internal()->streams();
2642 // This will remove the remote track from the streams.
2643 transceiver->internal()->receiver_internal()->set_stream_ids({});
2644 remove_list->push_back(transceiver);
2645 // Remove any streams that no longer have tracks.
2646 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2647 // of streams, see if the stream was removed by checking if this was the
2648 // last receiver with that stream ID.
2649 for (auto stream : media_streams) {
2650 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2651 remote_streams_->RemoveStream(stream);
2652 removed_streams->push_back(stream);
2653 }
2654 }
2655}
2656
Steve Antondcc3c022017-12-22 16:02:54 -08002657RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2658 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002659 const SessionDescriptionInterface& new_session,
2660 const SessionDescriptionInterface* old_local_description,
2661 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002662 RTC_DCHECK(IsUnifiedPlan());
2663
Steve Anton7464fca2018-01-19 11:10:37 -08002664 const cricket::ContentGroup* bundle_group = nullptr;
2665 if (new_session.GetType() == SdpType::kOffer) {
2666 auto bundle_group_or_error =
2667 GetEarlyBundleGroup(*new_session.description());
2668 if (!bundle_group_or_error.ok()) {
2669 return bundle_group_or_error.MoveError();
2670 }
2671 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002672 }
Steve Antondcc3c022017-12-22 16:02:54 -08002673
Steve Antondcc3c022017-12-22 16:02:54 -08002674 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002675 for (size_t i = 0; i < new_contents.size(); ++i) {
2676 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002677 cricket::MediaType media_type = new_content.media_description()->type();
2678 seen_mids_.insert(new_content.name);
2679 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2680 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002681 const cricket::ContentInfo* old_local_content = nullptr;
2682 if (old_local_description &&
2683 i < old_local_description->description()->contents().size()) {
2684 old_local_content =
2685 &old_local_description->description()->contents()[i];
2686 }
2687 const cricket::ContentInfo* old_remote_content = nullptr;
2688 if (old_remote_description &&
2689 i < old_remote_description->description()->contents().size()) {
2690 old_remote_content =
2691 &old_remote_description->description()->contents()[i];
2692 }
Steve Antondcc3c022017-12-22 16:02:54 -08002693 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002694 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2695 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002696 if (!transceiver_or_error.ok()) {
2697 return transceiver_or_error.MoveError();
2698 }
2699 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002700 RTCError error =
2701 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2702 if (!error.ok()) {
2703 return error;
2704 }
2705 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002706 if (GetDataMid() && new_content.name != *GetDataMid()) {
2707 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002708 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2709 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002710 continue;
2711 }
2712 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2713 if (!error.ok()) {
2714 return error;
2715 }
Steve Antondcc3c022017-12-22 16:02:54 -08002716 } else {
2717 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2718 "Unknown section type.");
2719 }
2720 }
2721
2722 return RTCError::OK();
2723}
2724
2725RTCError PeerConnection::UpdateTransceiverChannel(
2726 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2727 transceiver,
2728 const cricket::ContentInfo& content,
2729 const cricket::ContentGroup* bundle_group) {
2730 RTC_DCHECK(IsUnifiedPlan());
2731 RTC_DCHECK(transceiver);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002732 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08002733 if (content.rejected) {
2734 if (channel) {
2735 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08002736 DestroyChannelInterface(channel);
Steve Antondcc3c022017-12-22 16:02:54 -08002737 }
2738 } else {
2739 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002740 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002741 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002742 } else {
Steve Anton69470252018-02-09 11:43:08 -08002743 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002744 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002745 }
2746 if (!channel) {
2747 LOG_AND_RETURN_ERROR(
2748 RTCErrorType::INTERNAL_ERROR,
2749 "Failed to create channel for mid=" + content.name);
2750 }
2751 transceiver->internal()->SetChannel(channel);
2752 }
2753 }
2754 return RTCError::OK();
2755}
2756
Steve Antonfa2260d2017-12-28 16:38:23 -08002757RTCError PeerConnection::UpdateDataChannel(
2758 cricket::ContentSource source,
2759 const cricket::ContentInfo& content,
2760 const cricket::ContentGroup* bundle_group) {
2761 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002762 // If data channels are disabled, ignore this media section. CreateAnswer
2763 // will take care of rejecting it.
2764 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002765 }
2766 if (content.rejected) {
2767 DestroyDataChannel();
2768 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002769 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002770 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002771 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2772 "Failed to create data channel.");
2773 }
2774 }
2775 if (source == cricket::CS_REMOTE) {
2776 const MediaContentDescription* data_desc = content.media_description();
2777 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2778 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2779 }
2780 }
2781 }
2782 return RTCError::OK();
2783}
2784
Steve Antondcc3c022017-12-22 16:02:54 -08002785RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2786PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002787 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002788 size_t mline_index,
2789 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002790 const ContentInfo* old_local_content,
2791 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002792 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002793 // If this is an offer then the m= section might be recycled. If the m=
2794 // section is being recycled (defined as: rejected in the current local or
2795 // remote description and not rejected in new description), dissociate the
2796 // currently associated RtpTransceiver by setting its mid property to null,
2797 // and discard the mapping between the transceiver and its m= section index.
2798 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2799 old_remote_content)) {
2800 // We want to dissociate the transceiver that has the rejected mid.
2801 const std::string& old_mid =
2802 (old_local_content && old_local_content->rejected)
2803 ? old_local_content->name
2804 : old_remote_content->name;
2805 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002806 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002807 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2808 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002809 old_transceiver->internal()->set_mid(absl::nullopt);
2810 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002811 }
2812 }
2813 const MediaContentDescription* media_desc = content.media_description();
2814 auto transceiver = GetAssociatedTransceiver(content.name);
2815 if (source == cricket::CS_LOCAL) {
2816 // Find the RtpTransceiver that corresponds to this m= section, using the
2817 // mapping between transceivers and m= section indices established when
2818 // creating the offer.
2819 if (!transceiver) {
2820 transceiver = GetTransceiverByMLineIndex(mline_index);
2821 }
2822 if (!transceiver) {
2823 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2824 "Unknown transceiver");
2825 }
2826 } else {
2827 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2828 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2829 // of the same type...
2830 if (!transceiver &&
2831 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2832 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2833 }
2834 // If no RtpTransceiver was found in the previous step, create one with a
2835 // recvonly direction.
2836 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002837 RTC_LOG(LS_INFO) << "Adding "
2838 << cricket::MediaTypeToString(media_desc->type())
2839 << " transceiver for MID=" << content.name
2840 << " at i=" << mline_index
2841 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002842 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002843 auto sender =
2844 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002845 std::string receiver_id;
2846 if (!media_desc->streams().empty()) {
2847 receiver_id = media_desc->streams()[0].id;
2848 } else {
2849 receiver_id = rtc::CreateRandomUuid();
2850 }
2851 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002852 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002853 transceiver->internal()->set_direction(
2854 RtpTransceiverDirection::kRecvOnly);
2855 }
2856 }
2857 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002858 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002859 LOG_AND_RETURN_ERROR(
2860 RTCErrorType::INVALID_PARAMETER,
2861 "Transceiver type does not match media description type.");
2862 }
2863 // Associate the found or created RtpTransceiver with the m= section by
2864 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2865 // section, and establish a mapping between the transceiver and the index of
2866 // the m= section.
2867 transceiver->internal()->set_mid(content.name);
2868 transceiver->internal()->set_mline_index(mline_index);
2869 return std::move(transceiver);
2870}
2871
2872rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2873PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2874 RTC_DCHECK(IsUnifiedPlan());
2875 for (auto transceiver : transceivers_) {
2876 if (transceiver->mid() == mid) {
2877 return transceiver;
2878 }
2879 }
2880 return nullptr;
2881}
2882
2883rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2884PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2885 RTC_DCHECK(IsUnifiedPlan());
2886 for (auto transceiver : transceivers_) {
2887 if (transceiver->internal()->mline_index() == mline_index) {
2888 return transceiver;
2889 }
2890 }
2891 return nullptr;
2892}
2893
2894rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2895PeerConnection::FindAvailableTransceiverToReceive(
2896 cricket::MediaType media_type) const {
2897 RTC_DCHECK(IsUnifiedPlan());
2898 // From JSEP section 5.10 (Applying a Remote Description):
2899 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2900 // the same type that were added to the PeerConnection by addTrack and are not
2901 // associated with any m= section and are not stopped, find the first such
2902 // RtpTransceiver.
2903 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002904 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002905 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2906 !transceiver->stopped()) {
2907 return transceiver;
2908 }
2909 }
2910 return nullptr;
2911}
2912
Steve Antoned10bd92017-12-05 10:52:59 -08002913const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2914 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2915 transceiver,
2916 const SessionDescriptionInterface* sdesc) const {
2917 RTC_DCHECK(transceiver);
2918 RTC_DCHECK(sdesc);
2919 if (IsUnifiedPlan()) {
2920 if (!transceiver->internal()->mid()) {
2921 // This transceiver is not associated with a media section yet.
2922 return nullptr;
2923 }
2924 return sdesc->description()->GetContentByName(
2925 *transceiver->internal()->mid());
2926 } else {
2927 // Plan B only allows at most one audio and one video section, so use the
2928 // first media section of that type.
2929 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002930 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002931 }
2932}
2933
deadbeef46c73892016-11-16 19:42:04 -08002934PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2935 return configuration_;
2936}
2937
deadbeef293e9262017-01-11 12:28:30 -08002938bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2939 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002940 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002941 if (IsClosed()) {
2942 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2943 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2944 }
2945
Qingsi Wanga2d60672018-04-11 16:57:45 -07002946 // According to JSEP, after setLocalDescription, changing the candidate pool
2947 // size is not allowed, and changing the set of ICE servers will not result
2948 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002949 if (local_description() && configuration.ice_candidate_pool_size !=
2950 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002951 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2952 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002953 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002954 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002955
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002956 if (local_description() &&
2957 configuration.use_media_transport != configuration_.use_media_transport) {
2958 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2959 "SetLocalDescription.";
2960 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2961 }
2962
2963 if (remote_description() &&
2964 configuration.use_media_transport != configuration_.use_media_transport) {
2965 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2966 "SetRemoteDescription.";
2967 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2968 }
2969
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002970 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002971 configuration.use_media_transport_for_data_channels !=
2972 configuration_.use_media_transport_for_data_channels) {
2973 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2974 "after calling SetLocalDescription.";
2975 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2976 }
2977
2978 if (remote_description() &&
2979 configuration.use_media_transport_for_data_channels !=
2980 configuration_.use_media_transport_for_data_channels) {
2981 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2982 "after calling SetRemoteDescription.";
2983 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2984 }
2985
2986 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002987 configuration.crypto_options != configuration_.crypto_options) {
2988 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2989 "SetLocalDescription.";
2990 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2991 }
2992
Piotr (Peter) Slatala37227be2018-11-21 07:42:22 -08002993 if (configuration.use_media_transport_for_data_channels ||
2994 configuration.use_media_transport) {
2995 RTC_CHECK(configuration.bundle_policy == kBundlePolicyMaxBundle)
2996 << "Media transport requires MaxBundle policy.";
2997 }
2998
deadbeef293e9262017-01-11 12:28:30 -08002999 // The simplest (and most future-compatible) way to tell if the config was
3000 // modified in an invalid way is to copy each property we do support
3001 // modifying, then use operator==. There are far more properties we don't
3002 // support modifying than those we do, and more could be added.
3003 RTCConfiguration modified_config = configuration_;
3004 modified_config.servers = configuration.servers;
3005 modified_config.type = configuration.type;
3006 modified_config.ice_candidate_pool_size =
3007 configuration.ice_candidate_pool_size;
3008 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003009 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003010 modified_config.ice_check_interval_strong_connectivity =
3011 configuration.ice_check_interval_strong_connectivity;
3012 modified_config.ice_check_interval_weak_connectivity =
3013 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003014 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3015 modified_config.ice_unwritable_min_checks =
3016 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003017 modified_config.stun_candidate_keepalive_interval =
3018 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003019 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003020 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003021 modified_config.active_reset_srtp_params =
3022 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003023 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003024 modified_config.use_media_transport_for_data_channels =
3025 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003026 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003027 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003028 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3029 }
3030
Steve Anton038834f2017-07-14 15:59:59 -07003031 // Validate the modified configuration.
3032 RTCError validate_error = ValidateConfiguration(modified_config);
3033 if (!validate_error.ok()) {
3034 return SafeSetError(std::move(validate_error), error);
3035 }
3036
deadbeef293e9262017-01-11 12:28:30 -08003037 // Note that this isn't possible through chromium, since it's an unsigned
3038 // short in WebIDL.
3039 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003040 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003041 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3042 }
3043
3044 // Parse ICE servers before hopping to network thread.
3045 cricket::ServerAddresses stun_servers;
3046 std::vector<cricket::RelayServerConfig> turn_servers;
3047 RTCErrorType parse_error =
3048 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3049 if (parse_error != RTCErrorType::NONE) {
3050 return SafeSetError(parse_error, error);
3051 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003052 // Note if STUN or TURN servers were supplied.
3053 if (!stun_servers.empty()) {
3054 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3055 }
3056 if (!turn_servers.empty()) {
3057 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3058 }
deadbeef293e9262017-01-11 12:28:30 -08003059
3060 // In theory this shouldn't fail.
3061 if (!network_thread()->Invoke<bool>(
3062 RTC_FROM_HERE,
3063 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3064 stun_servers, turn_servers, modified_config.type,
3065 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003066 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003067 modified_config.turn_customizer,
3068 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003069 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003070 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3071 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003072
deadbeefd1a38b52016-12-10 13:15:33 -08003073 // As described in JSEP, calling setConfiguration with new ICE servers or
3074 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3075 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003076 if (modified_config.servers != configuration_.servers ||
3077 modified_config.type != configuration_.type ||
3078 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003079 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003080 }
skvladd1f5fda2017-02-03 16:54:05 -08003081
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003082 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003083 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003084 modified_config.use_media_transport ||
3085 modified_config.use_media_transport_for_data_channels
3086 ? factory_->media_transport_factory()
3087 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003088
Zhi Huangb57e1692018-06-12 11:41:11 -07003089 if (configuration_.active_reset_srtp_params !=
3090 modified_config.active_reset_srtp_params) {
3091 transport_controller_->SetActiveResetSrtpParams(
3092 modified_config.active_reset_srtp_params);
3093 }
3094
deadbeef293e9262017-01-11 12:28:30 -08003095 configuration_ = modified_config;
3096 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003097}
3098
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003099bool PeerConnection::AddIceCandidate(
3100 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003101 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003102 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003103 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003104 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003105 return false;
3106 }
Steve Antond25da372017-11-06 14:50:29 -08003107
3108 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003109 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003110 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003111 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003112 return false;
3113 }
3114
3115 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003116 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003117 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003118 return false;
3119 }
3120
3121 bool valid = false;
3122 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3123 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003124 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003125 return false;
3126 }
3127
3128 // Add this candidate to the remote session description.
3129 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003130 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003131 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003132 return false;
3133 }
3134
3135 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003136 bool result = UseCandidate(ice_candidate);
3137 if (result) {
3138 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3139 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3140 } else {
3141 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3142 }
3143 return result;
Steve Antond25da372017-11-06 14:50:29 -08003144 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003145 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003146 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003147 return true;
3148 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003149}
3150
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003151bool PeerConnection::RemoveIceCandidates(
3152 const std::vector<cricket::Candidate>& candidates) {
3153 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003154 if (IsClosed()) {
3155 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3156 return false;
3157 }
3158
Steve Antond25da372017-11-06 14:50:29 -08003159 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003160 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3161 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003162 return false;
3163 }
3164
3165 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003166 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003167 return false;
3168 }
3169
3170 size_t number_removed =
3171 mutable_remote_description()->RemoveCandidates(candidates);
3172 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003173 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003174 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003175 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003176 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003177 }
3178
3179 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003180 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3181 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003182 RTC_LOG(LS_ERROR)
3183 << "RemoveIceCandidates: Error when removing remote candidates: "
3184 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003185 }
3186 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003187}
3188
Niels Möller0c4f7be2018-05-07 14:01:37 +02003189RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003190 if (!worker_thread()->IsCurrent()) {
3191 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003192 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003193 }
3194
Niels Möller0c4f7be2018-05-07 14:01:37 +02003195 const bool has_min = bitrate.min_bitrate_bps.has_value();
3196 const bool has_start = bitrate.start_bitrate_bps.has_value();
3197 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003198 if (has_min && *bitrate.min_bitrate_bps < 0) {
3199 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3200 "min_bitrate_bps <= 0");
3201 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003202 if (has_start) {
3203 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003204 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003205 "start_bitrate_bps < min_bitrate_bps");
3206 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003207 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3208 "curent_bitrate_bps < 0");
3209 }
3210 }
3211 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003212 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003213 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003214 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003215 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3217 "max_bitrate_bps < min_bitrate_bps");
3218 } else if (*bitrate.max_bitrate_bps < 0) {
3219 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3220 "max_bitrate_bps < 0");
3221 }
3222 }
3223
zstein4b979802017-06-02 14:37:37 -07003224 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003225 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003226
3227 return RTCError::OK();
3228}
3229
Alex Narest78609d52017-10-20 10:37:47 +02003230void PeerConnection::SetBitrateAllocationStrategy(
3231 std::unique_ptr<rtc::BitrateAllocationStrategy>
3232 bitrate_allocation_strategy) {
3233 rtc::Thread* worker_thread = factory_->worker_thread();
3234 if (!worker_thread->IsCurrent()) {
3235 rtc::BitrateAllocationStrategy* strategy_raw =
3236 bitrate_allocation_strategy.release();
3237 auto functor = [this, strategy_raw]() {
3238 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003239 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003240 };
3241 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3242 return;
3243 }
3244 RTC_DCHECK(call_.get());
3245 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3246}
3247
henrika5f6bf242017-11-01 11:06:56 +01003248void PeerConnection::SetAudioPlayout(bool playout) {
3249 if (!worker_thread()->IsCurrent()) {
3250 worker_thread()->Invoke<void>(
3251 RTC_FROM_HERE,
3252 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3253 return;
3254 }
3255 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003256 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003257 audio_state->SetPlayout(playout);
3258}
3259
3260void PeerConnection::SetAudioRecording(bool recording) {
3261 if (!worker_thread()->IsCurrent()) {
3262 worker_thread()->Invoke<void>(
3263 RTC_FROM_HERE,
3264 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3265 return;
3266 }
3267 auto audio_state =
Sebastian Jansson6eb8a162018-11-16 11:29:55 +01003268 factory_->channel_manager()->media_engine()->voice().GetAudioState();
henrika5f6bf242017-11-01 11:06:56 +01003269 audio_state->SetRecording(recording);
3270}
3271
Steve Anton8c0f7a72017-10-03 10:03:10 -07003272std::unique_ptr<rtc::SSLCertificate>
3273PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003274 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3275 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003276 return nullptr;
3277 }
Steve Antonf25303e2018-10-16 15:23:31 -07003278 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003279}
3280
Zhi Huang70b820f2018-01-27 14:16:15 -08003281std::unique_ptr<rtc::SSLCertChain>
3282PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003283 auto audio_transceiver = GetFirstAudioTransceiver();
3284 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003285 return nullptr;
3286 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003287 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003288 audio_transceiver->internal()->channel()->transport_name());
3289}
3290
3291rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3292PeerConnection::GetFirstAudioTransceiver() const {
3293 for (auto transceiver : transceivers_) {
3294 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3295 return transceiver;
3296 }
3297 }
3298 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003299}
3300
ivoc14d5dbe2016-07-04 07:06:55 -07003301bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3302 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003303 // TODO(eladalon): It would be better to not allow negative values into PC.
3304 const size_t max_size = (max_size_bytes < 0)
3305 ? RtcEventLog::kUnlimitedOutput
3306 : rtc::saturated_cast<size_t>(max_size_bytes);
3307 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003308 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003309 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003310}
3311
Bjorn Tereliusde939432017-11-20 17:38:14 +01003312bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3313 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003314 // TODO(eladalon): In C++14, this can be done with a lambda.
3315 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003316 bool operator()() {
3317 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3318 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003319 PeerConnection* const pc;
3320 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003321 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003322 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003323 return worker_thread()->Invoke<bool>(
3324 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003325}
3326
3327void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003328 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003329 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3330}
3331
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003332const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003333 return pending_local_description_ ? pending_local_description_.get()
3334 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003335}
3336
3337const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003338 return pending_remote_description_ ? pending_remote_description_.get()
3339 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003340}
3341
deadbeeffe4a8a42016-12-20 17:56:17 -08003342const SessionDescriptionInterface* PeerConnection::current_local_description()
3343 const {
Steve Anton75737c02017-11-06 10:37:17 -08003344 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003345}
3346
3347const SessionDescriptionInterface* PeerConnection::current_remote_description()
3348 const {
Steve Anton75737c02017-11-06 10:37:17 -08003349 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003350}
3351
3352const SessionDescriptionInterface* PeerConnection::pending_local_description()
3353 const {
Steve Anton75737c02017-11-06 10:37:17 -08003354 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003355}
3356
3357const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3358 const {
Steve Anton75737c02017-11-06 10:37:17 -08003359 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003360}
3361
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003362void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003363 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003364 // Update stats here so that we have the most recent stats for tracks and
3365 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003366 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003367
Steve Anton75737c02017-11-06 10:37:17 -08003368 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003369 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003370
Steve Anton8af21862017-12-15 11:20:13 -08003371 for (auto transceiver : transceivers_) {
3372 transceiver->Stop();
3373 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003374
3375 // Ensure that all asynchronous stats requests are completed before destroying
3376 // the transport controller below.
3377 if (stats_collector_) {
3378 stats_collector_->WaitForPendingRequest();
3379 }
3380
3381 // Don't destroy BaseChannels until after stats has been cleaned up so that
3382 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003383 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003384
Qingsi Wang93a84392018-01-30 17:13:09 -08003385 // The event log is used in the transport controller, which must be outlived
3386 // by the former. CreateOffer by the peer connection is implemented
3387 // asynchronously and if the peer connection is closed without resetting the
3388 // WebRTC session description factory, the session description factory would
3389 // call the transport controller.
3390 webrtc_session_desc_factory_.reset();
3391 transport_controller_.reset();
3392
deadbeef42a42632017-03-10 15:18:00 -08003393 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003394 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3395 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003396
Steve Anton978b8762017-09-29 12:15:02 -07003397 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003398 call_.reset();
3399 // The event log must outlive call (and any other object that uses it).
3400 event_log_.reset();
3401 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003402 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003403 // The .h file says that observer can be discarded after close() returns.
3404 // Make sure this is true.
3405 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003406}
3407
Steve Antonad182762018-09-05 20:22:40 +00003408void PeerConnection::OnMessage(rtc::Message* msg) {
3409 switch (msg->message_id) {
3410 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3411 SetSessionDescriptionMsg* param =
3412 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3413 param->observer->OnSuccess();
3414 delete param;
3415 break;
3416 }
3417 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3418 SetSessionDescriptionMsg* param =
3419 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3420 param->observer->OnFailure(std::move(param->error));
3421 delete param;
3422 break;
3423 }
3424 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3425 CreateSessionDescriptionMsg* param =
3426 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3427 param->observer->OnFailure(std::move(param->error));
3428 delete param;
3429 break;
3430 }
3431 case MSG_GETSTATS: {
3432 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3433 StatsReports reports;
3434 stats_->GetStats(param->track, &reports);
3435 param->observer->OnComplete(reports);
3436 delete param;
3437 break;
3438 }
3439 case MSG_FREE_DATACHANNELS: {
3440 sctp_data_channels_to_free_.clear();
3441 break;
3442 }
3443 case MSG_REPORT_USAGE_PATTERN: {
3444 ReportUsagePattern();
3445 break;
3446 }
3447 default:
3448 RTC_NOTREACHED() << "Not implemented";
3449 break;
3450 }
3451}
3452
Steve Antonafb0bb72018-02-20 11:35:37 -08003453cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3454 RTC_DCHECK(!IsUnifiedPlan());
3455 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3456 GetAudioTransceiver()->internal()->channel());
3457 if (voice_channel) {
3458 return voice_channel->media_channel();
3459 } else {
3460 return nullptr;
3461 }
3462}
3463
3464cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3465 RTC_DCHECK(!IsUnifiedPlan());
3466 auto* video_channel = static_cast<cricket::VideoChannel*>(
3467 GetVideoTransceiver()->internal()->channel());
3468 if (video_channel) {
3469 return video_channel->media_channel();
3470 } else {
3471 return nullptr;
3472 }
3473}
3474
Steve Anton4171afb2017-11-20 10:20:22 -08003475void PeerConnection::CreateAudioReceiver(
3476 MediaStreamInterface* stream,
3477 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003478 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3479 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003480 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3481 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003482 auto* audio_receiver = new AudioRtpReceiver(
3483 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003484 audio_receiver->SetMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003485 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3486 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3487 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003488 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003489 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003490 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003491}
3492
Steve Anton4171afb2017-11-20 10:20:22 -08003493void PeerConnection::CreateVideoReceiver(
3494 MediaStreamInterface* stream,
3495 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003496 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3497 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003498 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3499 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003500 auto* video_receiver = new VideoRtpReceiver(
3501 worker_thread(), remote_sender_info.sender_id, streams);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003502 video_receiver->SetMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003503 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3504 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3505 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003506 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003507 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003508 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003509}
3510
deadbeef70ab1a12015-09-28 16:53:55 -07003511// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3512// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003513rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003514 const RtpSenderInfo& remote_sender_info) {
3515 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3516 if (!receiver) {
3517 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3518 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003519 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003520 }
Steve Anton4171afb2017-11-20 10:20:22 -08003521 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3522 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3523 } else {
3524 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3525 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003526 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003527}
3528
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003529void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3530 MediaStreamInterface* stream) {
3531 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003532 RTC_DCHECK(track);
3533 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003534 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003535 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003536 // We already have a sender for this track, so just change the stream_id
3537 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003538 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003539 return;
3540 }
3541
3542 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003543 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003544 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003545 new_sender->internal()->SetMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003546 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003547 // If the sender has already been configured in SDP, we call SetSsrc,
3548 // which will connect the sender to the underlying transport. This can
3549 // occur if a local session description that contains the ID of the sender
3550 // is set before AddStream is called. It can also occur if the local
3551 // session description is not changed and RemoveStream is called, and
3552 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003553 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003554 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003555 if (sender_info) {
3556 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003557 }
3558}
3559
3560// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3561// indefinitely, when we have unified plan SDP.
3562void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3563 MediaStreamInterface* stream) {
3564 RTC_DCHECK(!IsClosed());
3565 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003566 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003567 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3568 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003569 return;
3570 }
Steve Anton4171afb2017-11-20 10:20:22 -08003571 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003572}
3573
3574void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3575 MediaStreamInterface* stream) {
3576 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003577 RTC_DCHECK(track);
3578 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003579 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003580 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003581 // We already have a sender for this track, so just change the stream_id
3582 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003583 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003584 return;
3585 }
3586
3587 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003588 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003589 {stream->id()}, {});
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08003590 new_sender->internal()->SetMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003591 GetVideoTransceiver()->internal()->AddSender(new_sender);
3592 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003593 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003594 if (sender_info) {
3595 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003596 }
3597}
3598
3599void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3600 MediaStreamInterface* stream) {
3601 RTC_DCHECK(!IsClosed());
3602 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003603 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003604 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3605 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003606 return;
3607 }
Steve Anton4171afb2017-11-20 10:20:22 -08003608 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003609}
3610
Steve Antonba818672017-11-06 10:21:57 -08003611void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003612 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003613 if (ice_connection_state_ == new_state) {
3614 return;
3615 }
3616
deadbeefcbecd352015-09-23 11:50:27 -07003617 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003618 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003619 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003620 return;
3621 }
Steve Antonba818672017-11-06 10:21:57 -08003622
Mirko Bonadei675513b2017-11-09 11:09:25 +01003623 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3624 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003625 RTC_DCHECK(ice_connection_state_ !=
3626 PeerConnectionInterface::kIceConnectionClosed);
3627
Jonas Olsson1e87b4f2018-11-22 16:50:37 +01003628 if (new_state == PeerConnectionInterface::kIceConnectionConnected) {
3629 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
3630 } else if (new_state == PeerConnectionInterface::kIceConnectionCompleted) {
3631 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
3632 ReportTransportStats();
3633 }
3634
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003635 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003636 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003637}
3638
Jonas Olsson635474e2018-10-18 15:58:17 +02003639void PeerConnection::SetConnectionState(
3640 PeerConnectionInterface::PeerConnectionState new_state) {
3641 RTC_DCHECK(signaling_thread()->IsCurrent());
3642 if (connection_state_ == new_state)
3643 return;
3644 if (IsClosed())
3645 return;
3646 connection_state_ = new_state;
3647 Observer()->OnConnectionChange(new_state);
3648}
3649
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003650void PeerConnection::OnIceGatheringChange(
3651 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003652 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003653 if (IsClosed()) {
3654 return;
3655 }
3656 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003657 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003658}
3659
jbauch81bf7b02017-03-25 08:31:12 -07003660void PeerConnection::OnIceCandidate(
3661 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003662 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003663 if (IsClosed()) {
3664 return;
3665 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003666 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003667 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3668 candidate->candidate().address().IsPrivateIP()) {
3669 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3670 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003671 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003672}
3673
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003674void PeerConnection::OnIceCandidatesRemoved(
3675 const std::vector<cricket::Candidate>& candidates) {
3676 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003677 if (IsClosed()) {
3678 return;
3679 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003680 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003681}
3682
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003683void PeerConnection::ChangeSignalingState(
3684 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003685 RTC_DCHECK(signaling_thread()->IsCurrent());
3686 if (signaling_state_ == signaling_state) {
3687 return;
3688 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003689 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3690 << GetSignalingStateString(signaling_state_)
3691 << " New state: "
3692 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003693 signaling_state_ = signaling_state;
3694 if (signaling_state == kClosed) {
3695 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003696 Observer()->OnIceConnectionChange(ice_connection_state_);
Jonas Olsson635474e2018-10-18 15:58:17 +02003697 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3698 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003699 if (ice_gathering_state_ != kIceGatheringComplete) {
3700 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003701 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003702 }
3703 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003704 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003705}
3706
deadbeefeb459812015-12-15 19:24:43 -08003707void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3708 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003709 if (IsClosed()) {
3710 return;
3711 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003712 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003713 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003714}
3715
deadbeefeb459812015-12-15 19:24:43 -08003716void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3717 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003718 if (IsClosed()) {
3719 return;
3720 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003721 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003722 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003723}
3724
3725void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3726 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003727 if (IsClosed()) {
3728 return;
3729 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003730 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003731 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003732}
3733
3734void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3735 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003736 if (IsClosed()) {
3737 return;
3738 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003739 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003740 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003741}
3742
Henrik Boström31638672017-11-23 17:48:32 +01003743void PeerConnection::PostSetSessionDescriptionSuccess(
3744 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003745 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3746 signaling_thread()->Post(RTC_FROM_HERE, this,
3747 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003748}
3749
deadbeefab9b2d12015-10-14 11:33:11 -07003750void PeerConnection::PostSetSessionDescriptionFailure(
3751 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003752 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003753 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003754 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3755 msg->error = std::move(error);
3756 signaling_thread()->Post(RTC_FROM_HERE, this,
3757 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003758}
3759
3760void PeerConnection::PostCreateSessionDescriptionFailure(
3761 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003762 RTCError error) {
3763 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003764 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3765 msg->error = std::move(error);
3766 signaling_thread()->Post(RTC_FROM_HERE, this,
3767 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003768}
3769
zhihuang1c378ed2017-08-17 14:10:50 -07003770void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003771 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003772 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003773 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003774
Steve Antondcc3c022017-12-22 16:02:54 -08003775 if (IsUnifiedPlan()) {
3776 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3777 } else {
3778 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3779 }
3780
Steve Antonfa2260d2017-12-28 16:38:23 -08003781 // Intentionally unset the data channel type for RTP data channel with the
3782 // second condition. Otherwise the RTP data channels would be successfully
3783 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3784 // when building with chromium. We want to leave RTP data channels broken, so
3785 // people won't try to use them.
3786 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3787 session_options->data_channel_type = data_channel_type();
3788 }
3789
Steve Antondcc3c022017-12-22 16:02:54 -08003790 // Apply ICE restart flag and renomination flag.
3791 for (auto& options : session_options->media_description_options) {
3792 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3793 options.transport_options.enable_ice_renomination =
3794 configuration_.enable_ice_renomination;
3795 }
3796
3797 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003798 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08003799 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003800 session_options->pooled_ice_credentials =
3801 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3802 RTC_FROM_HERE,
3803 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3804 port_allocator_.get()));
Johannes Kron89f874e2018-11-12 10:25:48 +01003805 session_options->offer_extmap_allow_mixed =
3806 configuration_.offer_extmap_allow_mixed;
Steve Antondcc3c022017-12-22 16:02:54 -08003807}
3808
3809void PeerConnection::GetOptionsForPlanBOffer(
3810 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3811 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003812 // Figure out transceiver directional preferences.
3813 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3814 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3815
3816 // By default, generate sendrecv/recvonly m= sections.
3817 bool recv_audio = true;
3818 bool recv_video = true;
3819
3820 // By default, only offer a new m= section if we have media to send with it.
3821 bool offer_new_audio_description = send_audio;
3822 bool offer_new_video_description = send_video;
3823 bool offer_new_data_description = HasDataChannels();
3824
3825 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003826 if (offer_answer_options.offer_to_receive_audio !=
3827 RTCOfferAnswerOptions::kUndefined) {
3828 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003829 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003830 offer_new_audio_description ||
3831 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003832 }
Steve Antondcc3c022017-12-22 16:02:54 -08003833 if (offer_answer_options.offer_to_receive_video !=
3834 RTCOfferAnswerOptions::kUndefined) {
3835 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003836 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003837 offer_new_video_description ||
3838 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003839 }
3840
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003841 absl::optional<size_t> audio_index;
3842 absl::optional<size_t> video_index;
3843 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003844 // If a current description exists, generate m= sections in the same order,
3845 // using the first audio/video/data section that appears and rejecting
3846 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003847 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003848 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003849 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003850 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3851 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3852 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003853 }
3854
zhihuang1c378ed2017-08-17 14:10:50 -07003855 // Add audio/video/data m= sections to the end if needed.
3856 if (!audio_index && offer_new_audio_description) {
3857 session_options->media_description_options.push_back(
3858 cricket::MediaDescriptionOptions(
3859 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003860 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3861 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003862 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003863 }
zhihuang1c378ed2017-08-17 14:10:50 -07003864 if (!video_index && offer_new_video_description) {
3865 session_options->media_description_options.push_back(
3866 cricket::MediaDescriptionOptions(
3867 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003868 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3869 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003870 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003871 }
zhihuang1c378ed2017-08-17 14:10:50 -07003872 if (!data_index && offer_new_data_description) {
3873 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003874 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003875 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003876 }
3877
3878 cricket::MediaDescriptionOptions* audio_media_description_options =
3879 !audio_index ? nullptr
3880 : &session_options->media_description_options[*audio_index];
3881 cricket::MediaDescriptionOptions* video_media_description_options =
3882 !video_index ? nullptr
3883 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003884
Steve Anton4171afb2017-11-20 10:20:22 -08003885 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003886 video_media_description_options,
3887 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003888}
3889
3890// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3891// and return a reference to it.
3892// Generated MIDs should be no more than 3 bytes long to take up less space in
3893// the RTP packet.
3894static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3895 RTC_DCHECK(used_mids);
3896 // We're boring: just generate MIDs 0, 1, 2, ...
3897 size_t i = 0;
3898 std::set<std::string>::iterator it;
3899 bool inserted;
3900 do {
3901 std::string mid = rtc::ToString(i++);
3902 auto insert_result = used_mids->insert(mid);
3903 it = insert_result.first;
3904 inserted = insert_result.second;
3905 } while (!inserted);
3906 return *it;
3907}
3908
3909static cricket::MediaDescriptionOptions
3910GetMediaDescriptionOptionsForTransceiver(
3911 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3912 transceiver,
3913 const std::string& mid) {
3914 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003915 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003916 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003917 // This behavior is specified in JSEP. The gist is that:
3918 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3919 // sendrecv.
3920 // 2. If the MSID is included, then it must be included in any subsequent
3921 // offer/answer exactly the same until the RtpTransceiver is stopped.
3922 if (!transceiver->stopped() &&
3923 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3924 transceiver->internal()->has_ever_been_used_to_send())) {
3925 cricket::SenderOptions sender_options;
3926 sender_options.track_id = transceiver->sender()->id();
3927 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003928 int num_send_encoding_layers =
3929 transceiver->sender()->init_send_encodings().size();
3930 sender_options.num_sim_layers =
3931 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003932 media_description_options.sender_options.push_back(sender_options);
3933 }
Steve Antondcc3c022017-12-22 16:02:54 -08003934 return media_description_options;
3935}
3936
3937void PeerConnection::GetOptionsForUnifiedPlanOffer(
3938 const RTCOfferAnswerOptions& offer_answer_options,
3939 cricket::MediaSessionOptions* session_options) {
3940 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3941 // Offers) and 5.2.2 (Subsequent Offers).
3942 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3943 const ContentInfos& local_contents =
3944 (local_description() ? local_description()->description()->contents()
3945 : ContentInfos());
3946 const ContentInfos& remote_contents =
3947 (remote_description() ? remote_description()->description()->contents()
3948 : ContentInfos());
3949 // The mline indices that can be recycled. New transceivers should reuse these
3950 // slots first.
3951 std::queue<size_t> recycleable_mline_indices;
3952 // Track the MIDs used in previous offer/answer exchanges and the current
3953 // offer so that new, unique MIDs are generated.
3954 std::set<std::string> used_mids = seen_mids_;
3955 // First, go through each media section that exists in either the local or
3956 // remote description and generate a media section in this offer for the
3957 // associated transceiver. If a media section can be recycled, generate a
3958 // default, rejected media section here that can be later overwritten.
3959 for (size_t i = 0;
3960 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3961 // Either |local_content| or |remote_content| is non-null.
3962 const ContentInfo* local_content =
3963 (i < local_contents.size() ? &local_contents[i] : nullptr);
3964 const ContentInfo* remote_content =
3965 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3966 bool had_been_rejected = (local_content && local_content->rejected) ||
3967 (remote_content && remote_content->rejected);
3968 const std::string& mid =
3969 (local_content ? local_content->name : remote_content->name);
3970 cricket::MediaType media_type =
3971 (local_content ? local_content->media_description()->type()
3972 : remote_content->media_description()->type());
3973 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3974 media_type == cricket::MEDIA_TYPE_VIDEO) {
3975 auto transceiver = GetAssociatedTransceiver(mid);
3976 RTC_CHECK(transceiver);
3977 // A media section is considered eligible for recycling if it is marked as
3978 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003979 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003980 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003981 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3982 RtpTransceiverDirection::kInactive,
3983 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003984 recycleable_mline_indices.push(i);
3985 } else {
3986 session_options->media_description_options.push_back(
3987 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3988 // CreateOffer shouldn't really cause any state changes in
3989 // PeerConnection, but we need a way to match new transceivers to new
3990 // media sections in SetLocalDescription and JSEP specifies this is done
3991 // by recording the index of the media section generated for the
3992 // transceiver in the offer.
3993 transceiver->internal()->set_mline_index(i);
3994 }
3995 } else {
3996 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003997 RTC_CHECK(GetDataMid());
3998 if (had_been_rejected || mid != *GetDataMid()) {
3999 session_options->media_description_options.push_back(
4000 GetMediaDescriptionOptionsForRejectedData(mid));
4001 } else {
4002 session_options->media_description_options.push_back(
4003 GetMediaDescriptionOptionsForActiveData(mid));
4004 }
Steve Antondcc3c022017-12-22 16:02:54 -08004005 }
4006 }
4007 // Next, look for transceivers that are newly added (that is, are not stopped
4008 // and not associated). Reuse media sections marked as recyclable first,
4009 // otherwise append to the end of the offer. New media sections should be
4010 // added in the order they were added to the PeerConnection.
4011 for (auto transceiver : transceivers_) {
4012 if (transceiver->mid() || transceiver->stopped()) {
4013 continue;
4014 }
4015 size_t mline_index;
4016 if (!recycleable_mline_indices.empty()) {
4017 mline_index = recycleable_mline_indices.front();
4018 recycleable_mline_indices.pop();
4019 session_options->media_description_options[mline_index] =
4020 GetMediaDescriptionOptionsForTransceiver(transceiver,
4021 AllocateMid(&used_mids));
4022 } else {
4023 mline_index = session_options->media_description_options.size();
4024 session_options->media_description_options.push_back(
4025 GetMediaDescriptionOptionsForTransceiver(transceiver,
4026 AllocateMid(&used_mids)));
4027 }
4028 // See comment above for why CreateOffer changes the transceiver's state.
4029 transceiver->internal()->set_mline_index(mline_index);
4030 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004031 // Lastly, add a m-section if we have local data channels and an m section
4032 // does not already exist.
4033 if (!GetDataMid() && HasDataChannels()) {
4034 session_options->media_description_options.push_back(
4035 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4036 }
Steve Antondcc3c022017-12-22 16:02:54 -08004037}
4038
4039void PeerConnection::GetOptionsForAnswer(
4040 const RTCOfferAnswerOptions& offer_answer_options,
4041 cricket::MediaSessionOptions* session_options) {
4042 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4043
4044 if (IsUnifiedPlan()) {
4045 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4046 } else {
4047 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4048 }
4049
Steve Antonfa2260d2017-12-28 16:38:23 -08004050 // Intentionally unset the data channel type for RTP data channel. Otherwise
4051 // the RTP data channels would be successfully negotiated by default and the
4052 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4053 // We want to leave RTP data channels broken, so people won't try to use them.
4054 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4055 session_options->data_channel_type = data_channel_type();
4056 }
4057
Steve Antondcc3c022017-12-22 16:02:54 -08004058 // Apply ICE renomination flag.
4059 for (auto& options : session_options->media_description_options) {
4060 options.transport_options.enable_ice_renomination =
4061 configuration_.enable_ice_renomination;
4062 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004063
4064 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004065 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08004066 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004067 session_options->pooled_ice_credentials =
4068 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4069 RTC_FROM_HERE,
4070 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4071 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004072}
4073
Steve Antondcc3c022017-12-22 16:02:54 -08004074void PeerConnection::GetOptionsForPlanBAnswer(
4075 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004076 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004077 // Figure out transceiver directional preferences.
4078 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4079 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4080
4081 // By default, generate sendrecv/recvonly m= sections. The direction is also
4082 // restricted by the direction in the offer.
4083 bool recv_audio = true;
4084 bool recv_video = true;
4085
4086 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004087 if (offer_answer_options.offer_to_receive_audio !=
4088 RTCOfferAnswerOptions::kUndefined) {
4089 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004090 }
Steve Antondcc3c022017-12-22 16:02:54 -08004091 if (offer_answer_options.offer_to_receive_video !=
4092 RTCOfferAnswerOptions::kUndefined) {
4093 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004094 }
4095
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004096 absl::optional<size_t> audio_index;
4097 absl::optional<size_t> video_index;
4098 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004099
4100 // Generate m= sections that match those in the offer.
4101 // Note that mediasession.cc will handle intersection our preferred
4102 // direction with the offered direction.
4103 GenerateMediaDescriptionOptions(
4104 remote_description(),
4105 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4106 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4107 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004108
4109 cricket::MediaDescriptionOptions* audio_media_description_options =
4110 !audio_index ? nullptr
4111 : &session_options->media_description_options[*audio_index];
4112 cricket::MediaDescriptionOptions* video_media_description_options =
4113 !video_index ? nullptr
4114 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004115
Steve Anton4171afb2017-11-20 10:20:22 -08004116 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004117 video_media_description_options,
4118 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004119}
zhihuangaf388472016-11-02 16:49:48 -07004120
Steve Antondcc3c022017-12-22 16:02:54 -08004121void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4122 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4123 cricket::MediaSessionOptions* session_options) {
4124 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4125 // Answers) and 5.3.2 (Subsequent Answers).
4126 RTC_DCHECK(remote_description());
4127 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4128 for (const ContentInfo& content :
4129 remote_description()->description()->contents()) {
4130 cricket::MediaType media_type = content.media_description()->type();
4131 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4132 media_type == cricket::MEDIA_TYPE_VIDEO) {
4133 auto transceiver = GetAssociatedTransceiver(content.name);
4134 RTC_CHECK(transceiver);
4135 session_options->media_description_options.push_back(
4136 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4137 } else {
4138 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004139 // Reject all data sections if data channels are disabled.
4140 // Reject a data section if it has already been rejected.
4141 // Reject all data sections except for the first one.
4142 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4143 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004144 session_options->media_description_options.push_back(
4145 GetMediaDescriptionOptionsForRejectedData(content.name));
4146 } else {
4147 session_options->media_description_options.push_back(
4148 GetMediaDescriptionOptionsForActiveData(content.name));
4149 }
Steve Antondcc3c022017-12-22 16:02:54 -08004150 }
4151 }
htaa2a49d92016-03-04 02:51:39 -08004152}
4153
zhihuang1c378ed2017-08-17 14:10:50 -07004154void PeerConnection::GenerateMediaDescriptionOptions(
4155 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004156 RtpTransceiverDirection audio_direction,
4157 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004158 absl::optional<size_t>* audio_index,
4159 absl::optional<size_t>* video_index,
4160 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004161 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004162 for (const cricket::ContentInfo& content :
4163 session_desc->description()->contents()) {
4164 if (IsAudioContent(&content)) {
4165 // If we already have an audio m= section, reject this extra one.
4166 if (*audio_index) {
4167 session_options->media_description_options.push_back(
4168 cricket::MediaDescriptionOptions(
4169 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004170 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004171 } else {
4172 session_options->media_description_options.push_back(
4173 cricket::MediaDescriptionOptions(
4174 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004175 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004176 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004177 }
4178 } else if (IsVideoContent(&content)) {
4179 // If we already have an video m= section, reject this extra one.
4180 if (*video_index) {
4181 session_options->media_description_options.push_back(
4182 cricket::MediaDescriptionOptions(
4183 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004184 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004185 } else {
4186 session_options->media_description_options.push_back(
4187 cricket::MediaDescriptionOptions(
4188 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004189 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004190 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004191 }
4192 } else {
4193 RTC_DCHECK(IsDataContent(&content));
4194 // If we already have an data m= section, reject this extra one.
4195 if (*data_index) {
4196 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004197 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004198 } else {
4199 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004200 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004201 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004202 }
4203 }
htaa2a49d92016-03-04 02:51:39 -08004204 }
deadbeefab9b2d12015-10-14 11:33:11 -07004205}
4206
Steve Antonfa2260d2017-12-28 16:38:23 -08004207cricket::MediaDescriptionOptions
4208PeerConnection::GetMediaDescriptionOptionsForActiveData(
4209 const std::string& mid) const {
4210 // Direction for data sections is meaningless, but legacy endpoints might
4211 // expect sendrecv.
4212 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4213 RtpTransceiverDirection::kSendRecv,
4214 /*stopped=*/false);
4215 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4216 return options;
4217}
4218
4219cricket::MediaDescriptionOptions
4220PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4221 const std::string& mid) const {
4222 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4223 RtpTransceiverDirection::kInactive,
4224 /*stopped=*/true);
4225 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4226 return options;
4227}
4228
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004229absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004230 switch (data_channel_type_) {
4231 case cricket::DCT_RTP:
4232 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004233 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004234 }
4235 return rtp_data_channel_->content_name();
4236 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004237 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004238 case cricket::DCT_MEDIA_TRANSPORT:
4239 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004240 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004241 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004242 }
4243}
4244
Steve Anton4171afb2017-11-20 10:20:22 -08004245void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4246 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4247 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004248 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004249}
4250
Steve Anton4171afb2017-11-20 10:20:22 -08004251void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004252 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004253 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004254 cricket::MediaType media_type,
4255 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004256 RTC_DCHECK(!IsUnifiedPlan());
4257
Steve Anton4171afb2017-11-20 10:20:22 -08004258 std::vector<RtpSenderInfo>* current_senders =
4259 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004260
Steve Anton4171afb2017-11-20 10:20:22 -08004261 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004262 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004263 for (auto sender_it = current_senders->begin();
4264 sender_it != current_senders->end();
4265 /* incremented manually */) {
4266 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004267 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004268 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004269 std::string params_stream_id;
4270 if (params) {
4271 params_stream_id =
4272 (!params->first_stream_id().empty() ? params->first_stream_id()
4273 : kDefaultStreamId);
4274 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004275 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004276 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004277 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004278 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004279 sender_exists) {
4280 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004281 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004282 OnRemoteSenderRemoved(info, media_type);
4283 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004284 }
4285 }
4286
Steve Anton4171afb2017-11-20 10:20:22 -08004287 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004288 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004289 if (!params.has_ssrcs()) {
4290 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4291 // sender, this means it is coming from a Unified Plan endpoint,so we just
4292 // create a default.
4293 default_sender_needed = true;
4294 break;
4295 }
4296
Seth Hampson845e8782018-03-02 11:34:10 -08004297 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004298 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004299 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4300 // not supported in Plan B, we just take the first here and create the
4301 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004302 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004303 (!params.first_stream_id().empty() ? params.first_stream_id()
4304 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004305 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004306 uint32_t ssrc = params.first_ssrc();
4307
4308 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004309 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004310 if (!stream) {
4311 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004312 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004313 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004314 remote_streams_->AddStream(stream);
4315 new_streams->AddStream(stream);
4316 }
4317
Steve Anton4171afb2017-11-20 10:20:22 -08004318 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004319 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004320 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004321 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004322 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004323 }
4324 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004325
Steve Anton4171afb2017-11-20 10:20:22 -08004326 // Add default sender if necessary.
4327 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004328 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004329 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004330 if (!default_stream) {
4331 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004332 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004333 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004334 remote_streams_->AddStream(default_stream);
4335 new_streams->AddStream(default_stream);
4336 }
Steve Anton4171afb2017-11-20 10:20:22 -08004337 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4338 ? kDefaultAudioSenderId
4339 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004340 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004341 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004342 if (!default_sender_info) {
4343 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004344 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004345 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004346 }
4347 }
deadbeefab9b2d12015-10-14 11:33:11 -07004348}
4349
Steve Anton4171afb2017-11-20 10:20:22 -08004350void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4351 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004352 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4353 << " receiver for track_id=" << sender_info.sender_id
4354 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004355
Steve Anton3d954a62018-04-02 11:27:23 -07004356 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004357 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004358 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004359 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004360 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004361 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004362 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004363 }
4364}
4365
Steve Anton4171afb2017-11-20 10:20:22 -08004366void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4367 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004368 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4369 << " receiver for track_id=" << sender_info.sender_id
4370 << " and stream_id=" << sender_info.stream_id;
4371
Seth Hampson845e8782018-03-02 11:34:10 -08004372 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004373
Henrik Boström933d8b02017-10-10 10:05:16 -07004374 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004375 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004376 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4377 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004378 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004379 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004380 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004381 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004382 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004383 }
4384 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004385 // Stopping or destroying a VideoRtpReceiver will end the
4386 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004387 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004388 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004389 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004390 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004391 // There's no guarantee the track is still available, e.g. the track may
4392 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004393 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004394 }
4395 } else {
nisseede5da42017-01-12 05:15:36 -08004396 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004397 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004398 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004399 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004400 }
deadbeefab9b2d12015-10-14 11:33:11 -07004401}
4402
4403void PeerConnection::UpdateEndedRemoteMediaStreams() {
4404 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4405 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4406 MediaStreamInterface* stream = remote_streams_->at(i);
4407 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4408 streams_to_remove.push_back(stream);
4409 }
4410 }
4411
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004412 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004413 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004414 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004415 }
4416}
4417
Steve Anton4171afb2017-11-20 10:20:22 -08004418void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004419 const std::vector<cricket::StreamParams>& streams,
4420 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004421 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004422
Seth Hampson845e8782018-03-02 11:34:10 -08004423 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004424 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004425 for (auto sender_it = current_senders->begin();
4426 sender_it != current_senders->end();
4427 /* incremented manually */) {
4428 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004429 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004430 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4431 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004432 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004433 OnLocalSenderRemoved(info, media_type);
4434 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004435 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004436 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004437 }
4438 }
4439
Steve Anton4171afb2017-11-20 10:20:22 -08004440 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004441 for (const cricket::StreamParams& params : streams) {
4442 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004443 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004444 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004445 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004446 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004447 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004448 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004449 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004450 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004451 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004452 }
4453 }
4454}
4455
Steve Anton4171afb2017-11-20 10:20:22 -08004456void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4457 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004458 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004459 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004460 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004461 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4462 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004463 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004464 return;
4465 }
4466
deadbeeffac06552015-11-25 11:26:01 -08004467 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004468 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004469 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004470 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004471 }
deadbeeffac06552015-11-25 11:26:01 -08004472
Seth Hampson5b4f0752018-04-02 16:31:36 -07004473 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004474 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004475}
4476
Steve Anton4171afb2017-11-20 10:20:22 -08004477void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4478 cricket::MediaType media_type) {
4479 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004480 if (!sender) {
4481 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004482 // SessionDescriptions has been renegotiated.
4483 return;
4484 }
deadbeeffac06552015-11-25 11:26:01 -08004485
4486 // A sender has been removed from the SessionDescription but it's still
4487 // associated with the PeerConnection. This only occurs if the SDP doesn't
4488 // match with the calls to CreateSender, AddStream and RemoveStream.
4489 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004490 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004491 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004492 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004493 }
deadbeeffac06552015-11-25 11:26:01 -08004494
Steve Anton4171afb2017-11-20 10:20:22 -08004495 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004496}
4497
4498void PeerConnection::UpdateLocalRtpDataChannels(
4499 const cricket::StreamParamsVec& streams) {
4500 std::vector<std::string> existing_channels;
4501
4502 // Find new and active data channels.
4503 for (const cricket::StreamParams& params : streams) {
4504 // |it->sync_label| is actually the data channel label. The reason is that
4505 // we use the same naming of data channels as we do for
4506 // MediaStreams and Tracks.
4507 // For MediaStreams, the sync_label is the MediaStream label and the
4508 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004509 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004510 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004511 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004512 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004513 continue;
4514 }
4515 // Set the SSRC the data channel should use for sending.
4516 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4517 existing_channels.push_back(data_channel_it->first);
4518 }
4519
4520 UpdateClosingRtpDataChannels(existing_channels, true);
4521}
4522
4523void PeerConnection::UpdateRemoteRtpDataChannels(
4524 const cricket::StreamParamsVec& streams) {
4525 std::vector<std::string> existing_channels;
4526
4527 // Find new and active data channels.
4528 for (const cricket::StreamParams& params : streams) {
4529 // The data channel label is either the mslabel or the SSRC if the mslabel
4530 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004531 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004532 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004533 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004534 auto data_channel_it = rtp_data_channels_.find(label);
4535 if (data_channel_it == rtp_data_channels_.end()) {
4536 // This is a new data channel.
4537 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4538 } else {
4539 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4540 }
4541 existing_channels.push_back(label);
4542 }
4543
4544 UpdateClosingRtpDataChannels(existing_channels, false);
4545}
4546
4547void PeerConnection::UpdateClosingRtpDataChannels(
4548 const std::vector<std::string>& active_channels,
4549 bool is_local_update) {
4550 auto it = rtp_data_channels_.begin();
4551 while (it != rtp_data_channels_.end()) {
4552 DataChannel* data_channel = it->second;
4553 if (std::find(active_channels.begin(), active_channels.end(),
4554 data_channel->label()) != active_channels.end()) {
4555 ++it;
4556 continue;
4557 }
4558
4559 if (is_local_update) {
4560 data_channel->SetSendSsrc(0);
4561 } else {
4562 data_channel->RemotePeerRequestClose();
4563 }
4564
4565 if (data_channel->state() == DataChannel::kClosed) {
4566 rtp_data_channels_.erase(it);
4567 it = rtp_data_channels_.begin();
4568 } else {
4569 ++it;
4570 }
4571 }
4572}
4573
4574void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4575 uint32_t remote_ssrc) {
4576 rtc::scoped_refptr<DataChannel> channel(
4577 InternalCreateDataChannel(label, nullptr));
4578 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004579 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004580 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004581 return;
4582 }
4583 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004584 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4585 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004586 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004587}
4588
4589rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4590 const std::string& label,
4591 const InternalDataChannelInit* config) {
4592 if (IsClosed()) {
4593 return nullptr;
4594 }
Steve Anton75737c02017-11-06 10:37:17 -08004595 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004596 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004597 << "InternalCreateDataChannel: Data is not supported in this call.";
4598 return nullptr;
4599 }
4600 InternalDataChannelInit new_config =
4601 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004602 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004603 if (new_config.id < 0) {
4604 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004605 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004606 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004607 RTC_LOG(LS_ERROR)
4608 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004609 return nullptr;
4610 }
4611 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004612 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004613 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004614 return nullptr;
4615 }
4616 }
4617
Steve Anton75737c02017-11-06 10:37:17 -08004618 rtc::scoped_refptr<DataChannel> channel(
4619 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004620 if (!channel) {
4621 sid_allocator_.ReleaseSid(new_config.id);
4622 return nullptr;
4623 }
4624
4625 if (channel->data_channel_type() == cricket::DCT_RTP) {
4626 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004627 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4628 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004629 return nullptr;
4630 }
4631 rtp_data_channels_[channel->label()] = channel;
4632 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004633 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004634 sctp_data_channels_.push_back(channel);
4635 channel->SignalClosed.connect(this,
4636 &PeerConnection::OnSctpDataChannelClosed);
4637 }
4638
Steve Anton2d8609c2018-01-23 16:38:46 -08004639 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004640 return channel;
4641}
4642
4643bool PeerConnection::HasDataChannels() const {
4644 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4645}
4646
4647void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4648 for (const auto& channel : sctp_data_channels_) {
4649 if (channel->id() < 0) {
4650 int sid;
4651 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004652 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004653 continue;
4654 }
4655 channel->SetSctpSid(sid);
4656 }
4657 }
4658}
4659
4660void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004661 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004662 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4663 ++it) {
4664 if (it->get() == channel) {
4665 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004666 // After the closing procedure is done, it's safe to use this ID for
4667 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004668 sid_allocator_.ReleaseSid(channel->id());
4669 }
deadbeefbd292462015-12-14 18:15:29 -08004670 // Since this method is triggered by a signal from the DataChannel,
4671 // we can't free it directly here; we need to free it asynchronously.
4672 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004673 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004674 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4675 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004676 return;
4677 }
4678 }
4679}
4680
deadbeefab9b2d12015-10-14 11:33:11 -07004681void PeerConnection::OnDataChannelDestroyed() {
4682 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4683 // DataChannel may callback to us and try to modify the list.
4684 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4685 temp_rtp_dcs.swap(rtp_data_channels_);
4686 for (const auto& kv : temp_rtp_dcs) {
4687 kv.second->OnTransportChannelDestroyed();
4688 }
4689
4690 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4691 temp_sctp_dcs.swap(sctp_data_channels_);
4692 for (const auto& channel : temp_sctp_dcs) {
4693 channel->OnTransportChannelDestroyed();
4694 }
4695}
4696
4697void PeerConnection::OnDataChannelOpenMessage(
4698 const std::string& label,
4699 const InternalDataChannelInit& config) {
4700 rtc::scoped_refptr<DataChannel> channel(
4701 InternalCreateDataChannel(label, &config));
4702 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004703 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004704 return;
4705 }
4706
deadbeefa601f5c2016-06-06 14:27:39 -07004707 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4708 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004709 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004710 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004711}
4712
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004713bool PeerConnection::HandleOpenMessage_s(
4714 const cricket::ReceiveDataParams& params,
4715 const rtc::CopyOnWriteBuffer& buffer) {
4716 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4717 // Received OPEN message; parse and signal that a new data channel should
4718 // be created.
4719 std::string label;
4720 InternalDataChannelInit config;
4721 config.id = params.ssrc;
4722 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4723 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4724 << params.ssrc;
4725 return true;
4726 }
4727 config.open_handshake_role = InternalDataChannelInit::kAcker;
4728 OnDataChannelOpenMessage(label, config);
4729 return true;
4730 }
4731 return false;
4732}
4733
Steve Anton4171afb2017-11-20 10:20:22 -08004734rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4735PeerConnection::GetAudioTransceiver() const {
4736 // This method only works with Plan B SDP, where there is a single
4737 // audio/video transceiver.
4738 RTC_DCHECK(!IsUnifiedPlan());
4739 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004740 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004741 return transceiver;
4742 }
4743 }
4744 RTC_NOTREACHED();
4745 return nullptr;
4746}
4747
4748rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4749PeerConnection::GetVideoTransceiver() const {
4750 // This method only works with Plan B SDP, where there is a single
4751 // audio/video transceiver.
4752 RTC_DCHECK(!IsUnifiedPlan());
4753 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004754 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004755 return transceiver;
4756 }
4757 }
4758 RTC_NOTREACHED();
4759 return nullptr;
4760}
4761
4762// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4763// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004764bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004765 switch (type) {
4766 case cricket::MEDIA_TYPE_AUDIO:
4767 return !GetAudioTransceiver()->internal()->senders().empty();
4768 case cricket::MEDIA_TYPE_VIDEO:
4769 return !GetVideoTransceiver()->internal()->senders().empty();
4770 case cricket::MEDIA_TYPE_DATA:
4771 return false;
4772 }
4773 RTC_NOTREACHED();
4774 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004775}
4776
Steve Anton4171afb2017-11-20 10:20:22 -08004777rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4778PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4779 for (auto transceiver : transceivers_) {
4780 for (auto sender : transceiver->internal()->senders()) {
4781 if (sender->track() == track) {
4782 return sender;
4783 }
4784 }
4785 }
4786 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004787}
4788
Steve Anton4171afb2017-11-20 10:20:22 -08004789rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4790PeerConnection::FindSenderById(const std::string& sender_id) const {
4791 for (auto transceiver : transceivers_) {
4792 for (auto sender : transceiver->internal()->senders()) {
4793 if (sender->id() == sender_id) {
4794 return sender;
4795 }
4796 }
4797 }
4798 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004799}
4800
Steve Anton4171afb2017-11-20 10:20:22 -08004801rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4802PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4803 for (auto transceiver : transceivers_) {
4804 for (auto receiver : transceiver->internal()->receivers()) {
4805 if (receiver->id() == receiver_id) {
4806 return receiver;
4807 }
4808 }
4809 }
4810 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004811}
4812
Steve Anton4171afb2017-11-20 10:20:22 -08004813std::vector<PeerConnection::RtpSenderInfo>*
4814PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4815 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4816 media_type == cricket::MEDIA_TYPE_VIDEO);
4817 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4818 ? &remote_audio_sender_infos_
4819 : &remote_video_sender_infos_;
4820}
4821
4822std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004823 cricket::MediaType media_type) {
4824 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4825 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004826 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4827 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004828}
4829
Steve Anton4171afb2017-11-20 10:20:22 -08004830const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4831 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004832 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004833 const std::string sender_id) const {
4834 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004835 if (sender_info.stream_id == stream_id &&
4836 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004837 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004838 }
4839 }
4840 return nullptr;
4841}
4842
4843DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4844 for (const auto& channel : sctp_data_channels_) {
4845 if (channel->id() == sid) {
4846 return channel;
4847 }
4848 }
4849 return nullptr;
4850}
4851
deadbeef91dd5672016-05-18 16:55:30 -07004852bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004853 const cricket::ServerAddresses& stun_servers,
4854 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004855 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004856 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004857 // To handle both internal and externally created port allocator, we will
4858 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004859 port_allocator_flags_ = port_allocator_->flags();
4860 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4861 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4862 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004863 // If the disable-IPv6 flag was specified, we'll not override it
4864 // by experiment.
4865 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004866 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004867 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4868 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004869 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004870 }
4871
zhihuangb09b3f92017-03-07 14:40:51 -08004872 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004873 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004874 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004875 }
4876
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004877 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004878 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004879 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004880 }
4881
honghaiz60347052016-05-31 18:29:12 -07004882 if (configuration.candidate_network_policy ==
4883 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004884 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004885 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004886 }
4887
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004888 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004889 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004890 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4891 }
4892
Qingsi Wanga2d60672018-04-11 16:57:45 -07004893 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004894 // No step delay is used while allocating ports.
4895 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4896 port_allocator_->set_candidate_filter(
4897 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004898 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004899
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004900 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004901 for (auto& turn_server : turn_servers_copy) {
4902 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004903 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004904 // Call this last since it may create pooled allocator sessions using the
4905 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004906 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004907 stun_servers, std::move(turn_servers_copy),
4908 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4909 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004910 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004911 return true;
4912}
4913
deadbeef91dd5672016-05-18 16:55:30 -07004914bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004915 const cricket::ServerAddresses& stun_servers,
4916 const std::vector<cricket::RelayServerConfig>& turn_servers,
4917 IceTransportsType type,
4918 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004919 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004920 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004921 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004922 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004923 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004924 // According to JSEP, after setLocalDescription, changing the candidate pool
4925 // size is not allowed, and changing the set of ICE servers will not result
4926 // in new candidates being gathered.
4927 if (local_description()) {
4928 port_allocator_->FreezeCandidatePool();
4929 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004930 // Add the custom tls turn servers if they exist.
4931 auto turn_servers_copy = turn_servers;
4932 for (auto& turn_server : turn_servers_copy) {
4933 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4934 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004935 // Call this last since it may create pooled allocator sessions using the
4936 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004937 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004938 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4939 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004940}
4941
Steve Antonba818672017-11-06 10:21:57 -08004942cricket::ChannelManager* PeerConnection::channel_manager() const {
4943 return factory_->channel_manager();
4944}
4945
Elad Alon99c3fe52017-10-13 16:29:40 +02004946bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004947 std::unique_ptr<RtcEventLogOutput> output,
4948 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004949 if (!event_log_) {
4950 return false;
4951 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004952 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004953}
4954
4955void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004956 if (event_log_) {
4957 event_log_->StopLogging();
4958 }
ivoc14d5dbe2016-07-04 07:06:55 -07004959}
nisseeaabdf62017-05-05 02:23:02 -07004960
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004961cricket::ChannelInterface* PeerConnection::GetChannel(
Steve Anton75737c02017-11-06 10:37:17 -08004962 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004963 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08004964 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antondcc3c022017-12-22 16:02:54 -08004965 if (channel && channel->content_name() == content_name) {
4966 return channel;
4967 }
Steve Anton75737c02017-11-06 10:37:17 -08004968 }
4969 if (rtp_data_channel() &&
4970 rtp_data_channel()->content_name() == content_name) {
4971 return rtp_data_channel();
4972 }
4973 return nullptr;
4974}
4975
4976bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004977 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004978 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004979 RTC_LOG(LS_INFO)
4980 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004981 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004982 return false;
4983 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004984 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004985 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004986 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004987 return false;
4988 }
4989
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004990 absl::optional<rtc::SSLRole> dtls_role;
4991 if (sctp_mid_) {
4992 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4993 } else if (is_caller_) {
4994 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
4995 }
Zhi Huange830e682018-03-30 10:48:35 -07004996 if (dtls_role) {
4997 *role = *dtls_role;
4998 return true;
4999 }
5000 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005001}
5002
5003bool PeerConnection::GetSslRole(const std::string& content_name,
5004 rtc::SSLRole* role) {
5005 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005006 RTC_LOG(LS_INFO)
5007 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005008 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005009 return false;
5010 }
5011
Zhi Huange830e682018-03-30 10:48:35 -07005012 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5013 if (dtls_role) {
5014 *role = *dtls_role;
5015 return true;
5016 }
5017 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005018}
5019
Steve Antonf8470812017-12-04 10:46:21 -08005020void PeerConnection::SetSessionError(SessionError error,
5021 const std::string& error_desc) {
5022 RTC_DCHECK_RUN_ON(signaling_thread());
5023 if (error != session_error_) {
5024 session_error_ = error;
5025 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005026 }
5027}
5028
Zhi Huange830e682018-03-30 10:48:35 -07005029RTCError PeerConnection::UpdateSessionState(
5030 SdpType type,
5031 cricket::ContentSource source,
5032 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005033 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005034
5035 // If there's already a pending error then no state transition should happen.
5036 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005037 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005038
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005039 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005040 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005041 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005042 }
5043
5044 // Update the signaling state according to the specified state machine (see
5045 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005046 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005047 ChangeSignalingState(source == cricket::CS_LOCAL
5048 ? PeerConnectionInterface::kHaveLocalOffer
5049 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005050 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005051 ChangeSignalingState(source == cricket::CS_LOCAL
5052 ? PeerConnectionInterface::kHaveLocalPrAnswer
5053 : PeerConnectionInterface::kHaveRemotePrAnswer);
5054 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005055 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005056 ChangeSignalingState(PeerConnectionInterface::kStable);
5057 }
5058
5059 // Update internal objects according to the session description's media
5060 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005061 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005062 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005063 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005064 }
5065
Steve Anton8a006912017-12-04 15:25:56 -08005066 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005067}
5068
Steve Anton8a006912017-12-04 15:25:56 -08005069RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005070 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005071 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005072 const SessionDescriptionInterface* sdesc =
5073 (source == cricket::CS_LOCAL ? local_description()
5074 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005075 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005076
5077 // Push down the new SDP media section for each audio/video transceiver.
5078 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005079 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005080 FindMediaSectionForTransceiver(transceiver, sdesc);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005081 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005082 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005083 continue;
5084 }
5085 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005086 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005087 if (!content_desc) {
5088 continue;
5089 }
5090 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005091 bool success = (source == cricket::CS_LOCAL)
5092 ? channel->SetLocalContent(content_desc, type, &error)
5093 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005094 if (!success) {
5095 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5096 }
5097 }
5098
5099 // If using the RtpDataChannel, push down the new SDP section for it too.
5100 if (rtp_data_channel_) {
5101 const ContentInfo* data_content =
5102 cricket::GetFirstDataContent(sdesc->description());
5103 if (data_content && !data_content->rejected) {
5104 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005105 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005106 if (data_desc) {
5107 std::string error;
5108 bool success =
5109 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005110 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005111 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005112 if (!success) {
5113 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5114 std::move(error));
5115 }
Steve Anton75737c02017-11-06 10:37:17 -08005116 }
5117 }
5118 }
Steve Antoned10bd92017-12-05 10:52:59 -08005119
Steve Anton75737c02017-11-06 10:37:17 -08005120 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5121 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5122 if (sctp_transport_ && local_description() && remote_description() &&
5123 cricket::GetFirstDataContent(local_description()->description()) &&
5124 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005125 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005126 RTC_FROM_HERE,
5127 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005128 if (!success) {
5129 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5130 "Failed to push down SCTP parameters.");
5131 }
Steve Anton75737c02017-11-06 10:37:17 -08005132 }
Steve Antoned10bd92017-12-05 10:52:59 -08005133
Steve Anton8a006912017-12-04 15:25:56 -08005134 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005135}
5136
5137bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5138 RTC_DCHECK(network_thread()->IsCurrent());
5139 RTC_DCHECK(local_description());
5140 RTC_DCHECK(remote_description());
5141 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5142 // When we support "max-message-size", that would also be pushed down here.
5143 return sctp_transport_->Start(
5144 GetSctpPort(local_description()->description()),
5145 GetSctpPort(remote_description()->description()));
5146}
5147
Steve Anton8a006912017-12-04 15:25:56 -08005148RTCError PeerConnection::PushdownTransportDescription(
5149 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005150 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005151 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005152
Zhi Huange830e682018-03-30 10:48:35 -07005153 if (source == cricket::CS_LOCAL) {
5154 const SessionDescriptionInterface* sdesc = local_description();
5155 RTC_DCHECK(sdesc);
5156 return transport_controller_->SetLocalDescription(type,
5157 sdesc->description());
5158 } else {
5159 const SessionDescriptionInterface* sdesc = remote_description();
5160 RTC_DCHECK(sdesc);
5161 return transport_controller_->SetRemoteDescription(type,
5162 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005163 }
Steve Anton75737c02017-11-06 10:37:17 -08005164}
5165
5166bool PeerConnection::GetTransportDescription(
5167 const SessionDescription* description,
5168 const std::string& content_name,
5169 cricket::TransportDescription* tdesc) {
5170 if (!description || !tdesc) {
5171 return false;
5172 }
5173 const TransportInfo* transport_info =
5174 description->GetTransportInfoByName(content_name);
5175 if (!transport_info) {
5176 return false;
5177 }
5178 *tdesc = transport_info->description;
5179 return true;
5180}
5181
Steve Anton75737c02017-11-06 10:37:17 -08005182cricket::IceConfig PeerConnection::ParseIceConfig(
5183 const PeerConnectionInterface::RTCConfiguration& config) const {
5184 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005185 switch (config.continual_gathering_policy) {
5186 case PeerConnectionInterface::GATHER_ONCE:
5187 gathering_policy = cricket::GATHER_ONCE;
5188 break;
5189 case PeerConnectionInterface::GATHER_CONTINUALLY:
5190 gathering_policy = cricket::GATHER_CONTINUALLY;
5191 break;
5192 default:
5193 RTC_NOTREACHED();
5194 gathering_policy = cricket::GATHER_ONCE;
5195 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005196
Steve Anton75737c02017-11-06 10:37:17 -08005197 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005198 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5199 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005200 ice_config.prioritize_most_likely_candidate_pairs =
5201 config.prioritize_most_likely_ice_candidate_pairs;
5202 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005203 RTCConfigurationToIceConfigOptionalInt(
5204 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005205 ice_config.continual_gathering_policy = gathering_policy;
5206 ice_config.presume_writable_when_fully_relayed =
5207 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005208 ice_config.ice_check_interval_strong_connectivity =
5209 config.ice_check_interval_strong_connectivity;
5210 ice_config.ice_check_interval_weak_connectivity =
5211 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005212 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005213 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005214 ice_config.regather_all_networks_interval_range =
5215 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005216 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005217 return ice_config;
5218}
5219
Steve Anton75737c02017-11-06 10:37:17 -08005220bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5221 std::string* track_id) {
5222 if (!local_description()) {
5223 return false;
5224 }
5225 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5226 track_id);
5227}
5228
5229bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5230 std::string* track_id) {
5231 if (!remote_description()) {
5232 return false;
5233 }
5234 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5235 track_id);
5236}
5237
5238bool PeerConnection::SendData(const cricket::SendDataParams& params,
5239 const rtc::CopyOnWriteBuffer& payload,
5240 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005241 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5242 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5243 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005244 return false;
5245 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005246 if (media_transport_) {
5247 SendDataParams send_params;
5248 send_params.type = ToWebrtcDataMessageType(params.type);
5249 send_params.ordered = params.ordered;
5250 if (params.max_rtx_count >= 0) {
5251 send_params.max_rtx_count = params.max_rtx_count;
5252 } else if (params.max_rtx_ms >= 0) {
5253 send_params.max_rtx_ms = params.max_rtx_ms;
5254 }
5255 return media_transport_->SendData(params.sid, send_params, payload).ok();
5256 }
Steve Anton75737c02017-11-06 10:37:17 -08005257 return rtp_data_channel_
5258 ? rtp_data_channel_->SendData(params, payload, result)
5259 : network_thread()->Invoke<bool>(
5260 RTC_FROM_HERE,
5261 Bind(&cricket::SctpTransportInternal::SendData,
5262 sctp_transport_.get(), params, payload, result));
5263}
5264
5265bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005266 RTC_DCHECK_RUN_ON(signaling_thread());
5267 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005268 // Don't log an error here, because DataChannels are expected to call
5269 // ConnectDataChannel in this state. It's the only way to initially tell
5270 // whether or not the underlying transport is ready.
5271 return false;
5272 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005273 if (media_transport_) {
5274 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5275 &DataChannel::OnChannelReady);
5276 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5277 &DataChannel::OnDataReceived);
5278 SignalMediaTransportChannelClosing_s.connect(
5279 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5280 SignalMediaTransportChannelClosed_s.connect(
5281 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5282 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005283 rtp_data_channel_->SignalReadyToSendData.connect(
5284 webrtc_data_channel, &DataChannel::OnChannelReady);
5285 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5286 &DataChannel::OnDataReceived);
5287 } else {
5288 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5289 &DataChannel::OnChannelReady);
5290 SignalSctpDataReceived.connect(webrtc_data_channel,
5291 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005292 SignalSctpClosingProcedureStartedRemotely.connect(
5293 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5294 SignalSctpClosingProcedureComplete.connect(
5295 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005296 }
5297 return true;
5298}
5299
5300void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005301 RTC_DCHECK_RUN_ON(signaling_thread());
5302 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005303 RTC_LOG(LS_ERROR)
5304 << "DisconnectDataChannel called when rtp_data_channel_ and "
5305 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005306 return;
5307 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005308 if (media_transport_) {
5309 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5310 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5311 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5312 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5313 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005314 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5315 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5316 } else {
5317 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5318 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005319 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5320 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005321 }
5322}
5323
5324void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005325 if (media_transport_) {
5326 // No-op. Media transport does not need to add streams.
5327 return;
5328 }
Steve Anton75737c02017-11-06 10:37:17 -08005329 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005330 RTC_LOG(LS_ERROR)
5331 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005332 return;
5333 }
5334 network_thread()->Invoke<void>(
5335 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5336 sctp_transport_.get(), sid));
5337}
5338
5339void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005340 if (media_transport_) {
5341 media_transport_->CloseChannel(sid);
5342 return;
5343 }
Steve Anton75737c02017-11-06 10:37:17 -08005344 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005345 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005346 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005347 return;
5348 }
5349 network_thread()->Invoke<void>(
5350 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5351 sctp_transport_.get(), sid));
5352}
5353
5354bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005355 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005356 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005357 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005358 sctp_ready_to_send_data_;
5359}
5360
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005361void PeerConnection::OnDataReceived(int channel_id,
5362 DataMessageType type,
5363 const rtc::CopyOnWriteBuffer& buffer) {
5364 cricket::ReceiveDataParams params;
5365 params.sid = channel_id;
5366 params.type = ToCricketDataMessageType(type);
5367 media_transport_invoker_->AsyncInvoke<void>(
5368 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5369 RTC_DCHECK_RUN_ON(signaling_thread());
5370 if (!HandleOpenMessage_s(params, buffer)) {
5371 SignalMediaTransportReceivedData_s(params, buffer);
5372 }
5373 });
5374}
5375
5376void PeerConnection::OnChannelClosing(int channel_id) {
5377 media_transport_invoker_->AsyncInvoke<void>(
5378 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5379 RTC_DCHECK_RUN_ON(signaling_thread());
5380 SignalMediaTransportChannelClosing_s(channel_id);
5381 });
5382}
5383
5384void PeerConnection::OnChannelClosed(int channel_id) {
5385 media_transport_invoker_->AsyncInvoke<void>(
5386 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5387 RTC_DCHECK_RUN_ON(signaling_thread());
5388 SignalMediaTransportChannelClosed_s(channel_id);
5389 });
5390}
5391
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005392absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005393 if (sctp_mid_ && transport_controller_) {
5394 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5395 if (dtls_transport) {
5396 return dtls_transport->transport_name();
5397 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005398 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005399 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005400 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005401}
5402
Qingsi Wang72a43a12018-02-20 16:03:18 -08005403cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5404 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005405 network_thread()->Invoke<void>(
5406 RTC_FROM_HERE,
5407 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5408 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005409 return candidate_states_list;
5410}
5411
Steve Anton5dfde182018-02-06 10:34:40 -08005412std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5413 const {
5414 std::map<std::string, std::string> transport_names_by_mid;
5415 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005416 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton5dfde182018-02-06 10:34:40 -08005417 if (channel) {
5418 transport_names_by_mid[channel->content_name()] =
5419 channel->transport_name();
5420 }
Steve Anton75737c02017-11-06 10:37:17 -08005421 }
Steve Anton5dfde182018-02-06 10:34:40 -08005422 if (rtp_data_channel_) {
5423 transport_names_by_mid[rtp_data_channel_->content_name()] =
5424 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005425 }
5426 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005427 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005428 RTC_DCHECK(transport_name);
5429 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005430 }
Steve Anton5dfde182018-02-06 10:34:40 -08005431 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005432}
5433
Steve Anton5dfde182018-02-06 10:34:40 -08005434std::map<std::string, cricket::TransportStats>
5435PeerConnection::GetTransportStatsByNames(
5436 const std::set<std::string>& transport_names) {
5437 if (!network_thread()->IsCurrent()) {
5438 return network_thread()
5439 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5440 RTC_FROM_HERE,
5441 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005442 }
Steve Anton5dfde182018-02-06 10:34:40 -08005443 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5444 for (const std::string& transport_name : transport_names) {
5445 cricket::TransportStats transport_stats;
5446 bool success =
5447 transport_controller_->GetStats(transport_name, &transport_stats);
5448 if (success) {
5449 transport_stats_by_name[transport_name] = std::move(transport_stats);
5450 } else {
5451 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5452 << transport_name;
5453 }
5454 }
5455 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005456}
5457
5458bool PeerConnection::GetLocalCertificate(
5459 const std::string& transport_name,
5460 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005461 if (!certificate) {
5462 return false;
5463 }
5464 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5465 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005466}
5467
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005468std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005469 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005470 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005471}
5472
5473cricket::DataChannelType PeerConnection::data_channel_type() const {
5474 return data_channel_type_;
5475}
5476
5477bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5478 return pending_ice_restarts_.find(content_name) !=
5479 pending_ice_restarts_.end();
5480}
5481
Steve Anton75737c02017-11-06 10:37:17 -08005482bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5483 return transport_controller_->NeedsIceRestart(content_name);
5484}
5485
5486void PeerConnection::OnCertificateReady(
5487 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5488 transport_controller_->SetLocalCertificate(certificate);
5489}
5490
5491void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005492 SetSessionError(SessionError::kTransport,
5493 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005494}
5495
Steve Anton75737c02017-11-06 10:37:17 -08005496void PeerConnection::OnTransportControllerCandidatesGathered(
5497 const std::string& transport_name,
5498 const cricket::Candidates& candidates) {
5499 RTC_DCHECK(signaling_thread()->IsCurrent());
5500 int sdp_mline_index;
5501 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005502 RTC_LOG(LS_ERROR)
5503 << "OnTransportControllerCandidatesGathered: content name "
5504 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005505 return;
5506 }
5507
5508 for (cricket::Candidates::const_iterator citer = candidates.begin();
5509 citer != candidates.end(); ++citer) {
5510 // Use transport_name as the candidate media id.
5511 std::unique_ptr<JsepIceCandidate> candidate(
5512 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5513 if (local_description()) {
5514 mutable_local_description()->AddCandidate(candidate.get());
5515 }
5516 OnIceCandidate(std::move(candidate));
5517 }
5518}
5519
5520void PeerConnection::OnTransportControllerCandidatesRemoved(
5521 const std::vector<cricket::Candidate>& candidates) {
5522 RTC_DCHECK(signaling_thread()->IsCurrent());
5523 // Sanity check.
5524 for (const cricket::Candidate& candidate : candidates) {
5525 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005526 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005527 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005528 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005529 return;
5530 }
5531 }
5532
5533 if (local_description()) {
5534 mutable_local_description()->RemoveCandidates(candidates);
5535 }
5536 OnIceCandidatesRemoved(candidates);
5537}
5538
5539void PeerConnection::OnTransportControllerDtlsHandshakeError(
5540 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005541 RTC_HISTOGRAM_ENUMERATION(
5542 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5543 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005544}
5545
Steve Antoned10bd92017-12-05 10:52:59 -08005546void PeerConnection::EnableSending() {
5547 for (auto transceiver : transceivers_) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08005548 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Antoned10bd92017-12-05 10:52:59 -08005549 if (channel && !channel->enabled()) {
5550 channel->Enable(true);
5551 }
Steve Anton75737c02017-11-06 10:37:17 -08005552 }
5553
Steve Anton4171afb2017-11-20 10:20:22 -08005554 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005555 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005556 }
Steve Anton75737c02017-11-06 10:37:17 -08005557}
5558
5559// Returns the media index for a local ice candidate given the content name.
5560bool PeerConnection::GetLocalCandidateMediaIndex(
5561 const std::string& content_name,
5562 int* sdp_mline_index) {
5563 if (!local_description() || !sdp_mline_index) {
5564 return false;
5565 }
5566
5567 bool content_found = false;
5568 const ContentInfos& contents = local_description()->description()->contents();
5569 for (size_t index = 0; index < contents.size(); ++index) {
5570 if (contents[index].name == content_name) {
5571 *sdp_mline_index = static_cast<int>(index);
5572 content_found = true;
5573 break;
5574 }
5575 }
5576 return content_found;
5577}
5578
5579bool PeerConnection::UseCandidatesInSessionDescription(
5580 const SessionDescriptionInterface* remote_desc) {
5581 if (!remote_desc) {
5582 return true;
5583 }
5584 bool ret = true;
5585
5586 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5587 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5588 for (size_t n = 0; n < candidates->count(); ++n) {
5589 const IceCandidateInterface* candidate = candidates->at(n);
5590 bool valid = false;
5591 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5592 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005593 RTC_LOG(LS_INFO)
5594 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005595 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005596 }
5597 continue;
5598 }
5599 ret = UseCandidate(candidate);
5600 if (!ret) {
5601 break;
5602 }
5603 }
5604 }
5605 return ret;
5606}
5607
5608bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5609 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5610 size_t remote_content_size =
5611 remote_description()->description()->contents().size();
5612 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005613 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005614 return false;
5615 }
5616
5617 cricket::ContentInfo content =
5618 remote_description()->description()->contents()[mediacontent_index];
5619 std::vector<cricket::Candidate> candidates;
5620 candidates.push_back(candidate->candidate());
5621 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005622 RTCError error =
5623 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005624 if (error.ok()) {
5625 // Candidates successfully submitted for checking.
5626 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5627 ice_connection_state_ ==
5628 PeerConnectionInterface::kIceConnectionDisconnected) {
5629 // If state is New, then the session has just gotten its first remote ICE
5630 // candidates, so go to Checking.
5631 // If state is Disconnected, the session is re-using old candidates or
5632 // receiving additional ones, so go to Checking.
5633 // If state is Connected, stay Connected.
5634 // TODO(bemasc): If state is Connected, and the new candidates are for a
5635 // newly added transport, then the state actually _should_ move to
5636 // checking. Add a way to distinguish that case.
5637 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5638 }
5639 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005640 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005641 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005642 }
5643 return true;
5644}
5645
5646void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005647 // Destroy video channel first since it may have a pointer to the
5648 // voice channel.
5649 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005650 if (!video_info || video_info->rejected) {
5651 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005652 }
5653
Steve Anton6fec8802017-12-04 10:37:29 -08005654 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5655 if (!audio_info || audio_info->rejected) {
5656 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005657 }
5658
5659 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5660 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005661 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005662 }
5663}
5664
Steve Antondcc3c022017-12-22 16:02:54 -08005665RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5666 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005667 const cricket::ContentGroup* bundle_group = nullptr;
5668 if (configuration_.bundle_policy ==
5669 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005670 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005671 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005672 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5673 "max-bundle configured but session description "
5674 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005675 }
5676 }
Steve Antondcc3c022017-12-22 16:02:54 -08005677 return std::move(bundle_group);
5678}
5679
5680RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005681 // Creating the media channels. Transports should already have been created
5682 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005683 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005684 if (voice && !voice->rejected &&
5685 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005686 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005687 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005688 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5689 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005690 }
5691 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5692 }
5693
Steve Antondcc3c022017-12-22 16:02:54 -08005694 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005695 if (video && !video->rejected &&
5696 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005697 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005698 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005699 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5700 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005702 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005703 }
5704
Steve Antondcc3c022017-12-22 16:02:54 -08005705 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005706 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005707 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005708 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005709 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5710 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005711 }
5712 }
5713
Steve Anton8a006912017-12-04 15:25:56 -08005714 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005715}
5716
Steve Anton4171afb2017-11-20 10:20:22 -08005717// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005718cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005719 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005720 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005721 MediaTransportInterface* media_transport = nullptr;
5722 if (configuration_.use_media_transport) {
5723 media_transport = GetMediaTransport(mid);
5724 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005725
Steve Anton75737c02017-11-06 10:37:17 -08005726 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005727 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005728 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5729 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005730 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005731 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005732 }
Steve Anton75737c02017-11-06 10:37:17 -08005733 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5734 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005735 voice_channel->SignalSentPacket.connect(this,
5736 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005737 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005738
Steve Antoneda6ccd2017-12-04 10:21:55 -08005739 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005740}
5741
Steve Anton4171afb2017-11-20 10:20:22 -08005742// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005743cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005744 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005745 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5746
5747 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005748 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005749 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005750 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5751 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005752 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005753 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005754 }
Steve Anton75737c02017-11-06 10:37:17 -08005755 video_channel->SignalDtlsSrtpSetupFailure.connect(
5756 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005757 video_channel->SignalSentPacket.connect(this,
5758 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005759 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005760
Steve Antoneda6ccd2017-12-04 10:21:55 -08005761 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005762}
5763
Zhi Huange830e682018-03-30 10:48:35 -07005764bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005765 switch (data_channel_type_) {
5766 case cricket::DCT_MEDIA_TRANSPORT:
5767 if (network_thread()->Invoke<bool>(
5768 RTC_FROM_HERE,
5769 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5770 this, mid))) {
5771 for (const auto& channel : sctp_data_channels_) {
5772 channel->OnTransportChannelCreated();
5773 }
5774 return true;
5775 }
Steve Anton75737c02017-11-06 10:37:17 -08005776 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005777 case cricket::DCT_SCTP:
5778 if (!sctp_factory_) {
5779 RTC_LOG(LS_ERROR)
5780 << "Trying to create SCTP transport, but didn't compile with "
5781 "SCTP support (HAVE_SCTP)";
5782 return false;
5783 }
5784 if (!network_thread()->Invoke<bool>(
5785 RTC_FROM_HERE,
5786 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5787 return false;
5788 }
5789 for (const auto& channel : sctp_data_channels_) {
5790 channel->OnTransportChannelCreated();
5791 }
5792 return true;
5793 case cricket::DCT_RTP:
5794 default:
5795 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5796 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5797 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5798 SrtpRequired(), GetCryptoOptions());
5799 if (!rtp_data_channel_) {
5800 return false;
5801 }
5802 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5803 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5804 rtp_data_channel_->SignalSentPacket.connect(
5805 this, &PeerConnection::OnSentPacket_w);
5806 rtp_data_channel_->SetRtpTransport(rtp_transport);
5807 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005808 }
5809
Steve Anton75737c02017-11-06 10:37:17 -08005810 return true;
5811}
5812
5813Call::Stats PeerConnection::GetCallStats() {
5814 if (!worker_thread()->IsCurrent()) {
5815 return worker_thread()->Invoke<Call::Stats>(
5816 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5817 }
5818 if (call_) {
5819 return call_->GetStats();
5820 } else {
5821 return Call::Stats();
5822 }
5823}
5824
Zhi Huange830e682018-03-30 10:48:35 -07005825bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005826 RTC_DCHECK(network_thread()->IsCurrent());
5827 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005828 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005829 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005830 RTC_DCHECK(dtls_transport);
5831 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005832 RTC_DCHECK(sctp_transport_);
5833 sctp_invoker_.reset(new rtc::AsyncInvoker());
5834 sctp_transport_->SignalReadyToSendData.connect(
5835 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5836 sctp_transport_->SignalDataReceived.connect(
5837 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005838 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5839 // another thread. Would be nice if there was a helper class similar to
5840 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5841 // code.
5842 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5843 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5844 sctp_transport_->SignalClosingProcedureComplete.connect(
5845 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005846 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005847 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005848 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005849}
5850
5851void PeerConnection::DestroySctpTransport_n() {
5852 RTC_DCHECK(network_thread()->IsCurrent());
5853 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005854 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005855 sctp_invoker_.reset(nullptr);
5856 sctp_ready_to_send_data_ = false;
5857}
5858
5859void PeerConnection::OnSctpTransportReadyToSendData_n() {
5860 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5861 RTC_DCHECK(network_thread()->IsCurrent());
5862 // Note: Cannot use rtc::Bind here because it will grab a reference to
5863 // PeerConnection and potentially cause PeerConnection to live longer than
5864 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5865 // be destroyed before PeerConnection is destroyed, and at that point all
5866 // pending tasks will be cleared.
5867 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5868 OnSctpTransportReadyToSendData_s(true);
5869 });
5870}
5871
5872void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5873 RTC_DCHECK(signaling_thread()->IsCurrent());
5874 sctp_ready_to_send_data_ = ready;
5875 SignalSctpReadyToSendData(ready);
5876}
5877
5878void PeerConnection::OnSctpTransportDataReceived_n(
5879 const cricket::ReceiveDataParams& params,
5880 const rtc::CopyOnWriteBuffer& payload) {
5881 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5882 RTC_DCHECK(network_thread()->IsCurrent());
5883 // Note: Cannot use rtc::Bind here because it will grab a reference to
5884 // PeerConnection and potentially cause PeerConnection to live longer than
5885 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5886 // be destroyed before PeerConnection is destroyed, and at that point all
5887 // pending tasks will be cleared.
5888 sctp_invoker_->AsyncInvoke<void>(
5889 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5890 OnSctpTransportDataReceived_s(params, payload);
5891 });
5892}
5893
5894void PeerConnection::OnSctpTransportDataReceived_s(
5895 const cricket::ReceiveDataParams& params,
5896 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005897 RTC_DCHECK_RUN_ON(signaling_thread());
5898 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005899 SignalSctpDataReceived(params, payload);
5900 }
5901}
5902
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005903void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005904 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5905 RTC_DCHECK(network_thread()->IsCurrent());
5906 sctp_invoker_->AsyncInvoke<void>(
5907 RTC_FROM_HERE, signaling_thread(),
5908 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005909 &SignalSctpClosingProcedureStartedRemotely, sid));
5910}
5911
5912void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5913 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5914 RTC_DCHECK(network_thread()->IsCurrent());
5915 sctp_invoker_->AsyncInvoke<void>(
5916 RTC_FROM_HERE, signaling_thread(),
5917 rtc::Bind(&sigslot::signal1<int>::operator(),
5918 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005919}
5920
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005921bool PeerConnection::SetupMediaTransportForDataChannels_n(
5922 const std::string& mid) {
5923 media_transport_ = transport_controller_->GetMediaTransport(mid);
5924 if (!media_transport_) {
5925 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
5926 return false;
5927 }
5928
5929 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
5930 media_transport_->SetDataSink(this);
5931 media_transport_data_mid_ = mid;
5932 transport_controller_->SignalMediaTransportStateChanged.connect(
5933 this, &PeerConnection::OnMediaTransportStateChanged_n);
5934 // Check the initial state right away, in case transport is already writable.
5935 OnMediaTransportStateChanged_n();
5936 return true;
5937}
5938
5939void PeerConnection::TeardownMediaTransportForDataChannels_n() {
5940 if (!media_transport_) {
5941 return;
5942 }
5943 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
5944 media_transport_data_mid_.reset();
5945 media_transport_->SetDataSink(nullptr);
5946 media_transport_invoker_ = nullptr;
5947 media_transport_ = nullptr;
5948}
5949
5950void PeerConnection::OnMediaTransportStateChanged_n() {
5951 if (!media_transport_data_mid_ ||
5952 transport_controller_->GetMediaTransportState(
5953 *media_transport_data_mid_) != MediaTransportState::kWritable) {
5954 return;
5955 }
5956 media_transport_invoker_->AsyncInvoke<void>(
5957 RTC_FROM_HERE, signaling_thread(), [this] {
5958 RTC_DCHECK_RUN_ON(signaling_thread());
5959 media_transport_ready_to_send_data_ = true;
5960 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
5961 });
5962}
5963
Steve Anton75737c02017-11-06 10:37:17 -08005964// Returns false if bundle is enabled and rtcp_mux is disabled.
5965bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5966 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5967 if (!bundle_enabled)
5968 return true;
5969
5970 const cricket::ContentGroup* bundle_group =
5971 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5972 RTC_DCHECK(bundle_group != NULL);
5973
5974 const cricket::ContentInfos& contents = desc->contents();
5975 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5976 citer != contents.end(); ++citer) {
5977 const cricket::ContentInfo* content = (&*citer);
5978 RTC_DCHECK(content != NULL);
5979 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005980 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005981 if (!HasRtcpMuxEnabled(content))
5982 return false;
5983 }
5984 }
5985 // RTCP-MUX is enabled in all the contents.
5986 return true;
5987}
5988
5989bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005990 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005991}
5992
Steve Anton8a006912017-12-04 15:25:56 -08005993RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005994 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005995 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005996 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005997 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005998 }
5999
6000 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006001 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006002 }
6003
Steve Anton3828c062017-12-06 10:34:51 -08006004 SdpType type = sdesc->GetType();
6005 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6006 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006007 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006008 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006009 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006010 }
6011
6012 // Verify crypto settings.
6013 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006014 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6015 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006016 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006017 if (!crypto_error.ok()) {
6018 return crypto_error;
6019 }
Steve Anton75737c02017-11-06 10:37:17 -08006020 }
6021
6022 // Verify ice-ufrag and ice-pwd.
6023 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006024 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6025 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006026 }
6027
6028 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006029 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6030 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006031 }
6032
6033 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6034 // m-lines that do not rtcp-mux enabled.
6035
6036 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006037 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006038 // With an answer we want to compare the new answer session description with
6039 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006040 const cricket::SessionDescription* offer_desc =
6041 (source == cricket::CS_LOCAL) ? remote_description()->description()
6042 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006043 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6044 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6045 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006046 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6047 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006048 }
6049 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006050 // The re-offers should respect the order of m= sections in current
6051 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006052 // With a re-offer, either the current local or current remote descriptions
6053 // could be the most up to date, so we would like to check against both of
6054 // them if they exist. It could be the case that one of them has a 0 port
6055 // for a media section, but the other does not. This is important to check
6056 // against in the case that we are recycling an m= section.
6057 const cricket::SessionDescription* current_desc = nullptr;
6058 const cricket::SessionDescription* secondary_current_desc = nullptr;
6059 if (local_description()) {
6060 current_desc = local_description()->description();
6061 if (remote_description()) {
6062 secondary_current_desc = remote_description()->description();
6063 }
6064 } else if (remote_description()) {
6065 current_desc = remote_description()->description();
6066 }
Steve Anton75737c02017-11-06 10:37:17 -08006067 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006068 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6069 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6071 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006072 }
6073 }
6074
Steve Antonba42e992018-04-09 14:10:01 -07006075 if (IsUnifiedPlan()) {
6076 // Ensure that each audio and video media section has at most one
6077 // "StreamParams". This will return an error if receiving a session
6078 // description from a "Plan B" endpoint which adds multiple tracks of the
6079 // same type. With Unified Plan, there can only be at most one track per
6080 // media section.
6081 for (const ContentInfo& content : sdesc->description()->contents()) {
6082 const MediaContentDescription& desc = *content.description;
6083 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6084 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6085 desc.streams().size() > 1u) {
6086 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6087 "Media section has more than one track specified "
6088 "with a=ssrc lines which is not supported with "
6089 "Unified Plan.");
6090 }
6091 }
6092 }
6093
Steve Anton8a006912017-12-04 15:25:56 -08006094 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006095}
6096
Steve Anton3828c062017-12-06 10:34:51 -08006097bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006098 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006099 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006100 return (state == PeerConnectionInterface::kStable) ||
6101 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006102 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006103 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006104 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6105 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6106 }
6107}
6108
Steve Anton3828c062017-12-06 10:34:51 -08006109bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006110 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006111 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006112 return (state == PeerConnectionInterface::kStable) ||
6113 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006114 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006115 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006116 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6117 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6118 }
6119}
6120
Steve Antonf8470812017-12-04 10:46:21 -08006121const char* PeerConnection::SessionErrorToString(SessionError error) const {
6122 switch (error) {
6123 case SessionError::kNone:
6124 return "ERROR_NONE";
6125 case SessionError::kContent:
6126 return "ERROR_CONTENT";
6127 case SessionError::kTransport:
6128 return "ERROR_TRANSPORT";
6129 }
6130 RTC_NOTREACHED();
6131 return "";
6132}
6133
Steve Anton75737c02017-11-06 10:37:17 -08006134std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006135 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006136 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6137 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006138 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006139}
6140
Steve Anton8e20f172018-03-06 10:55:04 -08006141void PeerConnection::ReportSdpFormatReceived(
6142 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006143 int num_audio_mlines = 0;
6144 int num_video_mlines = 0;
6145 int num_audio_tracks = 0;
6146 int num_video_tracks = 0;
6147 for (const ContentInfo& content : remote_offer.description()->contents()) {
6148 cricket::MediaType media_type = content.media_description()->type();
6149 int num_tracks = std::max(
6150 1, static_cast<int>(content.media_description()->streams().size()));
6151 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6152 num_audio_mlines += 1;
6153 num_audio_tracks += num_tracks;
6154 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6155 num_video_mlines += 1;
6156 num_video_tracks += num_tracks;
6157 }
6158 }
6159 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6160 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6161 format = kSdpFormatReceivedComplexUnifiedPlan;
6162 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6163 format = kSdpFormatReceivedComplexPlanB;
6164 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6165 format = kSdpFormatReceivedSimple;
6166 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006167 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6168 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006169}
6170
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006171void PeerConnection::NoteUsageEvent(UsageEvent event) {
6172 RTC_DCHECK_RUN_ON(signaling_thread());
6173 usage_event_accumulator_ |= static_cast<int>(event);
6174}
6175
6176void PeerConnection::ReportUsagePattern() const {
6177 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006178 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6179 usage_event_accumulator_,
6180 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006181 const int bad_bits =
6182 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6183 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6184 const int good_bits =
6185 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6186 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6187 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6188 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6189 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006190 // If called after close(), we can't report, because observer may have
6191 // been deallocated, and therefore pointer is null. Write to log instead.
6192 if (observer_) {
6193 Observer()->OnInterestingUsage(usage_event_accumulator_);
6194 } else {
6195 RTC_LOG(LS_INFO) << "Interesting usage signature "
6196 << usage_event_accumulator_
6197 << " observed after observer shutdown";
6198 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006199 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006200}
6201
Steve Anton0ffaaa22018-02-23 10:31:30 -08006202void PeerConnection::ReportNegotiatedSdpSemantics(
6203 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006204 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006205 switch (answer.description()->msid_signaling()) {
6206 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006207 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006208 break;
6209 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006210 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006211 break;
6212 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006213 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006214 break;
6215 case cricket::kMsidSignalingMediaSection |
6216 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006217 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006218 break;
6219 default:
6220 RTC_NOTREACHED();
6221 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006222 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6223 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006224}
6225
Steve Anton75737c02017-11-06 10:37:17 -08006226// We need to check the local/remote description for the Transport instead of
6227// the session, because a new Transport added during renegotiation may have
6228// them unset while the session has them set from the previous negotiation.
6229// Not doing so may trigger the auto generation of transport description and
6230// mess up DTLS identity information, ICE credential, etc.
6231bool PeerConnection::ReadyToUseRemoteCandidate(
6232 const IceCandidateInterface* candidate,
6233 const SessionDescriptionInterface* remote_desc,
6234 bool* valid) {
6235 *valid = true;
6236
6237 const SessionDescriptionInterface* current_remote_desc =
6238 remote_desc ? remote_desc : remote_description();
6239
6240 if (!current_remote_desc) {
6241 return false;
6242 }
6243
6244 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6245 size_t remote_content_size =
6246 current_remote_desc->description()->contents().size();
6247 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006248 RTC_LOG(LS_ERROR)
6249 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6250 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006251
6252 *valid = false;
6253 return false;
6254 }
6255
6256 cricket::ContentInfo content =
6257 current_remote_desc->description()->contents()[mediacontent_index];
6258
6259 const std::string transport_name = GetTransportName(content.name);
6260 if (transport_name.empty()) {
6261 return false;
6262 }
Zhi Huange830e682018-03-30 10:48:35 -07006263 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006264}
6265
6266bool PeerConnection::SrtpRequired() const {
6267 return dtls_enabled_ ||
6268 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6269}
6270
6271void PeerConnection::OnTransportControllerGatheringState(
6272 cricket::IceGatheringState state) {
6273 RTC_DCHECK(signaling_thread()->IsCurrent());
6274 if (state == cricket::kIceGatheringGathering) {
6275 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6276 } else if (state == cricket::kIceGatheringComplete) {
6277 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6278 }
6279}
6280
6281void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006282 std::map<std::string, std::set<cricket::MediaType>>
6283 media_types_by_transport_name;
6284 for (auto transceiver : transceivers_) {
6285 if (transceiver->internal()->channel()) {
6286 const std::string& transport_name =
6287 transceiver->internal()->channel()->transport_name();
6288 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006289 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006290 }
Steve Anton75737c02017-11-06 10:37:17 -08006291 }
6292 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006293 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6294 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006295 }
Zhi Huange830e682018-03-30 10:48:35 -07006296
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006297 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006298 if (transport_name) {
6299 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006300 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006301 }
Zhi Huange830e682018-03-30 10:48:35 -07006302
Steve Antonc7b964c2018-02-01 14:39:45 -08006303 for (const auto& entry : media_types_by_transport_name) {
6304 const std::string& transport_name = entry.first;
6305 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006306 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006307 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006308 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006309 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006310 }
6311 }
6312}
6313// Walk through the ConnectionInfos to gather best connection usage
6314// for IPv4 and IPv6.
6315void PeerConnection::ReportBestConnectionState(
6316 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006317 for (const cricket::TransportChannelStats& channel_stats :
6318 stats.channel_stats) {
6319 for (const cricket::ConnectionInfo& connection_info :
6320 channel_stats.connection_infos) {
6321 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006322 continue;
6323 }
6324
Steve Antonc7b964c2018-02-01 14:39:45 -08006325 const cricket::Candidate& local = connection_info.local_candidate;
6326 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006327
6328 // Increment the counter for IceCandidatePairType.
6329 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6330 (local.type() == RELAY_PORT_TYPE &&
6331 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006332 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6333 GetIceCandidatePairCounter(local, remote),
6334 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006335 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006336 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6337 GetIceCandidatePairCounter(local, remote),
6338 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006339 } else {
6340 RTC_CHECK(0);
6341 }
Steve Anton75737c02017-11-06 10:37:17 -08006342
6343 // Increment the counter for IP type.
6344 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006345 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6346 kBestConnections_IPv4,
6347 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006348 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006349 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6350 kBestConnections_IPv6,
6351 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006352 } else {
6353 RTC_CHECK(0);
6354 }
6355
6356 return;
6357 }
6358 }
6359}
6360
6361void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006362 const cricket::TransportStats& stats,
6363 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006364 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6365 return;
6366 }
6367
6368 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6369 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6370 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6371 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6372 return;
6373 }
6374
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006375 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6376 for (cricket::MediaType media_type : media_types) {
6377 switch (media_type) {
6378 case cricket::MEDIA_TYPE_AUDIO:
6379 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6380 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6381 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6382 break;
6383 case cricket::MEDIA_TYPE_VIDEO:
6384 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6385 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6386 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6387 break;
6388 case cricket::MEDIA_TYPE_DATA:
6389 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6390 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6391 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6392 break;
6393 default:
6394 RTC_NOTREACHED();
6395 continue;
6396 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006397 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006398 }
6399
6400 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6401 for (cricket::MediaType media_type : media_types) {
6402 switch (media_type) {
6403 case cricket::MEDIA_TYPE_AUDIO:
6404 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6405 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6406 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6407 break;
6408 case cricket::MEDIA_TYPE_VIDEO:
6409 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6410 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6411 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6412 break;
6413 case cricket::MEDIA_TYPE_DATA:
6414 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6415 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6416 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6417 break;
6418 default:
6419 RTC_NOTREACHED();
6420 continue;
6421 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006422 }
Steve Anton75737c02017-11-06 10:37:17 -08006423 }
6424}
6425
6426void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6427 RTC_DCHECK(worker_thread()->IsCurrent());
6428 RTC_DCHECK(call_);
6429 call_->OnSentPacket(sent_packet);
6430}
6431
6432const std::string PeerConnection::GetTransportName(
6433 const std::string& content_name) {
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006434 cricket::ChannelInterface* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006435 if (channel) {
6436 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006437 }
Steve Anton6fec8802017-12-04 10:37:29 -08006438 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006439 RTC_DCHECK(sctp_mid_);
6440 if (content_name == *sctp_mid_) {
6441 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006442 }
6443 }
6444 // Return an empty string if failed to retrieve the transport name.
6445 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006446}
6447
Steve Anton6fec8802017-12-04 10:37:29 -08006448void PeerConnection::DestroyTransceiverChannel(
6449 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6450 transceiver) {
6451 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006452
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006453 cricket::ChannelInterface* channel = transceiver->internal()->channel();
Steve Anton6fec8802017-12-04 10:37:29 -08006454 if (channel) {
6455 transceiver->internal()->SetChannel(nullptr);
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006456 DestroyChannelInterface(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006457 }
6458}
6459
6460void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006461 if (rtp_data_channel_) {
6462 OnDataChannelDestroyed();
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006463 DestroyChannelInterface(rtp_data_channel_);
Steve Anton6fec8802017-12-04 10:37:29 -08006464 rtp_data_channel_ = nullptr;
6465 }
6466
6467 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6468 // grab a reference to this PeerConnection. If this is called from the
6469 // PeerConnection destructor, the RefCountedObject vtable will have already
6470 // been destroyed (since it is a subclass of PeerConnection) and using
6471 // rtc::Bind will cause "Pure virtual function called" error to appear.
6472
6473 if (sctp_transport_) {
6474 OnDataChannelDestroyed();
6475 network_thread()->Invoke<void>(RTC_FROM_HERE,
6476 [this] { DestroySctpTransport_n(); });
6477 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006478
6479 if (media_transport_) {
6480 OnDataChannelDestroyed();
6481 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6482 RTC_DCHECK_RUN_ON(network_thread());
6483 TeardownMediaTransportForDataChannels_n();
6484 });
6485 }
Steve Anton6fec8802017-12-04 10:37:29 -08006486}
6487
Amit Hilbuchdd9390c2018-11-13 16:26:05 -08006488void PeerConnection::DestroyChannelInterface(
6489 cricket::ChannelInterface* channel) {
Steve Anton6fec8802017-12-04 10:37:29 -08006490 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006491 switch (channel->media_type()) {
6492 case cricket::MEDIA_TYPE_AUDIO:
6493 channel_manager()->DestroyVoiceChannel(
6494 static_cast<cricket::VoiceChannel*>(channel));
6495 break;
6496 case cricket::MEDIA_TYPE_VIDEO:
6497 channel_manager()->DestroyVideoChannel(
6498 static_cast<cricket::VideoChannel*>(channel));
6499 break;
6500 case cricket::MEDIA_TYPE_DATA:
6501 channel_manager()->DestroyRtpDataChannel(
6502 static_cast<cricket::RtpDataChannel*>(channel));
6503 break;
6504 default:
6505 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6506 break;
6507 }
Zhi Huange830e682018-03-30 10:48:35 -07006508}
Steve Anton6fec8802017-12-04 10:37:29 -08006509
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006510bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006511 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006512 RtpTransportInternal* rtp_transport,
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006513 cricket::DtlsTransportInternal* dtls_transport,
6514 MediaTransportInterface* media_transport) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006515 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006516 auto base_channel = GetChannel(mid);
6517 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006518 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006519 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006520 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006521 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006522 }
Piotr (Peter) Slatalacc8e8bb2018-11-15 08:26:19 -08006523
6524 call_->MediaTransportChange(media_transport);
6525
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006526 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006527}
6528
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006529PeerConnectionObserver* PeerConnection::Observer() const {
6530 // In earlier production code, the pointer was not cleared on close,
6531 // which might have led to undefined behavior if the observer was not
6532 // deallocated, or strange crashes if it was.
6533 // We use CHECK in order to catch such behavior if it exists.
6534 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6535 RTC_CHECK(observer_);
6536 return observer_;
6537}
6538
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006539CryptoOptions PeerConnection::GetCryptoOptions() {
6540 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6541 // after it has been removed.
6542 return configuration_.crypto_options.has_value()
6543 ? *configuration_.crypto_options
6544 : factory_->options().crypto_options;
6545}
6546
Harald Alvestrand89061872018-01-02 14:08:34 +01006547void PeerConnection::ClearStatsCache() {
6548 if (stats_collector_) {
6549 stats_collector_->ClearCachedStatsReport();
6550 }
6551}
6552
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006553void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006554 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6555 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006556}
6557
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006558} // namespace webrtc