blob: f920ddf72c5d00ccf597250149b488e4a39de426 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 10:37:17 -0800342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800389}
390
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100417
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100424 }
425}
426
Harald Alvestrand76829d72018-07-18 23:24:36 +0200427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 10:37:17 -0800432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800443 continue;
444 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800479 }
480 }
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 continue;
494 }
Steve Anton8a006912017-12-04 15:25:56 -0800495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800515 return false;
516 }
517 }
518 return true;
519}
520
521bool GetTrackIdBySsrc(const SessionDescription* session_description,
522 uint32_t ssrc,
523 std::string* track_id) {
524 RTC_DCHECK(track_id != NULL);
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::AudioContentDescription* audio_desc =
527 cricket::GetFirstAudioContentDescription(session_description);
528 if (audio_desc) {
529 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535
Steve Antonb1c1de12017-12-21 15:14:30 -0800536 const cricket::VideoContentDescription* video_desc =
537 cricket::GetFirstVideoContentDescription(session_description);
538 if (video_desc) {
539 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800540 if (found) {
541 *track_id = found->id;
542 return true;
543 }
544 }
545 return false;
546}
547
548// Get the SCTP port out of a SessionDescription.
549// Return -1 if not found.
550int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800551 const cricket::DataContentDescription* data_desc =
552 GetFirstDataContentDescription(session_description);
553 RTC_DCHECK(data_desc);
554 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800555 return -1;
556 }
Steve Anton75737c02017-11-06 10:37:17 -0800557 std::string value;
558 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
559 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800560 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800561 if (!codec.Matches(match_pattern)) {
562 continue;
563 }
564 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
565 return rtc::FromString<int>(value);
566 }
567 }
568 return -1;
569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Steve Anton75737c02017-11-06 10:37:17 -0800634} // namespace
635
Henrik Boström31638672017-11-23 17:48:32 +0100636// Upon completion, posts a task to execute the callback of the
637// SetSessionDescriptionObserver asynchronously on the same thread. At this
638// point, the state of the peer connection might no longer reflect the effects
639// of the SetRemoteDescription operation, as the peer connection could have been
640// modified during the post.
641// TODO(hbos): Remove this class once we remove the version of
642// PeerConnectionInterface::SetRemoteDescription() that takes a
643// SetSessionDescriptionObserver as an argument.
644class PeerConnection::SetRemoteDescriptionObserverAdapter
645 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
646 public:
647 SetRemoteDescriptionObserverAdapter(
648 rtc::scoped_refptr<PeerConnection> pc,
649 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
650 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
651
652 // SetRemoteDescriptionObserverInterface implementation.
653 void OnSetRemoteDescriptionComplete(RTCError error) override {
654 if (error.ok())
655 pc_->PostSetSessionDescriptionSuccess(wrapper_);
656 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100657 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100658 }
659
660 private:
661 rtc::scoped_refptr<PeerConnection> pc_;
662 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
663};
664
deadbeef293e9262017-01-11 12:28:30 -0800665bool PeerConnectionInterface::RTCConfiguration::operator==(
666 const PeerConnectionInterface::RTCConfiguration& o) const {
667 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700668 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800669 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000670 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700671 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800672 BundlePolicy bundle_policy;
673 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700674 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
675 int ice_candidate_pool_size;
676 bool disable_ipv6;
677 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700678 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100679 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700680 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200681 absl::optional<int> screencast_min_bitrate;
682 absl::optional<bool> combined_audio_video_bwe;
683 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800684 TcpCandidatePolicy tcp_candidate_policy;
685 CandidateNetworkPolicy candidate_network_policy;
686 int audio_jitter_buffer_max_packets;
687 bool audio_jitter_buffer_fast_accelerate;
688 int ice_connection_receiving_timeout;
689 int ice_backup_candidate_pair_ping_interval;
690 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800691 bool prioritize_most_likely_ice_candidate_pairs;
692 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800693 bool prune_turn_ports;
694 bool presume_writable_when_fully_relayed;
695 bool enable_ice_renomination;
696 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200697 absl::optional<int> ice_check_interval_strong_connectivity;
698 absl::optional<int> ice_check_interval_weak_connectivity;
699 absl::optional<int> ice_check_min_interval;
700 absl::optional<int> ice_unwritable_timeout;
701 absl::optional<int> ice_unwritable_min_checks;
702 absl::optional<int> stun_candidate_keepalive_interval;
703 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200704 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800705 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200706 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700707 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800708 };
709 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
710 "Did you add something to RTCConfiguration and forget to "
711 "update operator==?");
712 return type == o.type && servers == o.servers &&
713 bundle_policy == o.bundle_policy &&
714 rtcp_mux_policy == o.rtcp_mux_policy &&
715 tcp_candidate_policy == o.tcp_candidate_policy &&
716 candidate_network_policy == o.candidate_network_policy &&
717 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
718 audio_jitter_buffer_fast_accelerate ==
719 o.audio_jitter_buffer_fast_accelerate &&
720 ice_connection_receiving_timeout ==
721 o.ice_connection_receiving_timeout &&
722 ice_backup_candidate_pair_ping_interval ==
723 o.ice_backup_candidate_pair_ping_interval &&
724 continual_gathering_policy == o.continual_gathering_policy &&
725 certificates == o.certificates &&
726 prioritize_most_likely_ice_candidate_pairs ==
727 o.prioritize_most_likely_ice_candidate_pairs &&
728 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800729 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700730 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100731 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800732 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800733 screencast_min_bitrate == o.screencast_min_bitrate &&
734 combined_audio_video_bwe == o.combined_audio_video_bwe &&
735 enable_dtls_srtp == o.enable_dtls_srtp &&
736 ice_candidate_pool_size == o.ice_candidate_pool_size &&
737 prune_turn_ports == o.prune_turn_ports &&
738 presume_writable_when_fully_relayed ==
739 o.presume_writable_when_fully_relayed &&
740 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800741 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800742 ice_check_interval_strong_connectivity ==
743 o.ice_check_interval_strong_connectivity &&
744 ice_check_interval_weak_connectivity ==
745 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700746 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700747 ice_unwritable_timeout == o.ice_unwritable_timeout &&
748 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800749 stun_candidate_keepalive_interval ==
750 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200751 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800752 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800753 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700754 network_preference == o.network_preference &&
755 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800756}
757
758bool PeerConnectionInterface::RTCConfiguration::operator!=(
759 const PeerConnectionInterface::RTCConfiguration& o) const {
760 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800761}
762
zhihuang8f65cdf2016-05-06 18:40:30 -0700763// Generate a RTCP CNAME when a PeerConnection is created.
764std::string GenerateRtcpCname() {
765 std::string cname;
766 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100767 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800768 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700769 }
770 return cname;
771}
772
zhihuang1c378ed2017-08-17 14:10:50 -0700773bool ValidateOfferAnswerOptions(
774 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
775 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
776 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700777}
778
zhihuang1c378ed2017-08-17 14:10:50 -0700779// From |rtc_options|, fill parts of |session_options| shared by all generated
780// m= sections (in other words, nothing that involves a map/array).
781void ExtractSharedMediaSessionOptions(
782 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
783 cricket::MediaSessionOptions* session_options) {
784 session_options->vad_enabled = rtc_options.voice_activity_detection;
785 session_options->bundle_enabled = rtc_options.use_rtp_mux;
786}
zhihuanga77e6bb2017-08-14 18:17:48 -0700787
zhihuang38ede132017-06-15 12:52:32 -0700788PeerConnection::PeerConnection(PeerConnectionFactory* factory,
789 std::unique_ptr<RtcEventLog> event_log,
790 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000791 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700792 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700793 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700794 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700795 remote_streams_(StreamCollection::Create()),
796 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000797
798PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100799 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800800 RTC_DCHECK_RUN_ON(signaling_thread());
801
Steve Anton8af21862017-12-15 11:20:13 -0800802 // Need to stop transceivers before destroying the stats collector because
803 // AudioRtpSender has a reference to the StatsCollector it will update when
804 // stopping.
805 for (auto transceiver : transceivers_) {
806 transceiver->Stop();
807 }
Steve Anton4171afb2017-11-20 10:20:22 -0800808
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700809 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800810 if (stats_collector_) {
811 stats_collector_->WaitForPendingRequest();
812 stats_collector_ = nullptr;
813 }
Steve Anton75737c02017-11-06 10:37:17 -0800814
Steve Anton8af21862017-12-15 11:20:13 -0800815 // Don't destroy BaseChannels until after stats has been cleaned up so that
816 // the last stats request can still read from the channels.
817 DestroyAllChannels();
818
Mirko Bonadei675513b2017-11-09 11:09:25 +0100819 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800820
821 webrtc_session_desc_factory_.reset();
822 sctp_invoker_.reset();
823 sctp_factory_.reset();
824 transport_controller_.reset();
825
deadbeef91dd5672016-05-18 16:55:30 -0700826 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700827 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700828 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700829 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700830 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700831 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800832 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700833 event_log_.reset();
834 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000835}
836
Steve Anton8af21862017-12-15 11:20:13 -0800837void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800838 // Destroy video channels first since they may have a pointer to a voice
839 // channel.
840 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800841 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800842 DestroyTransceiverChannel(transceiver);
843 }
844 }
845 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800846 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800847 DestroyTransceiverChannel(transceiver);
848 }
849 }
850 DestroyDataChannel();
851}
852
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000853bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000854 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700855 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100856 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700857
858 RTCError config_error = ValidateConfiguration(configuration);
859 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100860 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700861 return false;
862 }
863
Benjamin Wrightcab58882018-05-02 15:12:47 -0700864 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100865 RTC_LOG(LS_ERROR)
866 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100867 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800868 return false;
869 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200870
Benjamin Wrightcab58882018-05-02 15:12:47 -0700871 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800872 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100873 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100874 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800875 return false;
876 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700877
Benjamin Wrightcab58882018-05-02 15:12:47 -0700878 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700879 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700880 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700881 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800882
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200883 cricket::ServerAddresses stun_servers;
884 std::vector<cricket::RelayServerConfig> turn_servers;
885
886 RTCErrorType parse_error =
887 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
888 if (parse_error != RTCErrorType::NONE) {
889 return false;
890 }
891
deadbeef91dd5672016-05-18 16:55:30 -0700892 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700893 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700894 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200895 RTC_FROM_HERE,
896 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
897 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000898 return false;
899 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200900 // If initialization was successful, note if STUN or TURN servers
901 // were supplied.
902 if (!stun_servers.empty()) {
903 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
904 }
905 if (!turn_servers.empty()) {
906 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
907 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000908
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700909 // Send information about IPv4/IPv6 status.
910 PeerConnectionAddressFamilyCounter address_family;
911 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
912 address_family = kPeerConnection_IPv6;
913 } else {
914 address_family = kPeerConnection_IPv4;
915 }
916 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
917 kPeerConnectionAddressFamilyCounter_Max);
918
Zhi Huange830e682018-03-30 10:48:35 -0700919 const PeerConnectionFactoryInterface::Options& options = factory_->options();
920
Steve Anton75737c02017-11-06 10:37:17 -0800921 // RFC 3264: The numeric value of the session id and version in the
922 // o line MUST be representable with a "64 bit signed integer".
923 // Due to this constraint session id |session_id_| is max limited to
924 // LLONG_MAX.
925 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700926 JsepTransportController::Config config;
927 config.redetermine_role_on_ice_restart =
928 configuration.redetermine_role_on_ice_restart;
929 config.ssl_max_version = factory_->options().ssl_max_version;
930 config.disable_encryption = options.disable_encryption;
931 config.bundle_policy = configuration.bundle_policy;
932 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
933 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700934 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700935 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700936#if defined(ENABLE_EXTERNAL_AUTH)
937 config.enable_external_auth = true;
938#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700939 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700940 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700941 signaling_thread(), network_thread(), port_allocator_.get(),
942 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700943 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800944 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700945 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800946 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700947 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800948 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700949 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800950 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
951 transport_controller_->SignalDtlsHandshakeError.connect(
952 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
953
954 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700955
deadbeefab9b2d12015-10-14 11:33:11 -0700956 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700957 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958
Steve Antonba818672017-11-06 10:21:57 -0800959 configuration_ = configuration;
960
Steve Anton75737c02017-11-06 10:37:17 -0800961 // Obtain a certificate from RTCConfiguration if any were provided (optional).
962 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
963 if (!configuration.certificates.empty()) {
964 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
965 // just picking the first one. The decision should be made based on the DTLS
966 // handshake. The DTLS negotiations need to know about all certificates.
967 certificate = configuration.certificates[0];
968 }
969
Steve Antond25da372017-11-06 14:50:29 -0800970 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800971
972 if (options.disable_encryption) {
973 dtls_enabled_ = false;
974 } else {
975 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700976 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800977 // |configuration| can override the default |dtls_enabled_| value.
978 if (configuration.enable_dtls_srtp) {
979 dtls_enabled_ = *(configuration.enable_dtls_srtp);
980 }
981 }
982
983 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
984 // It takes precendence over the disable_sctp_data_channels
985 // PeerConnectionFactoryInterface::Options.
986 if (configuration.enable_rtp_data_channel) {
987 data_channel_type_ = cricket::DCT_RTP;
988 } else {
989 // DTLS has to be enabled to use SCTP.
990 if (!options.disable_sctp_data_channels && dtls_enabled_) {
991 data_channel_type_ = cricket::DCT_SCTP;
992 }
993 }
994
995 video_options_.screencast_min_bitrate_kbps =
996 configuration.screencast_min_bitrate;
997 audio_options_.combined_audio_video_bwe =
998 configuration.combined_audio_video_bwe;
999
1000 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001001 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001002
1003 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001004 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001005
1006 // Whether the certificate generator/certificate is null or not determines
1007 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1008 // the right instructions by clearing the variables if needed.
1009 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001010 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001011 certificate = nullptr;
1012 } else if (certificate) {
1013 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001014 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001015 }
1016
1017 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1018 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001019 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001020 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1021 this, &PeerConnection::OnCertificateReady);
1022
1023 if (options.disable_encryption) {
1024 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1025 }
1026
1027 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1028 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001029
Steve Anton4171afb2017-11-20 10:20:22 -08001030 // Add default audio/video transceivers for Plan B SDP.
1031 if (!IsUnifiedPlan()) {
1032 transceivers_.push_back(
1033 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1034 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1035 transceivers_.push_back(
1036 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1037 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1038 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001039 int delay_ms =
1040 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001041 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1042 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001043 return true;
1044}
1045
Steve Anton038834f2017-07-14 15:59:59 -07001046RTCError PeerConnection::ValidateConfiguration(
1047 const RTCConfiguration& config) const {
1048 if (config.ice_regather_interval_range &&
1049 config.continual_gathering_policy == GATHER_ONCE) {
1050 return RTCError(RTCErrorType::INVALID_PARAMETER,
1051 "ice_regather_interval_range specified but continual "
1052 "gathering policy is GATHER_ONCE");
1053 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001054 auto result =
1055 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1056 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001057}
1058
Yves Gerey665174f2018-06-19 15:03:05 +02001059rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001060 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1061 "Plan SdpSemantics. Please use GetSenders "
1062 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001063 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001064}
1065
Yves Gerey665174f2018-06-19 15:03:05 +02001066rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001067 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1068 "Plan SdpSemantics. Please use GetReceivers "
1069 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001070 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001071}
1072
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001073bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001074 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1075 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001076 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001077 if (IsClosed()) {
1078 return false;
1079 }
deadbeefab9b2d12015-10-14 11:33:11 -07001080 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001081 return false;
1082 }
deadbeefab9b2d12015-10-14 11:33:11 -07001083
1084 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001085 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1086 observer->SignalAudioTrackAdded.connect(this,
1087 &PeerConnection::OnAudioTrackAdded);
1088 observer->SignalAudioTrackRemoved.connect(
1089 this, &PeerConnection::OnAudioTrackRemoved);
1090 observer->SignalVideoTrackAdded.connect(this,
1091 &PeerConnection::OnVideoTrackAdded);
1092 observer->SignalVideoTrackRemoved.connect(
1093 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001094 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001095
deadbeefab9b2d12015-10-14 11:33:11 -07001096 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001097 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001098 }
1099 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001100 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001101 }
1102
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001103 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001104 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001105 return true;
1106}
1107
1108void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001109 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1110 "Plan SdpSemantics. Please use RemoveTrack "
1111 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001112 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001113 if (!IsClosed()) {
1114 for (const auto& track : local_stream->GetAudioTracks()) {
1115 RemoveAudioTrack(track.get(), local_stream);
1116 }
1117 for (const auto& track : local_stream->GetVideoTracks()) {
1118 RemoveVideoTrack(track.get(), local_stream);
1119 }
deadbeefab9b2d12015-10-14 11:33:11 -07001120 }
deadbeefab9b2d12015-10-14 11:33:11 -07001121 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001122 stream_observers_.erase(
1123 std::remove_if(
1124 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001125 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001126 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001127 }),
1128 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001129
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001130 if (IsClosed()) {
1131 return;
1132 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001133 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001134}
1135
Steve Anton2d6c76a2018-01-05 17:10:52 -08001136RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001137 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001138 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001139 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001140 if (!track) {
1141 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1142 }
1143 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1144 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1145 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1146 "Track has invalid kind: " + track->kind());
1147 }
Steve Antonf9381f02017-12-14 10:23:57 -08001148 if (IsClosed()) {
1149 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1150 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001151 }
Steve Anton4171afb2017-11-20 10:20:22 -08001152 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001153 LOG_AND_RETURN_ERROR(
1154 RTCErrorType::INVALID_PARAMETER,
1155 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001156 }
Steve Antonf9381f02017-12-14 10:23:57 -08001157 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001158 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1159 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001160 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001161 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001162 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001163 }
1164 return sender_or_error;
1165}
deadbeefe1f9d832016-01-14 15:35:42 -08001166
Steve Antonf9381f02017-12-14 10:23:57 -08001167RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1168PeerConnection::AddTrackPlanB(
1169 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001170 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001171 if (stream_ids.size() > 1u) {
1172 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1173 "AddTrack with more than one stream is not "
1174 "supported with Plan B semantics.");
1175 }
1176 std::vector<std::string> adjusted_stream_ids = stream_ids;
1177 if (adjusted_stream_ids.empty()) {
1178 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1179 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001180 cricket::MediaType media_type =
1181 (track->kind() == MediaStreamTrackInterface::kAudioKind
1182 ? cricket::MEDIA_TYPE_AUDIO
1183 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001184 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001185 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001186 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001187 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001188 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001189 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001190 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001191 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001192 if (sender_info) {
1193 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001194 }
Steve Antonf9381f02017-12-14 10:23:57 -08001195 } else {
1196 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001197 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001198 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001199 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001200 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001201 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001202 if (sender_info) {
1203 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001204 }
deadbeefe1f9d832016-01-14 15:35:42 -08001205 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001206 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001207}
deadbeefe1f9d832016-01-14 15:35:42 -08001208
Steve Antonf9381f02017-12-14 10:23:57 -08001209RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1210PeerConnection::AddTrackUnifiedPlan(
1211 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001212 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001213 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1214 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001215 RTC_LOG(LS_INFO) << "Reusing an existing "
1216 << cricket::MediaTypeToString(transceiver->media_type())
1217 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001218 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001219 transceiver->internal()->set_direction(
1220 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001221 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001222 transceiver->internal()->set_direction(
1223 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001224 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001225 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001226 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001227 } else {
1228 cricket::MediaType media_type =
1229 (track->kind() == MediaStreamTrackInterface::kAudioKind
1230 ? cricket::MEDIA_TYPE_AUDIO
1231 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001232 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1233 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001234 std::string sender_id = track->id();
1235 // Avoid creating a sender with an existing ID by generating a random ID.
1236 // This can happen if this is the second time AddTrack has created a sender
1237 // for this track.
1238 if (FindSenderById(sender_id)) {
1239 sender_id = rtc::CreateRandomUuid();
1240 }
Florent Castelli892acf02018-10-01 22:47:20 +02001241 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001242 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1243 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001244 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001245 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001246 }
Steve Antonf9381f02017-12-14 10:23:57 -08001247 return transceiver->sender();
1248}
1249
1250rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1251PeerConnection::FindFirstTransceiverForAddedTrack(
1252 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1253 RTC_DCHECK(track);
1254 for (auto transceiver : transceivers_) {
1255 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001256 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001257 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001258 !transceiver->internal()->has_ever_been_used_to_send() &&
1259 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001260 return transceiver;
1261 }
1262 }
1263 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001264}
1265
1266bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1267 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001268 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001269}
1270
Steve Anton24db5732018-07-23 10:27:33 -07001271RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001272 rtc::scoped_refptr<RtpSenderInterface> sender) {
1273 if (!sender) {
1274 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1275 }
deadbeefe1f9d832016-01-14 15:35:42 -08001276 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001277 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1278 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001279 }
Steve Antonf9381f02017-12-14 10:23:57 -08001280 if (IsUnifiedPlan()) {
1281 auto transceiver = FindTransceiverBySender(sender);
1282 if (!transceiver || !sender->track()) {
1283 return RTCError::OK();
1284 }
1285 sender->SetTrack(nullptr);
1286 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001287 transceiver->internal()->set_direction(
1288 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001289 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001290 transceiver->internal()->set_direction(
1291 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001292 }
Steve Anton4171afb2017-11-20 10:20:22 -08001293 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001294 bool removed;
1295 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1296 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1297 } else {
1298 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1299 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1300 }
1301 if (!removed) {
1302 LOG_AND_RETURN_ERROR(
1303 RTCErrorType::INVALID_PARAMETER,
1304 "Couldn't find sender " + sender->id() + " to remove.");
1305 }
Steve Anton4171afb2017-11-20 10:20:22 -08001306 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001307 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001308 return RTCError::OK();
1309}
1310
1311rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1312PeerConnection::FindTransceiverBySender(
1313 rtc::scoped_refptr<RtpSenderInterface> sender) {
1314 for (auto transceiver : transceivers_) {
1315 if (transceiver->sender() == sender) {
1316 return transceiver;
1317 }
1318 }
1319 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001320}
1321
Steve Anton9158ef62017-11-27 13:01:52 -08001322RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1323PeerConnection::AddTransceiver(
1324 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1325 return AddTransceiver(track, RtpTransceiverInit());
1326}
1327
1328RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1329PeerConnection::AddTransceiver(
1330 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1331 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001332 RTC_CHECK(IsUnifiedPlan())
1333 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001334 if (!track) {
1335 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1336 }
1337 cricket::MediaType media_type;
1338 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1339 media_type = cricket::MEDIA_TYPE_AUDIO;
1340 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1341 media_type = cricket::MEDIA_TYPE_VIDEO;
1342 } else {
1343 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1344 "Track kind is not audio or video");
1345 }
1346 return AddTransceiver(media_type, track, init);
1347}
1348
1349RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1350PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1351 return AddTransceiver(media_type, RtpTransceiverInit());
1352}
1353
1354RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1355PeerConnection::AddTransceiver(cricket::MediaType media_type,
1356 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001357 RTC_CHECK(IsUnifiedPlan())
1358 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001359 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1360 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1361 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1362 "media type is not audio or video");
1363 }
1364 return AddTransceiver(media_type, nullptr, init);
1365}
1366
1367RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1368PeerConnection::AddTransceiver(
1369 cricket::MediaType media_type,
1370 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001371 const RtpTransceiverInit& init,
1372 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001373 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1374 media_type == cricket::MEDIA_TYPE_VIDEO));
1375 if (track) {
1376 RTC_DCHECK_EQ(media_type,
1377 (track->kind() == MediaStreamTrackInterface::kAudioKind
1378 ? cricket::MEDIA_TYPE_AUDIO
1379 : cricket::MEDIA_TYPE_VIDEO));
1380 }
1381
1382 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001383 if (init.send_encodings.size() > 1) {
1384 LOG_AND_RETURN_ERROR(
1385 RTCErrorType::UNSUPPORTED_PARAMETER,
1386 "Attempted to create an encoder with more than 1 encoding parameter.");
1387 }
1388
1389 for (const auto& encoding : init.send_encodings) {
1390 if (encoding.ssrc.has_value()) {
1391 LOG_AND_RETURN_ERROR(
1392 RTCErrorType::UNSUPPORTED_PARAMETER,
1393 "Attempted to set an unimplemented parameter of RtpParameters.");
1394 }
1395 }
1396
1397 RtpParameters parameters;
1398 parameters.encodings = init.send_encodings;
1399 if (UnimplementedRtpParameterHasValue(parameters)) {
1400 LOG_AND_RETURN_ERROR(
1401 RTCErrorType::UNSUPPORTED_PARAMETER,
1402 "Attempted to set an unimplemented parameter of RtpParameters.");
1403 }
Steve Anton9158ef62017-11-27 13:01:52 -08001404
Steve Anton3d954a62018-04-02 11:27:23 -07001405 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1406 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001407 // Set the sender ID equal to the track ID if the track is specified unless
1408 // that sender ID is already in use.
1409 std::string sender_id =
1410 (track && !FindSenderById(track->id()) ? track->id()
1411 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001412 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1413 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001414 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1415 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1416 transceiver->internal()->set_direction(init.direction);
1417
Steve Anton22da89f2018-01-25 13:58:07 -08001418 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001419 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001420 }
Steve Antonf9381f02017-12-14 10:23:57 -08001421
1422 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1423}
1424
Steve Anton02ee47c2018-01-10 16:26:06 -08001425rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1426PeerConnection::CreateSender(
1427 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001428 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001429 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001430 const std::vector<std::string>& stream_ids,
1431 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001432 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001433 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1434 RTC_DCHECK(!track ||
1435 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1436 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1437 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001438 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001439 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001440 } else {
1441 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1442 RTC_DCHECK(!track ||
1443 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1444 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001445 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001446 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001448 bool set_track_succeeded = sender->SetTrack(track);
1449 RTC_DCHECK(set_track_succeeded);
1450 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001451 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001452 return sender;
1453}
1454
1455rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1456PeerConnection::CreateReceiver(cricket::MediaType media_type,
1457 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001458 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1459 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001460 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001461 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001462 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1463 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001464 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001465 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001466 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001467 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001468 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1469 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001470 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001471 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001472 return receiver;
1473}
1474
1475rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1476PeerConnection::CreateAndAddTransceiver(
1477 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1478 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1479 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001480 // Ensure that the new sender does not have an ID that is already in use by
1481 // another sender.
1482 // Allow receiver IDs to conflict since those come from remote SDP (which
1483 // could be invalid, but should not cause a crash).
1484 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001485 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1486 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001487 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001488 transceiver->internal()->SignalNegotiationNeeded.connect(
1489 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001490 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001491}
1492
Steve Anton52d86772018-02-20 15:48:12 -08001493void PeerConnection::OnNegotiationNeeded() {
1494 RTC_DCHECK_RUN_ON(signaling_thread());
1495 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001496 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001497}
1498
deadbeeffac06552015-11-25 11:26:01 -08001499rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001500 const std::string& kind,
1501 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001502 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1503 "Plan SdpSemantics. Please use AddTransceiver "
1504 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001505 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001506 if (IsClosed()) {
1507 return nullptr;
1508 }
Steve Anton4171afb2017-11-20 10:20:22 -08001509
Seth Hampson5b4f0752018-04-02 16:31:36 -07001510 // Internally we need to have one stream with Plan B semantics, so we
1511 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001512 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001513 if (stream_id.empty()) {
1514 stream_ids.push_back(rtc::CreateRandomUuid());
1515 RTC_LOG(LS_INFO)
1516 << "No stream_id specified for sender. Generated stream ID: "
1517 << stream_ids[0];
1518 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001519 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001520 }
1521
Steve Anton4171afb2017-11-20 10:20:22 -08001522 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001523 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001524 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001525 auto* audio_sender = new AudioRtpSender(
1526 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001527 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001528 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001529 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001530 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001531 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001532 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001533 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001534 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001535 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001536 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001537 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001538 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001539 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001540 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001541 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001542 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001543
deadbeefe1f9d832016-01-14 15:35:42 -08001544 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001545}
1546
deadbeef70ab1a12015-09-28 16:53:55 -07001547std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1548 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001549 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001550 for (auto sender : GetSendersInternal()) {
1551 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001552 }
1553 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001554}
1555
Steve Anton4171afb2017-11-20 10:20:22 -08001556std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1557PeerConnection::GetSendersInternal() const {
1558 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1559 all_senders;
1560 for (auto transceiver : transceivers_) {
1561 auto senders = transceiver->internal()->senders();
1562 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1563 }
1564 return all_senders;
1565}
1566
deadbeef70ab1a12015-09-28 16:53:55 -07001567std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1568PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001569 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001570 for (const auto& receiver : GetReceiversInternal()) {
1571 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001572 }
1573 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001574}
1575
Steve Anton4171afb2017-11-20 10:20:22 -08001576std::vector<
1577 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1578PeerConnection::GetReceiversInternal() const {
1579 std::vector<
1580 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1581 all_receivers;
1582 for (auto transceiver : transceivers_) {
1583 auto receivers = transceiver->internal()->receivers();
1584 all_receivers.insert(all_receivers.end(), receivers.begin(),
1585 receivers.end());
1586 }
1587 return all_receivers;
1588}
1589
Steve Anton9158ef62017-11-27 13:01:52 -08001590std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1591PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001592 RTC_CHECK(IsUnifiedPlan())
1593 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001594 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1595 for (auto transceiver : transceivers_) {
1596 all_transceivers.push_back(transceiver);
1597 }
1598 return all_transceivers;
1599}
1600
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001601bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001602 MediaStreamTrackInterface* track,
1603 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001604 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001605 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001606 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001607 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001608 return false;
1609 }
1610
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001611 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001612 // The StatsCollector is used to tell if a track is valid because it may
1613 // remember tracks that the PeerConnection previously removed.
1614 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001615 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1616 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001617 return false;
1618 }
Steve Antonad182762018-09-05 20:22:40 +00001619 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1620 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001621 return true;
1622}
1623
hbos74e1a4f2016-09-15 23:33:01 -07001624void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001625 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001626 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001627 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001628 stats_collector_->GetStatsReport(callback);
1629}
1630
Henrik Boström1df1bf82018-03-20 13:24:20 +01001631void PeerConnection::GetStats(
1632 rtc::scoped_refptr<RtpSenderInterface> selector,
1633 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1634 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1635 RTC_DCHECK(callback);
1636 RTC_DCHECK(stats_collector_);
1637 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1638 if (selector) {
1639 for (const auto& proxy_transceiver : transceivers_) {
1640 for (const auto& proxy_sender :
1641 proxy_transceiver->internal()->senders()) {
1642 if (proxy_sender == selector) {
1643 internal_sender = proxy_sender->internal();
1644 break;
1645 }
1646 }
1647 if (internal_sender)
1648 break;
1649 }
1650 }
1651 // If there is no |internal_sender| then |selector| is either null or does not
1652 // belong to the PeerConnection (in Plan B, senders can be removed from the
1653 // PeerConnection). This means that "all the stats objects representing the
1654 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1655 // produces an empty stats report.
1656 stats_collector_->GetStatsReport(internal_sender, callback);
1657}
1658
1659void PeerConnection::GetStats(
1660 rtc::scoped_refptr<RtpReceiverInterface> selector,
1661 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1662 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1663 RTC_DCHECK(callback);
1664 RTC_DCHECK(stats_collector_);
1665 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1666 if (selector) {
1667 for (const auto& proxy_transceiver : transceivers_) {
1668 for (const auto& proxy_receiver :
1669 proxy_transceiver->internal()->receivers()) {
1670 if (proxy_receiver == selector) {
1671 internal_receiver = proxy_receiver->internal();
1672 break;
1673 }
1674 }
1675 if (internal_receiver)
1676 break;
1677 }
1678 }
1679 // If there is no |internal_receiver| then |selector| is either null or does
1680 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1681 // the PeerConnection). This means that "all the stats objects representing
1682 // the selector" is an empty set. Invoking GetStatsReport() with a null
1683 // selector produces an empty stats report.
1684 stats_collector_->GetStatsReport(internal_receiver, callback);
1685}
1686
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001687PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1688 return signaling_state_;
1689}
1690
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001691PeerConnectionInterface::IceConnectionState
1692PeerConnection::ice_connection_state() {
1693 return ice_connection_state_;
1694}
1695
1696PeerConnectionInterface::IceGatheringState
1697PeerConnection::ice_gathering_state() {
1698 return ice_gathering_state_;
1699}
1700
Yves Gerey665174f2018-06-19 15:03:05 +02001701rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001702 const std::string& label,
1703 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001704 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001705
deadbeefab9b2d12015-10-14 11:33:11 -07001706 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001707
kwibergd1fe2812016-04-27 06:47:29 -07001708 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001709 if (config) {
1710 internal_config.reset(new InternalDataChannelInit(*config));
1711 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001712 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001713 InternalCreateDataChannel(label, internal_config.get()));
1714 if (!channel.get()) {
1715 return nullptr;
1716 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001717
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001718 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1719 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001720 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001721 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001722 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001723 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001724 return DataChannelProxy::Create(signaling_thread(), channel.get());
1725}
1726
1727void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001728 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001729 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001730
nisse7ce109a2017-01-31 00:57:56 -08001731 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001732 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001733 return;
1734 }
deadbeefab9b2d12015-10-14 11:33:11 -07001735
Steve Anton8d3444d2017-10-20 15:30:51 -07001736 if (IsClosed()) {
1737 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001738 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001739 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001740 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001741 return;
1742 }
1743
zhihuang1c378ed2017-08-17 14:10:50 -07001744 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001745 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001746 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001747 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001748 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001749 return;
1750 }
1751
Steve Anton22da89f2018-01-25 13:58:07 -08001752 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1753 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1754 if (IsUnifiedPlan()) {
1755 RTCError error = HandleLegacyOfferOptions(options);
1756 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001757 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001758 return;
1759 }
1760 }
1761
zhihuang1c378ed2017-08-17 14:10:50 -07001762 cricket::MediaSessionOptions session_options;
1763 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001764 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001765}
1766
Steve Anton22da89f2018-01-25 13:58:07 -08001767RTCError PeerConnection::HandleLegacyOfferOptions(
1768 const RTCOfferAnswerOptions& options) {
1769 RTC_DCHECK(IsUnifiedPlan());
1770
1771 if (options.offer_to_receive_audio == 0) {
1772 RemoveRecvDirectionFromReceivingTransceiversOfType(
1773 cricket::MEDIA_TYPE_AUDIO);
1774 } else if (options.offer_to_receive_audio == 1) {
1775 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1776 } else if (options.offer_to_receive_audio > 1) {
1777 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1778 "offer_to_receive_audio > 1 is not supported.");
1779 }
1780
1781 if (options.offer_to_receive_video == 0) {
1782 RemoveRecvDirectionFromReceivingTransceiversOfType(
1783 cricket::MEDIA_TYPE_VIDEO);
1784 } else if (options.offer_to_receive_video == 1) {
1785 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1786 } else if (options.offer_to_receive_video > 1) {
1787 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1788 "offer_to_receive_video > 1 is not supported.");
1789 }
1790
1791 return RTCError::OK();
1792}
1793
1794void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1795 cricket::MediaType media_type) {
1796 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001797 RtpTransceiverDirection new_direction =
1798 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1799 if (new_direction != transceiver->direction()) {
1800 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1801 << " transceiver (MID="
1802 << transceiver->mid().value_or("<not set>") << ") from "
1803 << RtpTransceiverDirectionToString(
1804 transceiver->direction())
1805 << " to "
1806 << RtpTransceiverDirectionToString(new_direction)
1807 << " since CreateOffer specified offer_to_receive=0";
1808 transceiver->internal()->set_direction(new_direction);
1809 }
Steve Anton22da89f2018-01-25 13:58:07 -08001810 }
1811}
1812
1813void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1814 cricket::MediaType media_type) {
1815 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001816 RTC_LOG(LS_INFO)
1817 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1818 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001819 RtpTransceiverInit init;
1820 init.direction = RtpTransceiverDirection::kRecvOnly;
1821 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1822 }
1823}
1824
1825std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1826PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1827 std::vector<
1828 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1829 receiving_transceivers;
1830 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001831 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001832 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1833 receiving_transceivers.push_back(transceiver);
1834 }
1835 }
1836 return receiving_transceivers;
1837}
1838
htaa2a49d92016-03-04 02:51:39 -08001839void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1840 const RTCOfferAnswerOptions& options) {
1841 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001842 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001843 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001844 return;
1845 }
1846
Steve Antondffead82018-02-06 10:31:29 -08001847 if (!(signaling_state_ == kHaveRemoteOffer ||
1848 signaling_state_ == kHaveLocalPrAnswer)) {
1849 std::string error =
1850 "PeerConnection cannot create an answer in a state other than "
1851 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001852 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001853 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001854 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001855 return;
1856 }
1857
Steve Antondffead82018-02-06 10:31:29 -08001858 // The remote description should be set if we're in the right state.
1859 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001860
Steve Anton22da89f2018-01-25 13:58:07 -08001861 if (IsUnifiedPlan()) {
1862 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1863 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1864 "supported with Unified Plan semantics. Use the "
1865 "RtpTransceiver API instead.";
1866 }
1867 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1868 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1869 "supported with Unified Plan semantics. Use the "
1870 "RtpTransceiver API instead.";
1871 }
1872 }
1873
htaa2a49d92016-03-04 02:51:39 -08001874 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001875 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001876
Steve Antond25da372017-11-06 14:50:29 -08001877 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001878}
1879
1880void PeerConnection::SetLocalDescription(
1881 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001882 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001883 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001884
Steve Anton80dd7b52018-02-16 17:08:42 -08001885 // The SetLocalDescription contract is that we take ownership of the session
1886 // description regardless of the outcome, so wrap it in a unique_ptr right
1887 // away. Ideally, SetLocalDescription's signature will be changed to take the
1888 // description as a unique_ptr argument to formalize this agreement.
1889 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1890
nisse7ce109a2017-01-31 00:57:56 -08001891 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001892 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001893 return;
1894 }
Steve Anton8a006912017-12-04 15:25:56 -08001895
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001896 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001897 PostSetSessionDescriptionFailure(
1898 observer,
1899 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001900 return;
1901 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001902
Steve Anton80dd7b52018-02-16 17:08:42 -08001903 // If a session error has occurred the PeerConnection is in a possibly
1904 // inconsistent state so fail right away.
1905 if (session_error() != SessionError::kNone) {
1906 std::string error_message = GetSessionErrorMsg();
1907 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001908 PostSetSessionDescriptionFailure(
1909 observer,
1910 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001911 return;
1912 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001913
Steve Anton80dd7b52018-02-16 17:08:42 -08001914 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1915 if (!error.ok()) {
1916 std::string error_message = GetSetDescriptionErrorMessage(
1917 cricket::CS_LOCAL, desc->GetType(), error);
1918 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001919 PostSetSessionDescriptionFailure(
1920 observer,
1921 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001922 return;
1923 }
1924
1925 // Grab the description type before moving ownership to ApplyLocalDescription,
1926 // which may destroy it before returning.
1927 const SdpType type = desc->GetType();
1928
1929 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001930 // |desc| may be destroyed at this point.
1931
1932 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001933 // If ApplyLocalDescription fails, the PeerConnection could be in an
1934 // inconsistent state, so act conservatively here and set the session error
1935 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1936 SetSessionError(SessionError::kContent, error.message());
1937 std::string error_message =
1938 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1939 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001940 PostSetSessionDescriptionFailure(
1941 observer,
1942 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001943 return;
1944 }
Steve Anton8a006912017-12-04 15:25:56 -08001945 RTC_DCHECK(local_description());
1946
1947 PostSetSessionDescriptionSuccess(observer);
1948
Steve Antonad182762018-09-05 20:22:40 +00001949 // MaybeStartGathering needs to be called after posting
1950 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1951 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001952 transport_controller_->MaybeStartGathering();
1953
Steve Antona3a92c22017-12-07 10:27:41 -08001954 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001955 // TODO(deadbeef): We already had to hop to the network thread for
1956 // MaybeStartGathering...
1957 network_thread()->Invoke<void>(
1958 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1959 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001960 // Make UMA notes about what was agreed to.
1961 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001962 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001963 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001964}
1965
1966RTCError PeerConnection::ApplyLocalDescription(
1967 std::unique_ptr<SessionDescriptionInterface> desc) {
1968 RTC_DCHECK_RUN_ON(signaling_thread());
1969 RTC_DCHECK(desc);
1970
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001971 // Update stats here so that we have the most recent stats for tracks and
1972 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001973 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001974
Steve Antondcc3c022017-12-22 16:02:54 -08001975 // Take a reference to the old local description since it's used below to
1976 // compare against the new local description. When setting the new local
1977 // description, grab ownership of the replaced session description in case it
1978 // is the same as |old_local_description|, to keep it alive for the duration
1979 // of the method.
1980 const SessionDescriptionInterface* old_local_description =
1981 local_description();
1982 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001983 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001984 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001985 replaced_local_description = pending_local_description_
1986 ? std::move(pending_local_description_)
1987 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001988 current_local_description_ = std::move(desc);
1989 pending_local_description_ = nullptr;
1990 current_remote_description_ = std::move(pending_remote_description_);
1991 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001992 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001993 pending_local_description_ = std::move(desc);
1994 }
1995 // The session description to apply now must be accessed by
1996 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001997 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001998
Zhi Huange830e682018-03-30 10:48:35 -07001999 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2000 if (!error.ok()) {
2001 return error;
2002 }
2003
Steve Antondcc3c022017-12-22 16:02:54 -08002004 if (IsUnifiedPlan()) {
2005 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002006 cricket::CS_LOCAL, *local_description(), old_local_description,
2007 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002008 if (!error.ok()) {
2009 return error;
2010 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002011 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2012 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002013 for (auto transceiver : transceivers_) {
2014 const ContentInfo* content =
2015 FindMediaSectionForTransceiver(transceiver, local_description());
2016 if (!content) {
2017 continue;
2018 }
2019 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002020 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2021 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002022 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002023 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2024 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2025 // "recvonly", process the removal of a remote track for the media
2026 // description, given transceiver, removeList, and muteTracks.
2027 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2028 (transceiver->internal()->fired_direction() &&
2029 RtpTransceiverDirectionHasRecv(
2030 *transceiver->internal()->fired_direction()))) {
2031 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2032 &removed_streams);
2033 }
2034 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2035 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002036 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002037 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002038 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002039 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002040 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002041 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002042 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002043 }
2044 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002045 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002046 }
2047 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002048 // Media channels will be created only when offer is set. These may use new
2049 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002050 if (type == SdpType::kOffer) {
2051 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2052 // description is applied. Restore back to old description.
2053 RTCError error = CreateChannels(*local_description()->description());
2054 if (!error.ok()) {
2055 return error;
2056 }
2057 }
Steve Antondcc3c022017-12-22 16:02:54 -08002058 // Remove unused channels if MediaContentDescription is rejected.
2059 RemoveUnusedChannels(local_description()->description());
2060 }
Steve Anton8a006912017-12-04 15:25:56 -08002061
Zhi Huange830e682018-03-30 10:48:35 -07002062 error = UpdateSessionState(type, cricket::CS_LOCAL,
2063 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002064 if (!error.ok()) {
2065 return error;
2066 }
Steve Antondcc3c022017-12-22 16:02:54 -08002067
Steve Anton8a006912017-12-04 15:25:56 -08002068 if (remote_description()) {
2069 // Now that we have a local description, we can push down remote candidates.
2070 UseCandidatesInSessionDescription(remote_description());
2071 }
2072
2073 pending_ice_restarts_.clear();
2074 if (session_error() != SessionError::kNone) {
2075 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2076 }
2077
deadbeefab9b2d12015-10-14 11:33:11 -07002078 // If setting the description decided our SSL role, allocate any necessary
2079 // SCTP sids.
2080 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002081 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002082 AllocateSctpSids(role);
2083 }
2084
Steve Antond3679212018-01-17 17:41:02 -08002085 if (IsUnifiedPlan()) {
2086 for (auto transceiver : transceivers_) {
2087 const ContentInfo* content =
2088 FindMediaSectionForTransceiver(transceiver, local_description());
2089 if (!content) {
2090 continue;
2091 }
Steve Anton74255ff2018-01-24 18:32:57 -08002092 const auto& streams = content->media_description()->streams();
2093 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002094 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002095 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002096 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002097 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002098 } else {
2099 // 0 is a special value meaning "this sender has no associated send
2100 // stream". Need to call this so the sender won't attempt to configure
2101 // a no longer existing stream and run into DCHECKs in the lower
2102 // layers.
2103 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002104 }
2105 }
2106 } else {
2107 // Plan B semantics.
2108
Steve Antondcc3c022017-12-22 16:02:54 -08002109 // Update state and SSRC of local MediaStreams and DataChannels based on the
2110 // local session description.
2111 const cricket::ContentInfo* audio_content =
2112 GetFirstAudioContent(local_description()->description());
2113 if (audio_content) {
2114 if (audio_content->rejected) {
2115 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2116 } else {
2117 const cricket::AudioContentDescription* audio_desc =
2118 audio_content->media_description()->as_audio();
2119 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2120 }
deadbeeffaac4972015-11-12 15:33:07 -08002121 }
deadbeefab9b2d12015-10-14 11:33:11 -07002122
Steve Antondcc3c022017-12-22 16:02:54 -08002123 const cricket::ContentInfo* video_content =
2124 GetFirstVideoContent(local_description()->description());
2125 if (video_content) {
2126 if (video_content->rejected) {
2127 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2128 } else {
2129 const cricket::VideoContentDescription* video_desc =
2130 video_content->media_description()->as_video();
2131 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2132 }
deadbeeffaac4972015-11-12 15:33:07 -08002133 }
deadbeefab9b2d12015-10-14 11:33:11 -07002134 }
2135
2136 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002137 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002138 if (data_content) {
2139 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002140 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002141 if (rtc::starts_with(data_desc->protocol().data(),
2142 cricket::kMediaProtocolRtpPrefix)) {
2143 UpdateLocalRtpDataChannels(data_desc->streams());
2144 }
2145 }
2146
Steve Anton8a006912017-12-04 15:25:56 -08002147 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002148}
2149
2150void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002151 SetSessionDescriptionObserver* observer,
2152 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002153 SetRemoteDescription(
2154 std::unique_ptr<SessionDescriptionInterface>(desc),
2155 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2156 new SetRemoteDescriptionObserverAdapter(this, observer)));
2157}
2158
2159void PeerConnection::SetRemoteDescription(
2160 std::unique_ptr<SessionDescriptionInterface> desc,
2161 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002162 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002163
nisse7ce109a2017-01-31 00:57:56 -08002164 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002165 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002166 return;
2167 }
Steve Anton8a006912017-12-04 15:25:56 -08002168
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002169 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002170 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002171 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002172 return;
2173 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002174
Steve Anton80dd7b52018-02-16 17:08:42 -08002175 // If a session error has occurred the PeerConnection is in a possibly
2176 // inconsistent state so fail right away.
2177 if (session_error() != SessionError::kNone) {
2178 std::string error_message = GetSessionErrorMsg();
2179 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2180 observer->OnSetRemoteDescriptionComplete(
2181 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2182 return;
2183 }
Steve Anton71439a62018-02-15 11:53:06 -08002184
Steve Antonba42e992018-04-09 14:10:01 -07002185 if (desc->GetType() == SdpType::kOffer) {
2186 // Report to UMA the format of the received offer.
2187 ReportSdpFormatReceived(*desc);
2188 }
2189
Steve Anton80dd7b52018-02-16 17:08:42 -08002190 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002191 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002192 std::string error_message = GetSetDescriptionErrorMessage(
2193 cricket::CS_REMOTE, desc->GetType(), error);
2194 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002195 observer->OnSetRemoteDescriptionComplete(
2196 RTCError(error.type(), std::move(error_message)));
2197 return;
2198 }
Steve Anton71439a62018-02-15 11:53:06 -08002199
Steve Anton80dd7b52018-02-16 17:08:42 -08002200 // Grab the description type before moving ownership to
2201 // ApplyRemoteDescription, which may destroy it before returning.
2202 const SdpType type = desc->GetType();
2203
2204 error = ApplyRemoteDescription(std::move(desc));
2205 // |desc| may be destroyed at this point.
2206
2207 if (!error.ok()) {
2208 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2209 // inconsistent state, so act conservatively here and set the session error
2210 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2211 SetSessionError(SessionError::kContent, error.message());
2212 std::string error_message =
2213 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2214 RTC_LOG(LS_ERROR) << error_message;
2215 observer->OnSetRemoteDescriptionComplete(
2216 RTCError(error.type(), std::move(error_message)));
2217 return;
2218 }
2219 RTC_DCHECK(remote_description());
2220
2221 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002222 // TODO(deadbeef): We already had to hop to the network thread for
2223 // MaybeStartGathering...
2224 network_thread()->Invoke<void>(
2225 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2226 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002227 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002228 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002229 }
2230
2231 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002232 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002233}
2234
2235RTCError PeerConnection::ApplyRemoteDescription(
2236 std::unique_ptr<SessionDescriptionInterface> desc) {
2237 RTC_DCHECK_RUN_ON(signaling_thread());
2238 RTC_DCHECK(desc);
2239
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002240 // Update stats here so that we have the most recent stats for tracks and
2241 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002242 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002243
Steve Antondcc3c022017-12-22 16:02:54 -08002244 // Take a reference to the old remote description since it's used below to
2245 // compare against the new remote description. When setting the new remote
2246 // description, grab ownership of the replaced session description in case it
2247 // is the same as |old_remote_description|, to keep it alive for the duration
2248 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002249 const SessionDescriptionInterface* old_remote_description =
2250 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002251 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002252 SdpType type = desc->GetType();
2253 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002254 replaced_remote_description = pending_remote_description_
2255 ? std::move(pending_remote_description_)
2256 : std::move(current_remote_description_);
2257 current_remote_description_ = std::move(desc);
2258 pending_remote_description_ = nullptr;
2259 current_local_description_ = std::move(pending_local_description_);
2260 } else {
2261 replaced_remote_description = std::move(pending_remote_description_);
2262 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002263 }
Steve Anton8a006912017-12-04 15:25:56 -08002264 // The session description to apply now must be accessed by
2265 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002266 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002267
Zhi Huange830e682018-03-30 10:48:35 -07002268 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2269 if (!error.ok()) {
2270 return error;
2271 }
Steve Anton8a006912017-12-04 15:25:56 -08002272 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002273 if (IsUnifiedPlan()) {
2274 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002275 cricket::CS_REMOTE, *remote_description(), local_description(),
2276 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002277 if (!error.ok()) {
2278 return error;
2279 }
Steve Antondcc3c022017-12-22 16:02:54 -08002280 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002281 // Media channels will be created only when offer is set. These may use new
2282 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002283 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002284 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002285 // description is applied. Restore back to old description.
2286 RTCError error = CreateChannels(*remote_description()->description());
2287 if (!error.ok()) {
2288 return error;
2289 }
2290 }
Steve Antondcc3c022017-12-22 16:02:54 -08002291 // Remove unused channels if MediaContentDescription is rejected.
2292 RemoveUnusedChannels(remote_description()->description());
2293 }
Steve Anton8a006912017-12-04 15:25:56 -08002294
Zhi Huange830e682018-03-30 10:48:35 -07002295 // NOTE: Candidates allocation will be initiated only when
2296 // SetLocalDescription is called.
2297 error = UpdateSessionState(type, cricket::CS_REMOTE,
2298 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002299 if (!error.ok()) {
2300 return error;
2301 }
2302
2303 if (local_description() &&
2304 !UseCandidatesInSessionDescription(remote_description())) {
2305 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2306 }
2307
2308 if (old_remote_description) {
2309 for (const cricket::ContentInfo& content :
2310 old_remote_description->description()->contents()) {
2311 // Check if this new SessionDescription contains new ICE ufrag and
2312 // password that indicates the remote peer requests an ICE restart.
2313 // TODO(deadbeef): When we start storing both the current and pending
2314 // remote description, this should reset pending_ice_restarts and compare
2315 // against the current description.
2316 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2317 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002318 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002319 pending_ice_restarts_.insert(content.name);
2320 }
2321 } else {
2322 // We retain all received candidates only if ICE is not restarted.
2323 // When ICE is restarted, all previous candidates belong to an old
2324 // generation and should not be kept.
2325 // TODO(deadbeef): This goes against the W3C spec which says the remote
2326 // description should only contain candidates from the last set remote
2327 // description plus any candidates added since then. We should remove
2328 // this once we're sure it won't break anything.
2329 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2330 old_remote_description, content.name, mutable_remote_description());
2331 }
2332 }
2333 }
2334
2335 if (session_error() != SessionError::kNone) {
2336 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2337 }
2338
2339 // Set the the ICE connection state to connecting since the connection may
2340 // become writable with peer reflexive candidates before any remote candidate
2341 // is signaled.
2342 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2343 // is to have a new signal the indicates a change in checking state from the
2344 // transport and expose a new checking() member from transport that can be
2345 // read to determine the current checking state. The existing SignalConnecting
2346 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002347 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002348 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002349 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2350 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2351 }
2352
deadbeefab9b2d12015-10-14 11:33:11 -07002353 // If setting the description decided our SSL role, allocate any necessary
2354 // SCTP sids.
2355 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002356 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002357 AllocateSctpSids(role);
2358 }
2359
Steve Antondcc3c022017-12-22 16:02:54 -08002360 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002361 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002362 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002363 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002364 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002365 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002366 for (auto transceiver : transceivers_) {
2367 const ContentInfo* content =
2368 FindMediaSectionForTransceiver(transceiver, remote_description());
2369 if (!content) {
2370 continue;
2371 }
2372 const MediaContentDescription* media_desc = content->media_description();
2373 RtpTransceiverDirection local_direction =
2374 RtpTransceiverDirectionReversed(media_desc->direction());
2375 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2376 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2377 // transceiver's current direction is neither sendrecv nor recvonly,
2378 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002379 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002380 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002381 // The remote description has signaled the stream IDs.
2382 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002383 }
Steve Antondcc3c022017-12-22 16:02:54 -08002384 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002385 (!transceiver->fired_direction() ||
2386 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002387 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002388 << content->name << " (added to "
2389 << GetStreamIdsString(stream_ids) << ").";
2390
2391 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2392 for (const std::string& stream_id : stream_ids) {
2393 rtc::scoped_refptr<MediaStreamInterface> stream =
2394 remote_streams_->find(stream_id);
2395 if (!stream) {
2396 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2397 MediaStream::Create(stream_id));
2398 remote_streams_->AddStream(stream);
2399 added_streams.push_back(stream);
2400 }
2401 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002402 }
Steve Anton3172c032018-05-03 15:30:18 -07002403 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002404 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2405 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002406 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002407 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002408 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002409 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2410 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2411 // removal of a remote track for the media description, given transceiver,
2412 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002413 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002414 (transceiver->fired_direction() &&
2415 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2416 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2417 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002418 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002419 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2420 transceiver->internal()->set_fired_direction(local_direction);
2421 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2422 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002423 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002424 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2425 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002426 transceiver->internal()->set_current_direction(local_direction);
2427 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002428 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2429 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002430 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002431 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2432 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002433 transceiver->Stop();
2434 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002435 if (!content->rejected &&
2436 RtpTransceiverDirectionHasRecv(local_direction)) {
2437 // Set ssrc to 0 in the case of an unsignalled ssrc.
2438 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002439 if (!media_desc->streams().empty() &&
2440 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002441 ssrc = media_desc->streams()[0].first_ssrc();
2442 }
2443 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002444 }
Steve Antondcc3c022017-12-22 16:02:54 -08002445 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002446 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002447 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002448 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002449 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002450 observer->OnTrack(transceiver);
2451 observer->OnAddTrack(transceiver->receiver(),
2452 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002453 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002454 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002455 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002456 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002457 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002458 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002459 }
2460 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002461 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002462 }
Steve Antondcc3c022017-12-22 16:02:54 -08002463 }
2464
Henrik Boströmfdb92012017-11-09 19:55:44 +01002465 const cricket::ContentInfo* audio_content =
2466 GetFirstAudioContent(remote_description()->description());
2467 const cricket::ContentInfo* video_content =
2468 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002469 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002470 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002471 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002472 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002473 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002474 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002475
2476 // Check if the descriptions include streams, just in case the peer supports
2477 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002478 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002479 (audio_desc && !audio_desc->streams().empty()) ||
2480 (video_desc && !video_desc->streams().empty())) {
2481 remote_peer_supports_msid_ = true;
2482 }
deadbeefab9b2d12015-10-14 11:33:11 -07002483
2484 // We wait to signal new streams until we finish processing the description,
2485 // since only at that point will new streams have all their tracks.
2486 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2487
Steve Antondcc3c022017-12-22 16:02:54 -08002488 if (!IsUnifiedPlan()) {
2489 // TODO(steveanton): When removing RTP senders/receivers in response to a
2490 // rejected media section, there is some cleanup logic that expects the
2491 // voice/ video channel to still be set. But in this method the voice/video
2492 // channel would have been destroyed by the SetRemoteDescription caller
2493 // above so the cleanup that relies on them fails to run. The RemoveSenders
2494 // calls should be moved to right before the DestroyChannel calls to fix
2495 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002496
Steve Antondcc3c022017-12-22 16:02:54 -08002497 // Find all audio rtp streams and create corresponding remote AudioTracks
2498 // and MediaStreams.
2499 if (audio_content) {
2500 if (audio_content->rejected) {
2501 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2502 } else {
2503 bool default_audio_track_needed =
2504 !remote_peer_supports_msid_ &&
2505 RtpTransceiverDirectionHasSend(audio_desc->direction());
2506 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2507 default_audio_track_needed, audio_desc->type(),
2508 new_streams);
2509 }
deadbeeffaac4972015-11-12 15:33:07 -08002510 }
deadbeefab9b2d12015-10-14 11:33:11 -07002511
Steve Antondcc3c022017-12-22 16:02:54 -08002512 // Find all video rtp streams and create corresponding remote VideoTracks
2513 // and MediaStreams.
2514 if (video_content) {
2515 if (video_content->rejected) {
2516 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2517 } else {
2518 bool default_video_track_needed =
2519 !remote_peer_supports_msid_ &&
2520 RtpTransceiverDirectionHasSend(video_desc->direction());
2521 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2522 default_video_track_needed, video_desc->type(),
2523 new_streams);
2524 }
deadbeeffaac4972015-11-12 15:33:07 -08002525 }
deadbeefab9b2d12015-10-14 11:33:11 -07002526
Steve Antondcc3c022017-12-22 16:02:54 -08002527 // Update the DataChannels with the information from the remote peer.
2528 if (data_desc) {
2529 if (rtc::starts_with(data_desc->protocol().data(),
2530 cricket::kMediaProtocolRtpPrefix)) {
2531 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2532 }
deadbeefab9b2d12015-10-14 11:33:11 -07002533 }
deadbeefab9b2d12015-10-14 11:33:11 -07002534
Steve Antondcc3c022017-12-22 16:02:54 -08002535 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002536 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002537 for (size_t i = 0; i < new_streams->count(); ++i) {
2538 MediaStreamInterface* new_stream = new_streams->at(i);
2539 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002540 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002541 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2542 }
deadbeefab9b2d12015-10-14 11:33:11 -07002543
Steve Antondcc3c022017-12-22 16:02:54 -08002544 UpdateEndedRemoteMediaStreams();
2545 }
deadbeefab9b2d12015-10-14 11:33:11 -07002546
Steve Anton8a006912017-12-04 15:25:56 -08002547 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002548}
2549
Steve Anton0f5400a2018-07-17 14:25:36 -07002550void PeerConnection::ProcessRemovalOfRemoteTrack(
2551 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2552 transceiver,
2553 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2554 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2555 RTC_DCHECK(transceiver->mid());
2556 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2557 << *transceiver->mid();
2558 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2559 transceiver->internal()->receiver_internal()->streams();
2560 // This will remove the remote track from the streams.
2561 transceiver->internal()->receiver_internal()->set_stream_ids({});
2562 remove_list->push_back(transceiver);
2563 // Remove any streams that no longer have tracks.
2564 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2565 // of streams, see if the stream was removed by checking if this was the
2566 // last receiver with that stream ID.
2567 for (auto stream : media_streams) {
2568 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2569 remote_streams_->RemoveStream(stream);
2570 removed_streams->push_back(stream);
2571 }
2572 }
2573}
2574
Steve Antondcc3c022017-12-22 16:02:54 -08002575RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2576 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002577 const SessionDescriptionInterface& new_session,
2578 const SessionDescriptionInterface* old_local_description,
2579 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002580 RTC_DCHECK(IsUnifiedPlan());
2581
Steve Anton7464fca2018-01-19 11:10:37 -08002582 const cricket::ContentGroup* bundle_group = nullptr;
2583 if (new_session.GetType() == SdpType::kOffer) {
2584 auto bundle_group_or_error =
2585 GetEarlyBundleGroup(*new_session.description());
2586 if (!bundle_group_or_error.ok()) {
2587 return bundle_group_or_error.MoveError();
2588 }
2589 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002590 }
Steve Antondcc3c022017-12-22 16:02:54 -08002591
Steve Antondcc3c022017-12-22 16:02:54 -08002592 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002593 for (size_t i = 0; i < new_contents.size(); ++i) {
2594 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002595 cricket::MediaType media_type = new_content.media_description()->type();
2596 seen_mids_.insert(new_content.name);
2597 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2598 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002599 const cricket::ContentInfo* old_local_content = nullptr;
2600 if (old_local_description &&
2601 i < old_local_description->description()->contents().size()) {
2602 old_local_content =
2603 &old_local_description->description()->contents()[i];
2604 }
2605 const cricket::ContentInfo* old_remote_content = nullptr;
2606 if (old_remote_description &&
2607 i < old_remote_description->description()->contents().size()) {
2608 old_remote_content =
2609 &old_remote_description->description()->contents()[i];
2610 }
Steve Antondcc3c022017-12-22 16:02:54 -08002611 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002612 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2613 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002614 if (!transceiver_or_error.ok()) {
2615 return transceiver_or_error.MoveError();
2616 }
2617 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002618 RTCError error =
2619 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2620 if (!error.ok()) {
2621 return error;
2622 }
2623 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002624 if (GetDataMid() && new_content.name != *GetDataMid()) {
2625 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002626 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2627 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002628 continue;
2629 }
2630 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2631 if (!error.ok()) {
2632 return error;
2633 }
Steve Antondcc3c022017-12-22 16:02:54 -08002634 } else {
2635 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2636 "Unknown section type.");
2637 }
2638 }
2639
2640 return RTCError::OK();
2641}
2642
2643RTCError PeerConnection::UpdateTransceiverChannel(
2644 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2645 transceiver,
2646 const cricket::ContentInfo& content,
2647 const cricket::ContentGroup* bundle_group) {
2648 RTC_DCHECK(IsUnifiedPlan());
2649 RTC_DCHECK(transceiver);
2650 cricket::BaseChannel* channel = transceiver->internal()->channel();
2651 if (content.rejected) {
2652 if (channel) {
2653 transceiver->internal()->SetChannel(nullptr);
2654 DestroyBaseChannel(channel);
2655 }
2656 } else {
2657 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002658 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002659 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002660 } else {
Steve Anton69470252018-02-09 11:43:08 -08002661 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002662 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002663 }
2664 if (!channel) {
2665 LOG_AND_RETURN_ERROR(
2666 RTCErrorType::INTERNAL_ERROR,
2667 "Failed to create channel for mid=" + content.name);
2668 }
2669 transceiver->internal()->SetChannel(channel);
2670 }
2671 }
2672 return RTCError::OK();
2673}
2674
Steve Antonfa2260d2017-12-28 16:38:23 -08002675RTCError PeerConnection::UpdateDataChannel(
2676 cricket::ContentSource source,
2677 const cricket::ContentInfo& content,
2678 const cricket::ContentGroup* bundle_group) {
2679 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002680 // If data channels are disabled, ignore this media section. CreateAnswer
2681 // will take care of rejecting it.
2682 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002683 }
2684 if (content.rejected) {
2685 DestroyDataChannel();
2686 } else {
2687 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002688 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002689 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2690 "Failed to create data channel.");
2691 }
2692 }
2693 if (source == cricket::CS_REMOTE) {
2694 const MediaContentDescription* data_desc = content.media_description();
2695 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2696 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2697 }
2698 }
2699 }
2700 return RTCError::OK();
2701}
2702
Steve Antondcc3c022017-12-22 16:02:54 -08002703RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2704PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002705 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002706 size_t mline_index,
2707 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002708 const ContentInfo* old_local_content,
2709 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002710 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002711 // If this is an offer then the m= section might be recycled. If the m=
2712 // section is being recycled (defined as: rejected in the current local or
2713 // remote description and not rejected in new description), dissociate the
2714 // currently associated RtpTransceiver by setting its mid property to null,
2715 // and discard the mapping between the transceiver and its m= section index.
2716 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2717 old_remote_content)) {
2718 // We want to dissociate the transceiver that has the rejected mid.
2719 const std::string& old_mid =
2720 (old_local_content && old_local_content->rejected)
2721 ? old_local_content->name
2722 : old_remote_content->name;
2723 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002724 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002725 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2726 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002727 old_transceiver->internal()->set_mid(absl::nullopt);
2728 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002729 }
2730 }
2731 const MediaContentDescription* media_desc = content.media_description();
2732 auto transceiver = GetAssociatedTransceiver(content.name);
2733 if (source == cricket::CS_LOCAL) {
2734 // Find the RtpTransceiver that corresponds to this m= section, using the
2735 // mapping between transceivers and m= section indices established when
2736 // creating the offer.
2737 if (!transceiver) {
2738 transceiver = GetTransceiverByMLineIndex(mline_index);
2739 }
2740 if (!transceiver) {
2741 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2742 "Unknown transceiver");
2743 }
2744 } else {
2745 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2746 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2747 // of the same type...
2748 if (!transceiver &&
2749 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2750 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2751 }
2752 // If no RtpTransceiver was found in the previous step, create one with a
2753 // recvonly direction.
2754 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002755 RTC_LOG(LS_INFO) << "Adding "
2756 << cricket::MediaTypeToString(media_desc->type())
2757 << " transceiver for MID=" << content.name
2758 << " at i=" << mline_index
2759 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002760 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002761 auto sender =
2762 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002763 std::string receiver_id;
2764 if (!media_desc->streams().empty()) {
2765 receiver_id = media_desc->streams()[0].id;
2766 } else {
2767 receiver_id = rtc::CreateRandomUuid();
2768 }
2769 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002770 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002771 transceiver->internal()->set_direction(
2772 RtpTransceiverDirection::kRecvOnly);
2773 }
2774 }
2775 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002776 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002777 LOG_AND_RETURN_ERROR(
2778 RTCErrorType::INVALID_PARAMETER,
2779 "Transceiver type does not match media description type.");
2780 }
2781 // Associate the found or created RtpTransceiver with the m= section by
2782 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2783 // section, and establish a mapping between the transceiver and the index of
2784 // the m= section.
2785 transceiver->internal()->set_mid(content.name);
2786 transceiver->internal()->set_mline_index(mline_index);
2787 return std::move(transceiver);
2788}
2789
2790rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2791PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2792 RTC_DCHECK(IsUnifiedPlan());
2793 for (auto transceiver : transceivers_) {
2794 if (transceiver->mid() == mid) {
2795 return transceiver;
2796 }
2797 }
2798 return nullptr;
2799}
2800
2801rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2802PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2803 RTC_DCHECK(IsUnifiedPlan());
2804 for (auto transceiver : transceivers_) {
2805 if (transceiver->internal()->mline_index() == mline_index) {
2806 return transceiver;
2807 }
2808 }
2809 return nullptr;
2810}
2811
2812rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2813PeerConnection::FindAvailableTransceiverToReceive(
2814 cricket::MediaType media_type) const {
2815 RTC_DCHECK(IsUnifiedPlan());
2816 // From JSEP section 5.10 (Applying a Remote Description):
2817 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2818 // the same type that were added to the PeerConnection by addTrack and are not
2819 // associated with any m= section and are not stopped, find the first such
2820 // RtpTransceiver.
2821 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002822 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002823 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2824 !transceiver->stopped()) {
2825 return transceiver;
2826 }
2827 }
2828 return nullptr;
2829}
2830
Steve Antoned10bd92017-12-05 10:52:59 -08002831const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2832 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2833 transceiver,
2834 const SessionDescriptionInterface* sdesc) const {
2835 RTC_DCHECK(transceiver);
2836 RTC_DCHECK(sdesc);
2837 if (IsUnifiedPlan()) {
2838 if (!transceiver->internal()->mid()) {
2839 // This transceiver is not associated with a media section yet.
2840 return nullptr;
2841 }
2842 return sdesc->description()->GetContentByName(
2843 *transceiver->internal()->mid());
2844 } else {
2845 // Plan B only allows at most one audio and one video section, so use the
2846 // first media section of that type.
2847 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002848 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002849 }
2850}
2851
deadbeef46c73892016-11-16 19:42:04 -08002852PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2853 return configuration_;
2854}
2855
deadbeef293e9262017-01-11 12:28:30 -08002856bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2857 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002858 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002859 if (IsClosed()) {
2860 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2861 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2862 }
2863
Qingsi Wanga2d60672018-04-11 16:57:45 -07002864 // According to JSEP, after setLocalDescription, changing the candidate pool
2865 // size is not allowed, and changing the set of ICE servers will not result
2866 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002867 if (local_description() && configuration.ice_candidate_pool_size !=
2868 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002869 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2870 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002871 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002872 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002873
deadbeef293e9262017-01-11 12:28:30 -08002874 // The simplest (and most future-compatible) way to tell if the config was
2875 // modified in an invalid way is to copy each property we do support
2876 // modifying, then use operator==. There are far more properties we don't
2877 // support modifying than those we do, and more could be added.
2878 RTCConfiguration modified_config = configuration_;
2879 modified_config.servers = configuration.servers;
2880 modified_config.type = configuration.type;
2881 modified_config.ice_candidate_pool_size =
2882 configuration.ice_candidate_pool_size;
2883 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002884 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002885 modified_config.ice_check_interval_strong_connectivity =
2886 configuration.ice_check_interval_strong_connectivity;
2887 modified_config.ice_check_interval_weak_connectivity =
2888 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002889 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2890 modified_config.ice_unwritable_min_checks =
2891 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002892 modified_config.stun_candidate_keepalive_interval =
2893 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002894 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002895 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002896 modified_config.active_reset_srtp_params =
2897 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002898 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002899 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002900 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2901 }
2902
Steve Anton038834f2017-07-14 15:59:59 -07002903 // Validate the modified configuration.
2904 RTCError validate_error = ValidateConfiguration(modified_config);
2905 if (!validate_error.ok()) {
2906 return SafeSetError(std::move(validate_error), error);
2907 }
2908
deadbeef293e9262017-01-11 12:28:30 -08002909 // Note that this isn't possible through chromium, since it's an unsigned
2910 // short in WebIDL.
2911 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002912 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002913 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2914 }
2915
2916 // Parse ICE servers before hopping to network thread.
2917 cricket::ServerAddresses stun_servers;
2918 std::vector<cricket::RelayServerConfig> turn_servers;
2919 RTCErrorType parse_error =
2920 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2921 if (parse_error != RTCErrorType::NONE) {
2922 return SafeSetError(parse_error, error);
2923 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002924 // Note if STUN or TURN servers were supplied.
2925 if (!stun_servers.empty()) {
2926 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2927 }
2928 if (!turn_servers.empty()) {
2929 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2930 }
deadbeef293e9262017-01-11 12:28:30 -08002931
2932 // In theory this shouldn't fail.
2933 if (!network_thread()->Invoke<bool>(
2934 RTC_FROM_HERE,
2935 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2936 stun_servers, turn_servers, modified_config.type,
2937 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002938 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002939 modified_config.turn_customizer,
2940 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002941 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002942 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2943 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002944
deadbeefd1a38b52016-12-10 13:15:33 -08002945 // As described in JSEP, calling setConfiguration with new ICE servers or
2946 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2947 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002948 if (modified_config.servers != configuration_.servers ||
2949 modified_config.type != configuration_.type ||
2950 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002951 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002952 }
skvladd1f5fda2017-02-03 16:54:05 -08002953
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002954 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002955
Zhi Huangb57e1692018-06-12 11:41:11 -07002956 if (configuration_.active_reset_srtp_params !=
2957 modified_config.active_reset_srtp_params) {
2958 transport_controller_->SetActiveResetSrtpParams(
2959 modified_config.active_reset_srtp_params);
2960 }
2961
deadbeef293e9262017-01-11 12:28:30 -08002962 configuration_ = modified_config;
2963 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002964}
2965
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002966bool PeerConnection::AddIceCandidate(
2967 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002968 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002969 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002970 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002971 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002972 return false;
2973 }
Steve Antond25da372017-11-06 14:50:29 -08002974
2975 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002976 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002977 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002978 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002979 return false;
2980 }
2981
2982 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002983 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002984 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002985 return false;
2986 }
2987
2988 bool valid = false;
2989 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2990 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002991 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002992 return false;
2993 }
2994
2995 // Add this candidate to the remote session description.
2996 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002997 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002998 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002999 return false;
3000 }
3001
3002 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003003 bool result = UseCandidate(ice_candidate);
3004 if (result) {
3005 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3006 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3007 } else {
3008 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3009 }
3010 return result;
Steve Antond25da372017-11-06 14:50:29 -08003011 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003012 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003013 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003014 return true;
3015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003016}
3017
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003018bool PeerConnection::RemoveIceCandidates(
3019 const std::vector<cricket::Candidate>& candidates) {
3020 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003021 if (IsClosed()) {
3022 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3023 return false;
3024 }
3025
Steve Antond25da372017-11-06 14:50:29 -08003026 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003027 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3028 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003029 return false;
3030 }
3031
3032 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003033 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003034 return false;
3035 }
3036
3037 size_t number_removed =
3038 mutable_remote_description()->RemoveCandidates(candidates);
3039 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003040 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003041 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003042 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003043 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003044 }
3045
3046 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003047 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3048 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003049 RTC_LOG(LS_ERROR)
3050 << "RemoveIceCandidates: Error when removing remote candidates: "
3051 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003052 }
3053 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003054}
3055
Niels Möller0c4f7be2018-05-07 14:01:37 +02003056RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003057 if (!worker_thread()->IsCurrent()) {
3058 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003059 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003060 }
3061
Niels Möller0c4f7be2018-05-07 14:01:37 +02003062 const bool has_min = bitrate.min_bitrate_bps.has_value();
3063 const bool has_start = bitrate.start_bitrate_bps.has_value();
3064 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003065 if (has_min && *bitrate.min_bitrate_bps < 0) {
3066 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3067 "min_bitrate_bps <= 0");
3068 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003069 if (has_start) {
3070 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003071 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003072 "start_bitrate_bps < min_bitrate_bps");
3073 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003074 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3075 "curent_bitrate_bps < 0");
3076 }
3077 }
3078 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003079 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003080 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003081 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003082 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3083 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3084 "max_bitrate_bps < min_bitrate_bps");
3085 } else if (*bitrate.max_bitrate_bps < 0) {
3086 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3087 "max_bitrate_bps < 0");
3088 }
3089 }
3090
zstein4b979802017-06-02 14:37:37 -07003091 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003092 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003093
3094 return RTCError::OK();
3095}
3096
Alex Narest78609d52017-10-20 10:37:47 +02003097void PeerConnection::SetBitrateAllocationStrategy(
3098 std::unique_ptr<rtc::BitrateAllocationStrategy>
3099 bitrate_allocation_strategy) {
3100 rtc::Thread* worker_thread = factory_->worker_thread();
3101 if (!worker_thread->IsCurrent()) {
3102 rtc::BitrateAllocationStrategy* strategy_raw =
3103 bitrate_allocation_strategy.release();
3104 auto functor = [this, strategy_raw]() {
3105 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003106 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003107 };
3108 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3109 return;
3110 }
3111 RTC_DCHECK(call_.get());
3112 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3113}
3114
henrika5f6bf242017-11-01 11:06:56 +01003115void PeerConnection::SetAudioPlayout(bool playout) {
3116 if (!worker_thread()->IsCurrent()) {
3117 worker_thread()->Invoke<void>(
3118 RTC_FROM_HERE,
3119 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3120 return;
3121 }
3122 auto audio_state =
3123 factory_->channel_manager()->media_engine()->GetAudioState();
3124 audio_state->SetPlayout(playout);
3125}
3126
3127void PeerConnection::SetAudioRecording(bool recording) {
3128 if (!worker_thread()->IsCurrent()) {
3129 worker_thread()->Invoke<void>(
3130 RTC_FROM_HERE,
3131 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3132 return;
3133 }
3134 auto audio_state =
3135 factory_->channel_manager()->media_engine()->GetAudioState();
3136 audio_state->SetRecording(recording);
3137}
3138
Steve Anton8c0f7a72017-10-03 10:03:10 -07003139std::unique_ptr<rtc::SSLCertificate>
3140PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003141 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3142 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003143 return nullptr;
3144 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003145 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003146}
3147
Zhi Huang70b820f2018-01-27 14:16:15 -08003148std::unique_ptr<rtc::SSLCertChain>
3149PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003150 auto audio_transceiver = GetFirstAudioTransceiver();
3151 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003152 return nullptr;
3153 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003154 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003155 audio_transceiver->internal()->channel()->transport_name());
3156}
3157
3158rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3159PeerConnection::GetFirstAudioTransceiver() const {
3160 for (auto transceiver : transceivers_) {
3161 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3162 return transceiver;
3163 }
3164 }
3165 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003166}
3167
ivoc14d5dbe2016-07-04 07:06:55 -07003168bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3169 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003170 // TODO(eladalon): It would be better to not allow negative values into PC.
3171 const size_t max_size = (max_size_bytes < 0)
3172 ? RtcEventLog::kUnlimitedOutput
3173 : rtc::saturated_cast<size_t>(max_size_bytes);
3174 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003175 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003176 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003177}
3178
Bjorn Tereliusde939432017-11-20 17:38:14 +01003179bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3180 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003181 // TODO(eladalon): In C++14, this can be done with a lambda.
3182 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003183 bool operator()() {
3184 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3185 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003186 PeerConnection* const pc;
3187 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003188 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003189 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003190 return worker_thread()->Invoke<bool>(
3191 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003192}
3193
3194void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003195 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003196 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3197}
3198
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003199const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003200 return pending_local_description_ ? pending_local_description_.get()
3201 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003202}
3203
3204const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003205 return pending_remote_description_ ? pending_remote_description_.get()
3206 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003207}
3208
deadbeeffe4a8a42016-12-20 17:56:17 -08003209const SessionDescriptionInterface* PeerConnection::current_local_description()
3210 const {
Steve Anton75737c02017-11-06 10:37:17 -08003211 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003212}
3213
3214const SessionDescriptionInterface* PeerConnection::current_remote_description()
3215 const {
Steve Anton75737c02017-11-06 10:37:17 -08003216 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003217}
3218
3219const SessionDescriptionInterface* PeerConnection::pending_local_description()
3220 const {
Steve Anton75737c02017-11-06 10:37:17 -08003221 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003222}
3223
3224const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3225 const {
Steve Anton75737c02017-11-06 10:37:17 -08003226 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003227}
3228
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003229void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003230 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003231 // Update stats here so that we have the most recent stats for tracks and
3232 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003233 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003234
Steve Anton75737c02017-11-06 10:37:17 -08003235 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003236 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003237
Steve Anton8af21862017-12-15 11:20:13 -08003238 for (auto transceiver : transceivers_) {
3239 transceiver->Stop();
3240 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003241
3242 // Ensure that all asynchronous stats requests are completed before destroying
3243 // the transport controller below.
3244 if (stats_collector_) {
3245 stats_collector_->WaitForPendingRequest();
3246 }
3247
3248 // Don't destroy BaseChannels until after stats has been cleaned up so that
3249 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003250 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003251
Qingsi Wang93a84392018-01-30 17:13:09 -08003252 // The event log is used in the transport controller, which must be outlived
3253 // by the former. CreateOffer by the peer connection is implemented
3254 // asynchronously and if the peer connection is closed without resetting the
3255 // WebRTC session description factory, the session description factory would
3256 // call the transport controller.
3257 webrtc_session_desc_factory_.reset();
3258 transport_controller_.reset();
3259
deadbeef42a42632017-03-10 15:18:00 -08003260 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003261 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3262 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003263
Steve Anton978b8762017-09-29 12:15:02 -07003264 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003265 call_.reset();
3266 // The event log must outlive call (and any other object that uses it).
3267 event_log_.reset();
3268 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003269 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003270 // The .h file says that observer can be discarded after close() returns.
3271 // Make sure this is true.
3272 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003273}
3274
Steve Antonad182762018-09-05 20:22:40 +00003275void PeerConnection::OnMessage(rtc::Message* msg) {
3276 switch (msg->message_id) {
3277 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3278 SetSessionDescriptionMsg* param =
3279 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3280 param->observer->OnSuccess();
3281 delete param;
3282 break;
3283 }
3284 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3285 SetSessionDescriptionMsg* param =
3286 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3287 param->observer->OnFailure(std::move(param->error));
3288 delete param;
3289 break;
3290 }
3291 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3292 CreateSessionDescriptionMsg* param =
3293 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3294 param->observer->OnFailure(std::move(param->error));
3295 delete param;
3296 break;
3297 }
3298 case MSG_GETSTATS: {
3299 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3300 StatsReports reports;
3301 stats_->GetStats(param->track, &reports);
3302 param->observer->OnComplete(reports);
3303 delete param;
3304 break;
3305 }
3306 case MSG_FREE_DATACHANNELS: {
3307 sctp_data_channels_to_free_.clear();
3308 break;
3309 }
3310 case MSG_REPORT_USAGE_PATTERN: {
3311 ReportUsagePattern();
3312 break;
3313 }
3314 default:
3315 RTC_NOTREACHED() << "Not implemented";
3316 break;
3317 }
3318}
3319
Steve Antonafb0bb72018-02-20 11:35:37 -08003320cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3321 RTC_DCHECK(!IsUnifiedPlan());
3322 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3323 GetAudioTransceiver()->internal()->channel());
3324 if (voice_channel) {
3325 return voice_channel->media_channel();
3326 } else {
3327 return nullptr;
3328 }
3329}
3330
3331cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3332 RTC_DCHECK(!IsUnifiedPlan());
3333 auto* video_channel = static_cast<cricket::VideoChannel*>(
3334 GetVideoTransceiver()->internal()->channel());
3335 if (video_channel) {
3336 return video_channel->media_channel();
3337 } else {
3338 return nullptr;
3339 }
3340}
3341
Steve Anton4171afb2017-11-20 10:20:22 -08003342void PeerConnection::CreateAudioReceiver(
3343 MediaStreamInterface* stream,
3344 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003345 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3346 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003347 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3348 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003349 auto* audio_receiver = new AudioRtpReceiver(
3350 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003351 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003352 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3353 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3354 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003355 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003356 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003357 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003358}
3359
Steve Anton4171afb2017-11-20 10:20:22 -08003360void PeerConnection::CreateVideoReceiver(
3361 MediaStreamInterface* stream,
3362 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003363 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3364 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003365 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3366 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003367 auto* video_receiver = new VideoRtpReceiver(
3368 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003369 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003370 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3371 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3372 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003373 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003374 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003375 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003376}
3377
deadbeef70ab1a12015-09-28 16:53:55 -07003378// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3379// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003380rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003381 const RtpSenderInfo& remote_sender_info) {
3382 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3383 if (!receiver) {
3384 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3385 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003386 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003387 }
Steve Anton4171afb2017-11-20 10:20:22 -08003388 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3389 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3390 } else {
3391 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3392 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003393 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003394}
3395
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003396void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3397 MediaStreamInterface* stream) {
3398 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003399 RTC_DCHECK(track);
3400 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003401 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003402 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003403 // We already have a sender for this track, so just change the stream_id
3404 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003405 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003406 return;
3407 }
3408
3409 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003410 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003411 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003412 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003413 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003414 // If the sender has already been configured in SDP, we call SetSsrc,
3415 // which will connect the sender to the underlying transport. This can
3416 // occur if a local session description that contains the ID of the sender
3417 // is set before AddStream is called. It can also occur if the local
3418 // session description is not changed and RemoveStream is called, and
3419 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003420 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003421 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003422 if (sender_info) {
3423 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003424 }
3425}
3426
3427// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3428// indefinitely, when we have unified plan SDP.
3429void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3430 MediaStreamInterface* stream) {
3431 RTC_DCHECK(!IsClosed());
3432 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003433 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003434 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3435 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003436 return;
3437 }
Steve Anton4171afb2017-11-20 10:20:22 -08003438 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003439}
3440
3441void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3442 MediaStreamInterface* stream) {
3443 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003444 RTC_DCHECK(track);
3445 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003446 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003447 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003448 // We already have a sender for this track, so just change the stream_id
3449 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003450 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003451 return;
3452 }
3453
3454 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003455 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003456 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003457 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003458 GetVideoTransceiver()->internal()->AddSender(new_sender);
3459 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003460 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003461 if (sender_info) {
3462 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003463 }
3464}
3465
3466void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3467 MediaStreamInterface* stream) {
3468 RTC_DCHECK(!IsClosed());
3469 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003470 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003471 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3472 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003473 return;
3474 }
Steve Anton4171afb2017-11-20 10:20:22 -08003475 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003476}
3477
Steve Antonba818672017-11-06 10:21:57 -08003478void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003479 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003480 if (ice_connection_state_ == new_state) {
3481 return;
3482 }
3483
deadbeefcbecd352015-09-23 11:50:27 -07003484 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003485 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003486 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003487 return;
3488 }
Steve Antonba818672017-11-06 10:21:57 -08003489
Mirko Bonadei675513b2017-11-09 11:09:25 +01003490 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3491 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003492 RTC_DCHECK(ice_connection_state_ !=
3493 PeerConnectionInterface::kIceConnectionClosed);
3494
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003496 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003497}
3498
3499void PeerConnection::OnIceGatheringChange(
3500 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003501 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003502 if (IsClosed()) {
3503 return;
3504 }
3505 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003506 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003507}
3508
jbauch81bf7b02017-03-25 08:31:12 -07003509void PeerConnection::OnIceCandidate(
3510 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003511 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003512 if (IsClosed()) {
3513 return;
3514 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003515 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003516 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3517 candidate->candidate().address().IsPrivateIP()) {
3518 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3519 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003520 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003521}
3522
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003523void PeerConnection::OnIceCandidatesRemoved(
3524 const std::vector<cricket::Candidate>& candidates) {
3525 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003526 if (IsClosed()) {
3527 return;
3528 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003529 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003530}
3531
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003532void PeerConnection::ChangeSignalingState(
3533 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003534 RTC_DCHECK(signaling_thread()->IsCurrent());
3535 if (signaling_state_ == signaling_state) {
3536 return;
3537 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003538 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3539 << GetSignalingStateString(signaling_state_)
3540 << " New state: "
3541 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003542 signaling_state_ = signaling_state;
3543 if (signaling_state == kClosed) {
3544 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003545 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003546 if (ice_gathering_state_ != kIceGatheringComplete) {
3547 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003548 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003549 }
3550 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003551 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003552}
3553
deadbeefeb459812015-12-15 19:24:43 -08003554void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3555 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003556 if (IsClosed()) {
3557 return;
3558 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003559 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003560 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003561}
3562
deadbeefeb459812015-12-15 19:24:43 -08003563void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3564 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003565 if (IsClosed()) {
3566 return;
3567 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003568 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003569 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003570}
3571
3572void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3573 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003574 if (IsClosed()) {
3575 return;
3576 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003577 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003578 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003579}
3580
3581void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3582 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003583 if (IsClosed()) {
3584 return;
3585 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003586 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003587 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003588}
3589
Henrik Boström31638672017-11-23 17:48:32 +01003590void PeerConnection::PostSetSessionDescriptionSuccess(
3591 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003592 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3593 signaling_thread()->Post(RTC_FROM_HERE, this,
3594 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003595}
3596
deadbeefab9b2d12015-10-14 11:33:11 -07003597void PeerConnection::PostSetSessionDescriptionFailure(
3598 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003599 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003600 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003601 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3602 msg->error = std::move(error);
3603 signaling_thread()->Post(RTC_FROM_HERE, this,
3604 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003605}
3606
3607void PeerConnection::PostCreateSessionDescriptionFailure(
3608 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003609 RTCError error) {
3610 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003611 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3612 msg->error = std::move(error);
3613 signaling_thread()->Post(RTC_FROM_HERE, this,
3614 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003615}
3616
zhihuang1c378ed2017-08-17 14:10:50 -07003617void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003618 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003619 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003620 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003621
Steve Antondcc3c022017-12-22 16:02:54 -08003622 if (IsUnifiedPlan()) {
3623 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3624 } else {
3625 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3626 }
3627
Steve Antonfa2260d2017-12-28 16:38:23 -08003628 // Intentionally unset the data channel type for RTP data channel with the
3629 // second condition. Otherwise the RTP data channels would be successfully
3630 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3631 // when building with chromium. We want to leave RTP data channels broken, so
3632 // people won't try to use them.
3633 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3634 session_options->data_channel_type = data_channel_type();
3635 }
3636
Steve Antondcc3c022017-12-22 16:02:54 -08003637 // Apply ICE restart flag and renomination flag.
3638 for (auto& options : session_options->media_description_options) {
3639 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3640 options.transport_options.enable_ice_renomination =
3641 configuration_.enable_ice_renomination;
3642 }
3643
3644 session_options->rtcp_cname = rtcp_cname_;
3645 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003646 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003647}
3648
3649void PeerConnection::GetOptionsForPlanBOffer(
3650 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3651 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003652 // Figure out transceiver directional preferences.
3653 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3654 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3655
3656 // By default, generate sendrecv/recvonly m= sections.
3657 bool recv_audio = true;
3658 bool recv_video = true;
3659
3660 // By default, only offer a new m= section if we have media to send with it.
3661 bool offer_new_audio_description = send_audio;
3662 bool offer_new_video_description = send_video;
3663 bool offer_new_data_description = HasDataChannels();
3664
3665 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003666 if (offer_answer_options.offer_to_receive_audio !=
3667 RTCOfferAnswerOptions::kUndefined) {
3668 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003669 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003670 offer_new_audio_description ||
3671 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003672 }
Steve Antondcc3c022017-12-22 16:02:54 -08003673 if (offer_answer_options.offer_to_receive_video !=
3674 RTCOfferAnswerOptions::kUndefined) {
3675 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003676 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003677 offer_new_video_description ||
3678 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003679 }
3680
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003681 absl::optional<size_t> audio_index;
3682 absl::optional<size_t> video_index;
3683 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003684 // If a current description exists, generate m= sections in the same order,
3685 // using the first audio/video/data section that appears and rejecting
3686 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003687 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003688 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003689 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003690 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3691 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3692 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003693 }
3694
zhihuang1c378ed2017-08-17 14:10:50 -07003695 // Add audio/video/data m= sections to the end if needed.
3696 if (!audio_index && offer_new_audio_description) {
3697 session_options->media_description_options.push_back(
3698 cricket::MediaDescriptionOptions(
3699 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003700 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3701 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003702 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003703 }
zhihuang1c378ed2017-08-17 14:10:50 -07003704 if (!video_index && offer_new_video_description) {
3705 session_options->media_description_options.push_back(
3706 cricket::MediaDescriptionOptions(
3707 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003708 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3709 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003710 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003711 }
zhihuang1c378ed2017-08-17 14:10:50 -07003712 if (!data_index && offer_new_data_description) {
3713 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003714 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003715 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003716 }
3717
3718 cricket::MediaDescriptionOptions* audio_media_description_options =
3719 !audio_index ? nullptr
3720 : &session_options->media_description_options[*audio_index];
3721 cricket::MediaDescriptionOptions* video_media_description_options =
3722 !video_index ? nullptr
3723 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003724
Steve Anton4171afb2017-11-20 10:20:22 -08003725 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003726 video_media_description_options,
3727 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003728}
3729
3730// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3731// and return a reference to it.
3732// Generated MIDs should be no more than 3 bytes long to take up less space in
3733// the RTP packet.
3734static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3735 RTC_DCHECK(used_mids);
3736 // We're boring: just generate MIDs 0, 1, 2, ...
3737 size_t i = 0;
3738 std::set<std::string>::iterator it;
3739 bool inserted;
3740 do {
3741 std::string mid = rtc::ToString(i++);
3742 auto insert_result = used_mids->insert(mid);
3743 it = insert_result.first;
3744 inserted = insert_result.second;
3745 } while (!inserted);
3746 return *it;
3747}
3748
3749static cricket::MediaDescriptionOptions
3750GetMediaDescriptionOptionsForTransceiver(
3751 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3752 transceiver,
3753 const std::string& mid) {
3754 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003755 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003756 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003757 // This behavior is specified in JSEP. The gist is that:
3758 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3759 // sendrecv.
3760 // 2. If the MSID is included, then it must be included in any subsequent
3761 // offer/answer exactly the same until the RtpTransceiver is stopped.
3762 if (!transceiver->stopped() &&
3763 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3764 transceiver->internal()->has_ever_been_used_to_send())) {
3765 cricket::SenderOptions sender_options;
3766 sender_options.track_id = transceiver->sender()->id();
3767 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003768 int num_send_encoding_layers =
3769 transceiver->sender()->init_send_encodings().size();
3770 sender_options.num_sim_layers =
3771 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003772 media_description_options.sender_options.push_back(sender_options);
3773 }
Steve Antondcc3c022017-12-22 16:02:54 -08003774 return media_description_options;
3775}
3776
3777void PeerConnection::GetOptionsForUnifiedPlanOffer(
3778 const RTCOfferAnswerOptions& offer_answer_options,
3779 cricket::MediaSessionOptions* session_options) {
3780 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3781 // Offers) and 5.2.2 (Subsequent Offers).
3782 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3783 const ContentInfos& local_contents =
3784 (local_description() ? local_description()->description()->contents()
3785 : ContentInfos());
3786 const ContentInfos& remote_contents =
3787 (remote_description() ? remote_description()->description()->contents()
3788 : ContentInfos());
3789 // The mline indices that can be recycled. New transceivers should reuse these
3790 // slots first.
3791 std::queue<size_t> recycleable_mline_indices;
3792 // Track the MIDs used in previous offer/answer exchanges and the current
3793 // offer so that new, unique MIDs are generated.
3794 std::set<std::string> used_mids = seen_mids_;
3795 // First, go through each media section that exists in either the local or
3796 // remote description and generate a media section in this offer for the
3797 // associated transceiver. If a media section can be recycled, generate a
3798 // default, rejected media section here that can be later overwritten.
3799 for (size_t i = 0;
3800 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3801 // Either |local_content| or |remote_content| is non-null.
3802 const ContentInfo* local_content =
3803 (i < local_contents.size() ? &local_contents[i] : nullptr);
3804 const ContentInfo* remote_content =
3805 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3806 bool had_been_rejected = (local_content && local_content->rejected) ||
3807 (remote_content && remote_content->rejected);
3808 const std::string& mid =
3809 (local_content ? local_content->name : remote_content->name);
3810 cricket::MediaType media_type =
3811 (local_content ? local_content->media_description()->type()
3812 : remote_content->media_description()->type());
3813 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3814 media_type == cricket::MEDIA_TYPE_VIDEO) {
3815 auto transceiver = GetAssociatedTransceiver(mid);
3816 RTC_CHECK(transceiver);
3817 // A media section is considered eligible for recycling if it is marked as
3818 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003819 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003820 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003821 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3822 RtpTransceiverDirection::kInactive,
3823 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003824 recycleable_mline_indices.push(i);
3825 } else {
3826 session_options->media_description_options.push_back(
3827 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3828 // CreateOffer shouldn't really cause any state changes in
3829 // PeerConnection, but we need a way to match new transceivers to new
3830 // media sections in SetLocalDescription and JSEP specifies this is done
3831 // by recording the index of the media section generated for the
3832 // transceiver in the offer.
3833 transceiver->internal()->set_mline_index(i);
3834 }
3835 } else {
3836 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003837 RTC_CHECK(GetDataMid());
3838 if (had_been_rejected || mid != *GetDataMid()) {
3839 session_options->media_description_options.push_back(
3840 GetMediaDescriptionOptionsForRejectedData(mid));
3841 } else {
3842 session_options->media_description_options.push_back(
3843 GetMediaDescriptionOptionsForActiveData(mid));
3844 }
Steve Antondcc3c022017-12-22 16:02:54 -08003845 }
3846 }
3847 // Next, look for transceivers that are newly added (that is, are not stopped
3848 // and not associated). Reuse media sections marked as recyclable first,
3849 // otherwise append to the end of the offer. New media sections should be
3850 // added in the order they were added to the PeerConnection.
3851 for (auto transceiver : transceivers_) {
3852 if (transceiver->mid() || transceiver->stopped()) {
3853 continue;
3854 }
3855 size_t mline_index;
3856 if (!recycleable_mline_indices.empty()) {
3857 mline_index = recycleable_mline_indices.front();
3858 recycleable_mline_indices.pop();
3859 session_options->media_description_options[mline_index] =
3860 GetMediaDescriptionOptionsForTransceiver(transceiver,
3861 AllocateMid(&used_mids));
3862 } else {
3863 mline_index = session_options->media_description_options.size();
3864 session_options->media_description_options.push_back(
3865 GetMediaDescriptionOptionsForTransceiver(transceiver,
3866 AllocateMid(&used_mids)));
3867 }
3868 // See comment above for why CreateOffer changes the transceiver's state.
3869 transceiver->internal()->set_mline_index(mline_index);
3870 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003871 // Lastly, add a m-section if we have local data channels and an m section
3872 // does not already exist.
3873 if (!GetDataMid() && HasDataChannels()) {
3874 session_options->media_description_options.push_back(
3875 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3876 }
Steve Antondcc3c022017-12-22 16:02:54 -08003877}
3878
3879void PeerConnection::GetOptionsForAnswer(
3880 const RTCOfferAnswerOptions& offer_answer_options,
3881 cricket::MediaSessionOptions* session_options) {
3882 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3883
3884 if (IsUnifiedPlan()) {
3885 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3886 } else {
3887 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3888 }
3889
Steve Antonfa2260d2017-12-28 16:38:23 -08003890 // Intentionally unset the data channel type for RTP data channel. Otherwise
3891 // the RTP data channels would be successfully negotiated by default and the
3892 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3893 // We want to leave RTP data channels broken, so people won't try to use them.
3894 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3895 session_options->data_channel_type = data_channel_type();
3896 }
3897
Steve Antondcc3c022017-12-22 16:02:54 -08003898 // Apply ICE renomination flag.
3899 for (auto& options : session_options->media_description_options) {
3900 options.transport_options.enable_ice_renomination =
3901 configuration_.enable_ice_renomination;
3902 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003903
3904 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003905 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003906 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003907}
3908
Steve Antondcc3c022017-12-22 16:02:54 -08003909void PeerConnection::GetOptionsForPlanBAnswer(
3910 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003911 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003912 // Figure out transceiver directional preferences.
3913 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3914 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3915
3916 // By default, generate sendrecv/recvonly m= sections. The direction is also
3917 // restricted by the direction in the offer.
3918 bool recv_audio = true;
3919 bool recv_video = true;
3920
3921 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003922 if (offer_answer_options.offer_to_receive_audio !=
3923 RTCOfferAnswerOptions::kUndefined) {
3924 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003925 }
Steve Antondcc3c022017-12-22 16:02:54 -08003926 if (offer_answer_options.offer_to_receive_video !=
3927 RTCOfferAnswerOptions::kUndefined) {
3928 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003929 }
3930
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003931 absl::optional<size_t> audio_index;
3932 absl::optional<size_t> video_index;
3933 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003934
3935 // Generate m= sections that match those in the offer.
3936 // Note that mediasession.cc will handle intersection our preferred
3937 // direction with the offered direction.
3938 GenerateMediaDescriptionOptions(
3939 remote_description(),
3940 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3941 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3942 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003943
3944 cricket::MediaDescriptionOptions* audio_media_description_options =
3945 !audio_index ? nullptr
3946 : &session_options->media_description_options[*audio_index];
3947 cricket::MediaDescriptionOptions* video_media_description_options =
3948 !video_index ? nullptr
3949 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003950
Steve Anton4171afb2017-11-20 10:20:22 -08003951 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003952 video_media_description_options,
3953 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003954}
zhihuangaf388472016-11-02 16:49:48 -07003955
Steve Antondcc3c022017-12-22 16:02:54 -08003956void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3957 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3958 cricket::MediaSessionOptions* session_options) {
3959 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3960 // Answers) and 5.3.2 (Subsequent Answers).
3961 RTC_DCHECK(remote_description());
3962 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3963 for (const ContentInfo& content :
3964 remote_description()->description()->contents()) {
3965 cricket::MediaType media_type = content.media_description()->type();
3966 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3967 media_type == cricket::MEDIA_TYPE_VIDEO) {
3968 auto transceiver = GetAssociatedTransceiver(content.name);
3969 RTC_CHECK(transceiver);
3970 session_options->media_description_options.push_back(
3971 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3972 } else {
3973 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003974 // Reject all data sections if data channels are disabled.
3975 // Reject a data section if it has already been rejected.
3976 // Reject all data sections except for the first one.
3977 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3978 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003979 session_options->media_description_options.push_back(
3980 GetMediaDescriptionOptionsForRejectedData(content.name));
3981 } else {
3982 session_options->media_description_options.push_back(
3983 GetMediaDescriptionOptionsForActiveData(content.name));
3984 }
Steve Antondcc3c022017-12-22 16:02:54 -08003985 }
3986 }
htaa2a49d92016-03-04 02:51:39 -08003987}
3988
zhihuang1c378ed2017-08-17 14:10:50 -07003989void PeerConnection::GenerateMediaDescriptionOptions(
3990 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003991 RtpTransceiverDirection audio_direction,
3992 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003993 absl::optional<size_t>* audio_index,
3994 absl::optional<size_t>* video_index,
3995 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003996 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003997 for (const cricket::ContentInfo& content :
3998 session_desc->description()->contents()) {
3999 if (IsAudioContent(&content)) {
4000 // If we already have an audio m= section, reject this extra one.
4001 if (*audio_index) {
4002 session_options->media_description_options.push_back(
4003 cricket::MediaDescriptionOptions(
4004 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004005 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004006 } else {
4007 session_options->media_description_options.push_back(
4008 cricket::MediaDescriptionOptions(
4009 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004010 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004011 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004012 }
4013 } else if (IsVideoContent(&content)) {
4014 // If we already have an video m= section, reject this extra one.
4015 if (*video_index) {
4016 session_options->media_description_options.push_back(
4017 cricket::MediaDescriptionOptions(
4018 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004019 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004020 } else {
4021 session_options->media_description_options.push_back(
4022 cricket::MediaDescriptionOptions(
4023 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004024 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004025 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004026 }
4027 } else {
4028 RTC_DCHECK(IsDataContent(&content));
4029 // If we already have an data m= section, reject this extra one.
4030 if (*data_index) {
4031 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004032 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004033 } else {
4034 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004035 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004036 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004037 }
4038 }
htaa2a49d92016-03-04 02:51:39 -08004039 }
deadbeefab9b2d12015-10-14 11:33:11 -07004040}
4041
Steve Antonfa2260d2017-12-28 16:38:23 -08004042cricket::MediaDescriptionOptions
4043PeerConnection::GetMediaDescriptionOptionsForActiveData(
4044 const std::string& mid) const {
4045 // Direction for data sections is meaningless, but legacy endpoints might
4046 // expect sendrecv.
4047 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4048 RtpTransceiverDirection::kSendRecv,
4049 /*stopped=*/false);
4050 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4051 return options;
4052}
4053
4054cricket::MediaDescriptionOptions
4055PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4056 const std::string& mid) const {
4057 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4058 RtpTransceiverDirection::kInactive,
4059 /*stopped=*/true);
4060 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4061 return options;
4062}
4063
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004064absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004065 switch (data_channel_type_) {
4066 case cricket::DCT_RTP:
4067 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004068 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004069 }
4070 return rtp_data_channel_->content_name();
4071 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004072 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004073 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004074 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004075 }
4076}
4077
Steve Anton4171afb2017-11-20 10:20:22 -08004078void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4079 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4080 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004081 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004082}
4083
Steve Anton4171afb2017-11-20 10:20:22 -08004084void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004085 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004086 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004087 cricket::MediaType media_type,
4088 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004089 RTC_DCHECK(!IsUnifiedPlan());
4090
Steve Anton4171afb2017-11-20 10:20:22 -08004091 std::vector<RtpSenderInfo>* current_senders =
4092 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004093
Steve Anton4171afb2017-11-20 10:20:22 -08004094 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004095 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004096 for (auto sender_it = current_senders->begin();
4097 sender_it != current_senders->end();
4098 /* incremented manually */) {
4099 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004100 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004101 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004102 std::string params_stream_id;
4103 if (params) {
4104 params_stream_id =
4105 (!params->first_stream_id().empty() ? params->first_stream_id()
4106 : kDefaultStreamId);
4107 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004108 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004109 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004110 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004111 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004112 sender_exists) {
4113 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004114 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004115 OnRemoteSenderRemoved(info, media_type);
4116 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004117 }
4118 }
4119
Steve Anton4171afb2017-11-20 10:20:22 -08004120 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004121 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004122 if (!params.has_ssrcs()) {
4123 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4124 // sender, this means it is coming from a Unified Plan endpoint,so we just
4125 // create a default.
4126 default_sender_needed = true;
4127 break;
4128 }
4129
Seth Hampson845e8782018-03-02 11:34:10 -08004130 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004131 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004132 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4133 // not supported in Plan B, we just take the first here and create the
4134 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004135 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004136 (!params.first_stream_id().empty() ? params.first_stream_id()
4137 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004138 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004139 uint32_t ssrc = params.first_ssrc();
4140
4141 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004142 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004143 if (!stream) {
4144 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004145 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004146 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004147 remote_streams_->AddStream(stream);
4148 new_streams->AddStream(stream);
4149 }
4150
Steve Anton4171afb2017-11-20 10:20:22 -08004151 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004152 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004153 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004154 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004155 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004156 }
4157 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004158
Steve Anton4171afb2017-11-20 10:20:22 -08004159 // Add default sender if necessary.
4160 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004161 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004162 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004163 if (!default_stream) {
4164 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004165 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004166 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004167 remote_streams_->AddStream(default_stream);
4168 new_streams->AddStream(default_stream);
4169 }
Steve Anton4171afb2017-11-20 10:20:22 -08004170 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4171 ? kDefaultAudioSenderId
4172 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004173 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004174 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004175 if (!default_sender_info) {
4176 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004177 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004178 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004179 }
4180 }
deadbeefab9b2d12015-10-14 11:33:11 -07004181}
4182
Steve Anton4171afb2017-11-20 10:20:22 -08004183void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4184 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004185 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4186 << " receiver for track_id=" << sender_info.sender_id
4187 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004188
Steve Anton3d954a62018-04-02 11:27:23 -07004189 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004190 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004191 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004192 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004193 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004194 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004195 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004196 }
4197}
4198
Steve Anton4171afb2017-11-20 10:20:22 -08004199void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4200 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004201 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4202 << " receiver for track_id=" << sender_info.sender_id
4203 << " and stream_id=" << sender_info.stream_id;
4204
Seth Hampson845e8782018-03-02 11:34:10 -08004205 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004206
Henrik Boström933d8b02017-10-10 10:05:16 -07004207 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004208 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004209 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4210 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004211 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004212 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004213 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004214 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004215 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004216 }
4217 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004218 // Stopping or destroying a VideoRtpReceiver will end the
4219 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004220 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004221 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004222 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004223 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004224 // There's no guarantee the track is still available, e.g. the track may
4225 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004226 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004227 }
4228 } else {
nisseede5da42017-01-12 05:15:36 -08004229 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004230 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004231 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004232 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004233 }
deadbeefab9b2d12015-10-14 11:33:11 -07004234}
4235
4236void PeerConnection::UpdateEndedRemoteMediaStreams() {
4237 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4238 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4239 MediaStreamInterface* stream = remote_streams_->at(i);
4240 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4241 streams_to_remove.push_back(stream);
4242 }
4243 }
4244
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004245 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004246 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004247 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004248 }
4249}
4250
Steve Anton4171afb2017-11-20 10:20:22 -08004251void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004252 const std::vector<cricket::StreamParams>& streams,
4253 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004254 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004255
Seth Hampson845e8782018-03-02 11:34:10 -08004256 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004257 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004258 for (auto sender_it = current_senders->begin();
4259 sender_it != current_senders->end();
4260 /* incremented manually */) {
4261 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004262 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004263 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4264 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004265 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004266 OnLocalSenderRemoved(info, media_type);
4267 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004268 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004269 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004270 }
4271 }
4272
Steve Anton4171afb2017-11-20 10:20:22 -08004273 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004274 for (const cricket::StreamParams& params : streams) {
4275 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004276 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004277 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004278 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004279 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004280 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004281 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004282 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004283 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004284 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004285 }
4286 }
4287}
4288
Steve Anton4171afb2017-11-20 10:20:22 -08004289void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4290 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004291 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004292 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004293 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004294 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4295 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004296 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004297 return;
4298 }
4299
deadbeeffac06552015-11-25 11:26:01 -08004300 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004301 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004302 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004303 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004304 }
deadbeeffac06552015-11-25 11:26:01 -08004305
Seth Hampson5b4f0752018-04-02 16:31:36 -07004306 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004307 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004308}
4309
Steve Anton4171afb2017-11-20 10:20:22 -08004310void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4311 cricket::MediaType media_type) {
4312 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004313 if (!sender) {
4314 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004315 // SessionDescriptions has been renegotiated.
4316 return;
4317 }
deadbeeffac06552015-11-25 11:26:01 -08004318
4319 // A sender has been removed from the SessionDescription but it's still
4320 // associated with the PeerConnection. This only occurs if the SDP doesn't
4321 // match with the calls to CreateSender, AddStream and RemoveStream.
4322 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004323 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004324 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004325 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004326 }
deadbeeffac06552015-11-25 11:26:01 -08004327
Steve Anton4171afb2017-11-20 10:20:22 -08004328 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004329}
4330
4331void PeerConnection::UpdateLocalRtpDataChannels(
4332 const cricket::StreamParamsVec& streams) {
4333 std::vector<std::string> existing_channels;
4334
4335 // Find new and active data channels.
4336 for (const cricket::StreamParams& params : streams) {
4337 // |it->sync_label| is actually the data channel label. The reason is that
4338 // we use the same naming of data channels as we do for
4339 // MediaStreams and Tracks.
4340 // For MediaStreams, the sync_label is the MediaStream label and the
4341 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004342 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004343 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004344 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004345 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004346 continue;
4347 }
4348 // Set the SSRC the data channel should use for sending.
4349 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4350 existing_channels.push_back(data_channel_it->first);
4351 }
4352
4353 UpdateClosingRtpDataChannels(existing_channels, true);
4354}
4355
4356void PeerConnection::UpdateRemoteRtpDataChannels(
4357 const cricket::StreamParamsVec& streams) {
4358 std::vector<std::string> existing_channels;
4359
4360 // Find new and active data channels.
4361 for (const cricket::StreamParams& params : streams) {
4362 // The data channel label is either the mslabel or the SSRC if the mslabel
4363 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004364 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004365 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004366 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004367 auto data_channel_it = rtp_data_channels_.find(label);
4368 if (data_channel_it == rtp_data_channels_.end()) {
4369 // This is a new data channel.
4370 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4371 } else {
4372 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4373 }
4374 existing_channels.push_back(label);
4375 }
4376
4377 UpdateClosingRtpDataChannels(existing_channels, false);
4378}
4379
4380void PeerConnection::UpdateClosingRtpDataChannels(
4381 const std::vector<std::string>& active_channels,
4382 bool is_local_update) {
4383 auto it = rtp_data_channels_.begin();
4384 while (it != rtp_data_channels_.end()) {
4385 DataChannel* data_channel = it->second;
4386 if (std::find(active_channels.begin(), active_channels.end(),
4387 data_channel->label()) != active_channels.end()) {
4388 ++it;
4389 continue;
4390 }
4391
4392 if (is_local_update) {
4393 data_channel->SetSendSsrc(0);
4394 } else {
4395 data_channel->RemotePeerRequestClose();
4396 }
4397
4398 if (data_channel->state() == DataChannel::kClosed) {
4399 rtp_data_channels_.erase(it);
4400 it = rtp_data_channels_.begin();
4401 } else {
4402 ++it;
4403 }
4404 }
4405}
4406
4407void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4408 uint32_t remote_ssrc) {
4409 rtc::scoped_refptr<DataChannel> channel(
4410 InternalCreateDataChannel(label, nullptr));
4411 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004412 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004413 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004414 return;
4415 }
4416 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004417 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4418 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004419 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004420}
4421
4422rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4423 const std::string& label,
4424 const InternalDataChannelInit* config) {
4425 if (IsClosed()) {
4426 return nullptr;
4427 }
Steve Anton75737c02017-11-06 10:37:17 -08004428 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004429 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004430 << "InternalCreateDataChannel: Data is not supported in this call.";
4431 return nullptr;
4432 }
4433 InternalDataChannelInit new_config =
4434 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004435 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004436 if (new_config.id < 0) {
4437 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004438 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004439 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004440 RTC_LOG(LS_ERROR)
4441 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004442 return nullptr;
4443 }
4444 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004445 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004446 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004447 return nullptr;
4448 }
4449 }
4450
Steve Anton75737c02017-11-06 10:37:17 -08004451 rtc::scoped_refptr<DataChannel> channel(
4452 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004453 if (!channel) {
4454 sid_allocator_.ReleaseSid(new_config.id);
4455 return nullptr;
4456 }
4457
4458 if (channel->data_channel_type() == cricket::DCT_RTP) {
4459 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004460 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4461 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004462 return nullptr;
4463 }
4464 rtp_data_channels_[channel->label()] = channel;
4465 } else {
4466 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4467 sctp_data_channels_.push_back(channel);
4468 channel->SignalClosed.connect(this,
4469 &PeerConnection::OnSctpDataChannelClosed);
4470 }
4471
Steve Anton2d8609c2018-01-23 16:38:46 -08004472 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004473 return channel;
4474}
4475
4476bool PeerConnection::HasDataChannels() const {
4477 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4478}
4479
4480void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4481 for (const auto& channel : sctp_data_channels_) {
4482 if (channel->id() < 0) {
4483 int sid;
4484 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004485 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004486 continue;
4487 }
4488 channel->SetSctpSid(sid);
4489 }
4490 }
4491}
4492
4493void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004494 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004495 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4496 ++it) {
4497 if (it->get() == channel) {
4498 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004499 // After the closing procedure is done, it's safe to use this ID for
4500 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004501 sid_allocator_.ReleaseSid(channel->id());
4502 }
deadbeefbd292462015-12-14 18:15:29 -08004503 // Since this method is triggered by a signal from the DataChannel,
4504 // we can't free it directly here; we need to free it asynchronously.
4505 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004506 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004507 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4508 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004509 return;
4510 }
4511 }
4512}
4513
deadbeefab9b2d12015-10-14 11:33:11 -07004514void PeerConnection::OnDataChannelDestroyed() {
4515 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4516 // DataChannel may callback to us and try to modify the list.
4517 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4518 temp_rtp_dcs.swap(rtp_data_channels_);
4519 for (const auto& kv : temp_rtp_dcs) {
4520 kv.second->OnTransportChannelDestroyed();
4521 }
4522
4523 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4524 temp_sctp_dcs.swap(sctp_data_channels_);
4525 for (const auto& channel : temp_sctp_dcs) {
4526 channel->OnTransportChannelDestroyed();
4527 }
4528}
4529
4530void PeerConnection::OnDataChannelOpenMessage(
4531 const std::string& label,
4532 const InternalDataChannelInit& config) {
4533 rtc::scoped_refptr<DataChannel> channel(
4534 InternalCreateDataChannel(label, &config));
4535 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004536 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004537 return;
4538 }
4539
deadbeefa601f5c2016-06-06 14:27:39 -07004540 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4541 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004542 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004543 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004544}
4545
Steve Anton4171afb2017-11-20 10:20:22 -08004546rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4547PeerConnection::GetAudioTransceiver() const {
4548 // This method only works with Plan B SDP, where there is a single
4549 // audio/video transceiver.
4550 RTC_DCHECK(!IsUnifiedPlan());
4551 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004552 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004553 return transceiver;
4554 }
4555 }
4556 RTC_NOTREACHED();
4557 return nullptr;
4558}
4559
4560rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4561PeerConnection::GetVideoTransceiver() const {
4562 // This method only works with Plan B SDP, where there is a single
4563 // audio/video transceiver.
4564 RTC_DCHECK(!IsUnifiedPlan());
4565 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004566 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004567 return transceiver;
4568 }
4569 }
4570 RTC_NOTREACHED();
4571 return nullptr;
4572}
4573
4574// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4575// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004576bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004577 switch (type) {
4578 case cricket::MEDIA_TYPE_AUDIO:
4579 return !GetAudioTransceiver()->internal()->senders().empty();
4580 case cricket::MEDIA_TYPE_VIDEO:
4581 return !GetVideoTransceiver()->internal()->senders().empty();
4582 case cricket::MEDIA_TYPE_DATA:
4583 return false;
4584 }
4585 RTC_NOTREACHED();
4586 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004587}
4588
Steve Anton4171afb2017-11-20 10:20:22 -08004589rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4590PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4591 for (auto transceiver : transceivers_) {
4592 for (auto sender : transceiver->internal()->senders()) {
4593 if (sender->track() == track) {
4594 return sender;
4595 }
4596 }
4597 }
4598 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004599}
4600
Steve Anton4171afb2017-11-20 10:20:22 -08004601rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4602PeerConnection::FindSenderById(const std::string& sender_id) const {
4603 for (auto transceiver : transceivers_) {
4604 for (auto sender : transceiver->internal()->senders()) {
4605 if (sender->id() == sender_id) {
4606 return sender;
4607 }
4608 }
4609 }
4610 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004611}
4612
Steve Anton4171afb2017-11-20 10:20:22 -08004613rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4614PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4615 for (auto transceiver : transceivers_) {
4616 for (auto receiver : transceiver->internal()->receivers()) {
4617 if (receiver->id() == receiver_id) {
4618 return receiver;
4619 }
4620 }
4621 }
4622 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004623}
4624
Steve Anton4171afb2017-11-20 10:20:22 -08004625std::vector<PeerConnection::RtpSenderInfo>*
4626PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4627 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4628 media_type == cricket::MEDIA_TYPE_VIDEO);
4629 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4630 ? &remote_audio_sender_infos_
4631 : &remote_video_sender_infos_;
4632}
4633
4634std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004635 cricket::MediaType media_type) {
4636 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4637 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004638 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4639 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004640}
4641
Steve Anton4171afb2017-11-20 10:20:22 -08004642const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4643 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004644 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004645 const std::string sender_id) const {
4646 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004647 if (sender_info.stream_id == stream_id &&
4648 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004649 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004650 }
4651 }
4652 return nullptr;
4653}
4654
4655DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4656 for (const auto& channel : sctp_data_channels_) {
4657 if (channel->id() == sid) {
4658 return channel;
4659 }
4660 }
4661 return nullptr;
4662}
4663
deadbeef91dd5672016-05-18 16:55:30 -07004664bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004665 const cricket::ServerAddresses& stun_servers,
4666 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004667 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004668 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004669 // To handle both internal and externally created port allocator, we will
4670 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004671 port_allocator_flags_ = port_allocator_->flags();
4672 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4673 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4674 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004675 // If the disable-IPv6 flag was specified, we'll not override it
4676 // by experiment.
4677 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004678 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004679 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4680 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004681 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004682 }
4683
zhihuangb09b3f92017-03-07 14:40:51 -08004684 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004685 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004686 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004687 }
4688
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004689 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004690 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004691 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004692 }
4693
honghaiz60347052016-05-31 18:29:12 -07004694 if (configuration.candidate_network_policy ==
4695 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004696 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004697 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004698 }
4699
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004700 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004701 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004702 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4703 }
4704
Qingsi Wanga2d60672018-04-11 16:57:45 -07004705 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004706 // No step delay is used while allocating ports.
4707 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4708 port_allocator_->set_candidate_filter(
4709 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004710 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004711
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004712 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004713 for (auto& turn_server : turn_servers_copy) {
4714 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004715 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004716 // Call this last since it may create pooled allocator sessions using the
4717 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004718 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004719 stun_servers, std::move(turn_servers_copy),
4720 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4721 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004722 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004723 return true;
4724}
4725
deadbeef91dd5672016-05-18 16:55:30 -07004726bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004727 const cricket::ServerAddresses& stun_servers,
4728 const std::vector<cricket::RelayServerConfig>& turn_servers,
4729 IceTransportsType type,
4730 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004731 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004732 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004733 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004734 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004735 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004736 // According to JSEP, after setLocalDescription, changing the candidate pool
4737 // size is not allowed, and changing the set of ICE servers will not result
4738 // in new candidates being gathered.
4739 if (local_description()) {
4740 port_allocator_->FreezeCandidatePool();
4741 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004742 // Add the custom tls turn servers if they exist.
4743 auto turn_servers_copy = turn_servers;
4744 for (auto& turn_server : turn_servers_copy) {
4745 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4746 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004747 // Call this last since it may create pooled allocator sessions using the
4748 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004749 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004750 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4751 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004752}
4753
Steve Antonba818672017-11-06 10:21:57 -08004754cricket::ChannelManager* PeerConnection::channel_manager() const {
4755 return factory_->channel_manager();
4756}
4757
Elad Alon99c3fe52017-10-13 16:29:40 +02004758bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004759 std::unique_ptr<RtcEventLogOutput> output,
4760 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004761 if (!event_log_) {
4762 return false;
4763 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004764 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004765}
4766
4767void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004768 if (event_log_) {
4769 event_log_->StopLogging();
4770 }
ivoc14d5dbe2016-07-04 07:06:55 -07004771}
nisseeaabdf62017-05-05 02:23:02 -07004772
Steve Anton75737c02017-11-06 10:37:17 -08004773cricket::BaseChannel* PeerConnection::GetChannel(
4774 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004775 for (auto transceiver : transceivers_) {
4776 cricket::BaseChannel* channel = transceiver->internal()->channel();
4777 if (channel && channel->content_name() == content_name) {
4778 return channel;
4779 }
Steve Anton75737c02017-11-06 10:37:17 -08004780 }
4781 if (rtp_data_channel() &&
4782 rtp_data_channel()->content_name() == content_name) {
4783 return rtp_data_channel();
4784 }
4785 return nullptr;
4786}
4787
4788bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4789 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004790 RTC_LOG(LS_INFO)
4791 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004792 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004793 return false;
4794 }
4795 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004796 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004797 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004798 return false;
4799 }
4800
Zhi Huange830e682018-03-30 10:48:35 -07004801 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4802 if (dtls_role) {
4803 *role = *dtls_role;
4804 return true;
4805 }
4806 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004807}
4808
4809bool PeerConnection::GetSslRole(const std::string& content_name,
4810 rtc::SSLRole* role) {
4811 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004812 RTC_LOG(LS_INFO)
4813 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004814 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004815 return false;
4816 }
4817
Zhi Huange830e682018-03-30 10:48:35 -07004818 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4819 if (dtls_role) {
4820 *role = *dtls_role;
4821 return true;
4822 }
4823 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004824}
4825
Steve Antonf8470812017-12-04 10:46:21 -08004826void PeerConnection::SetSessionError(SessionError error,
4827 const std::string& error_desc) {
4828 RTC_DCHECK_RUN_ON(signaling_thread());
4829 if (error != session_error_) {
4830 session_error_ = error;
4831 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004832 }
4833}
4834
Zhi Huange830e682018-03-30 10:48:35 -07004835RTCError PeerConnection::UpdateSessionState(
4836 SdpType type,
4837 cricket::ContentSource source,
4838 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004839 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004840
4841 // If there's already a pending error then no state transition should happen.
4842 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004843 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004844
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004845 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004846 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004847 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004848 }
4849
4850 // Update the signaling state according to the specified state machine (see
4851 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004852 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004853 ChangeSignalingState(source == cricket::CS_LOCAL
4854 ? PeerConnectionInterface::kHaveLocalOffer
4855 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004856 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004857 ChangeSignalingState(source == cricket::CS_LOCAL
4858 ? PeerConnectionInterface::kHaveLocalPrAnswer
4859 : PeerConnectionInterface::kHaveRemotePrAnswer);
4860 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004861 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004862 ChangeSignalingState(PeerConnectionInterface::kStable);
4863 }
4864
4865 // Update internal objects according to the session description's media
4866 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004867 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004868 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004869 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004870 }
4871
Steve Anton8a006912017-12-04 15:25:56 -08004872 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004873}
4874
Steve Anton8a006912017-12-04 15:25:56 -08004875RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004876 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004877 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004878 const SessionDescriptionInterface* sdesc =
4879 (source == cricket::CS_LOCAL ? local_description()
4880 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004881 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004882
4883 // Push down the new SDP media section for each audio/video transceiver.
4884 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004885 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004886 FindMediaSectionForTransceiver(transceiver, sdesc);
4887 cricket::BaseChannel* channel = transceiver->internal()->channel();
4888 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004889 continue;
4890 }
4891 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004892 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004893 if (!content_desc) {
4894 continue;
4895 }
4896 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004897 bool success = (source == cricket::CS_LOCAL)
4898 ? channel->SetLocalContent(content_desc, type, &error)
4899 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004900 if (!success) {
4901 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4902 }
4903 }
4904
4905 // If using the RtpDataChannel, push down the new SDP section for it too.
4906 if (rtp_data_channel_) {
4907 const ContentInfo* data_content =
4908 cricket::GetFirstDataContent(sdesc->description());
4909 if (data_content && !data_content->rejected) {
4910 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004911 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004912 if (data_desc) {
4913 std::string error;
4914 bool success =
4915 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004916 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004917 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004918 if (!success) {
4919 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4920 std::move(error));
4921 }
Steve Anton75737c02017-11-06 10:37:17 -08004922 }
4923 }
4924 }
Steve Antoned10bd92017-12-05 10:52:59 -08004925
Steve Anton75737c02017-11-06 10:37:17 -08004926 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4927 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4928 if (sctp_transport_ && local_description() && remote_description() &&
4929 cricket::GetFirstDataContent(local_description()->description()) &&
4930 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004931 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004932 RTC_FROM_HERE,
4933 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004934 if (!success) {
4935 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4936 "Failed to push down SCTP parameters.");
4937 }
Steve Anton75737c02017-11-06 10:37:17 -08004938 }
Steve Antoned10bd92017-12-05 10:52:59 -08004939
Steve Anton8a006912017-12-04 15:25:56 -08004940 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004941}
4942
4943bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4944 RTC_DCHECK(network_thread()->IsCurrent());
4945 RTC_DCHECK(local_description());
4946 RTC_DCHECK(remote_description());
4947 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4948 // When we support "max-message-size", that would also be pushed down here.
4949 return sctp_transport_->Start(
4950 GetSctpPort(local_description()->description()),
4951 GetSctpPort(remote_description()->description()));
4952}
4953
Steve Anton8a006912017-12-04 15:25:56 -08004954RTCError PeerConnection::PushdownTransportDescription(
4955 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004956 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004957 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004958
Zhi Huange830e682018-03-30 10:48:35 -07004959 if (source == cricket::CS_LOCAL) {
4960 const SessionDescriptionInterface* sdesc = local_description();
4961 RTC_DCHECK(sdesc);
4962 return transport_controller_->SetLocalDescription(type,
4963 sdesc->description());
4964 } else {
4965 const SessionDescriptionInterface* sdesc = remote_description();
4966 RTC_DCHECK(sdesc);
4967 return transport_controller_->SetRemoteDescription(type,
4968 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004969 }
Steve Anton75737c02017-11-06 10:37:17 -08004970}
4971
4972bool PeerConnection::GetTransportDescription(
4973 const SessionDescription* description,
4974 const std::string& content_name,
4975 cricket::TransportDescription* tdesc) {
4976 if (!description || !tdesc) {
4977 return false;
4978 }
4979 const TransportInfo* transport_info =
4980 description->GetTransportInfoByName(content_name);
4981 if (!transport_info) {
4982 return false;
4983 }
4984 *tdesc = transport_info->description;
4985 return true;
4986}
4987
Steve Anton75737c02017-11-06 10:37:17 -08004988cricket::IceConfig PeerConnection::ParseIceConfig(
4989 const PeerConnectionInterface::RTCConfiguration& config) const {
4990 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004991 switch (config.continual_gathering_policy) {
4992 case PeerConnectionInterface::GATHER_ONCE:
4993 gathering_policy = cricket::GATHER_ONCE;
4994 break;
4995 case PeerConnectionInterface::GATHER_CONTINUALLY:
4996 gathering_policy = cricket::GATHER_CONTINUALLY;
4997 break;
4998 default:
4999 RTC_NOTREACHED();
5000 gathering_policy = cricket::GATHER_ONCE;
5001 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005002
Steve Anton75737c02017-11-06 10:37:17 -08005003 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005004 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5005 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005006 ice_config.prioritize_most_likely_candidate_pairs =
5007 config.prioritize_most_likely_ice_candidate_pairs;
5008 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005009 RTCConfigurationToIceConfigOptionalInt(
5010 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005011 ice_config.continual_gathering_policy = gathering_policy;
5012 ice_config.presume_writable_when_fully_relayed =
5013 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005014 ice_config.ice_check_interval_strong_connectivity =
5015 config.ice_check_interval_strong_connectivity;
5016 ice_config.ice_check_interval_weak_connectivity =
5017 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005018 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005019 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005020 ice_config.regather_all_networks_interval_range =
5021 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005022 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005023 return ice_config;
5024}
5025
Steve Anton75737c02017-11-06 10:37:17 -08005026bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5027 std::string* track_id) {
5028 if (!local_description()) {
5029 return false;
5030 }
5031 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5032 track_id);
5033}
5034
5035bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5036 std::string* track_id) {
5037 if (!remote_description()) {
5038 return false;
5039 }
5040 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5041 track_id);
5042}
5043
5044bool PeerConnection::SendData(const cricket::SendDataParams& params,
5045 const rtc::CopyOnWriteBuffer& payload,
5046 cricket::SendDataResult* result) {
5047 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005048 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005049 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005050 return false;
5051 }
5052 return rtp_data_channel_
5053 ? rtp_data_channel_->SendData(params, payload, result)
5054 : network_thread()->Invoke<bool>(
5055 RTC_FROM_HERE,
5056 Bind(&cricket::SctpTransportInternal::SendData,
5057 sctp_transport_.get(), params, payload, result));
5058}
5059
5060bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5061 if (!rtp_data_channel_ && !sctp_transport_) {
5062 // Don't log an error here, because DataChannels are expected to call
5063 // ConnectDataChannel in this state. It's the only way to initially tell
5064 // whether or not the underlying transport is ready.
5065 return false;
5066 }
5067 if (rtp_data_channel_) {
5068 rtp_data_channel_->SignalReadyToSendData.connect(
5069 webrtc_data_channel, &DataChannel::OnChannelReady);
5070 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5071 &DataChannel::OnDataReceived);
5072 } else {
5073 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5074 &DataChannel::OnChannelReady);
5075 SignalSctpDataReceived.connect(webrtc_data_channel,
5076 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005077 SignalSctpClosingProcedureStartedRemotely.connect(
5078 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5079 SignalSctpClosingProcedureComplete.connect(
5080 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005081 }
5082 return true;
5083}
5084
5085void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5086 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005087 RTC_LOG(LS_ERROR)
5088 << "DisconnectDataChannel called when rtp_data_channel_ and "
5089 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005090 return;
5091 }
5092 if (rtp_data_channel_) {
5093 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5094 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5095 } else {
5096 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5097 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005098 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5099 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005100 }
5101}
5102
5103void PeerConnection::AddSctpDataStream(int sid) {
5104 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005105 RTC_LOG(LS_ERROR)
5106 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005107 return;
5108 }
5109 network_thread()->Invoke<void>(
5110 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5111 sctp_transport_.get(), sid));
5112}
5113
5114void PeerConnection::RemoveSctpDataStream(int sid) {
5115 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005116 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005117 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005118 return;
5119 }
5120 network_thread()->Invoke<void>(
5121 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5122 sctp_transport_.get(), sid));
5123}
5124
5125bool PeerConnection::ReadyToSendData() const {
5126 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5127 sctp_ready_to_send_data_;
5128}
5129
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005130absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005131 if (sctp_mid_ && transport_controller_) {
5132 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5133 if (dtls_transport) {
5134 return dtls_transport->transport_name();
5135 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005136 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005137 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005138 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005139}
5140
Qingsi Wang72a43a12018-02-20 16:03:18 -08005141cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5142 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005143 network_thread()->Invoke<void>(
5144 RTC_FROM_HERE,
5145 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5146 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005147 return candidate_states_list;
5148}
5149
Steve Anton5dfde182018-02-06 10:34:40 -08005150std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5151 const {
5152 std::map<std::string, std::string> transport_names_by_mid;
5153 for (auto transceiver : transceivers_) {
5154 cricket::BaseChannel* channel = transceiver->internal()->channel();
5155 if (channel) {
5156 transport_names_by_mid[channel->content_name()] =
5157 channel->transport_name();
5158 }
Steve Anton75737c02017-11-06 10:37:17 -08005159 }
Steve Anton5dfde182018-02-06 10:34:40 -08005160 if (rtp_data_channel_) {
5161 transport_names_by_mid[rtp_data_channel_->content_name()] =
5162 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005163 }
5164 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005165 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005166 RTC_DCHECK(transport_name);
5167 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005168 }
Steve Anton5dfde182018-02-06 10:34:40 -08005169 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005170}
5171
Steve Anton5dfde182018-02-06 10:34:40 -08005172std::map<std::string, cricket::TransportStats>
5173PeerConnection::GetTransportStatsByNames(
5174 const std::set<std::string>& transport_names) {
5175 if (!network_thread()->IsCurrent()) {
5176 return network_thread()
5177 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5178 RTC_FROM_HERE,
5179 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005180 }
Steve Anton5dfde182018-02-06 10:34:40 -08005181 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5182 for (const std::string& transport_name : transport_names) {
5183 cricket::TransportStats transport_stats;
5184 bool success =
5185 transport_controller_->GetStats(transport_name, &transport_stats);
5186 if (success) {
5187 transport_stats_by_name[transport_name] = std::move(transport_stats);
5188 } else {
5189 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5190 << transport_name;
5191 }
5192 }
5193 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005194}
5195
5196bool PeerConnection::GetLocalCertificate(
5197 const std::string& transport_name,
5198 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005199 if (!certificate) {
5200 return false;
5201 }
5202 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5203 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005204}
5205
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005206std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005207 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005208 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005209}
5210
5211cricket::DataChannelType PeerConnection::data_channel_type() const {
5212 return data_channel_type_;
5213}
5214
5215bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5216 return pending_ice_restarts_.find(content_name) !=
5217 pending_ice_restarts_.end();
5218}
5219
Steve Anton75737c02017-11-06 10:37:17 -08005220bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5221 return transport_controller_->NeedsIceRestart(content_name);
5222}
5223
5224void PeerConnection::OnCertificateReady(
5225 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5226 transport_controller_->SetLocalCertificate(certificate);
5227}
5228
5229void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005230 SetSessionError(SessionError::kTransport,
5231 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005232}
5233
5234void PeerConnection::OnTransportControllerConnectionState(
5235 cricket::IceConnectionState state) {
5236 switch (state) {
5237 case cricket::kIceConnectionConnecting:
5238 // If the current state is Connected or Completed, then there were
5239 // writable channels but now there are not, so the next state must
5240 // be Disconnected.
5241 // kIceConnectionConnecting is currently used as the default,
5242 // un-connected state by the TransportController, so its only use is
5243 // detecting disconnections.
5244 if (ice_connection_state_ ==
5245 PeerConnectionInterface::kIceConnectionConnected ||
5246 ice_connection_state_ ==
5247 PeerConnectionInterface::kIceConnectionCompleted) {
5248 SetIceConnectionState(
5249 PeerConnectionInterface::kIceConnectionDisconnected);
5250 }
5251 break;
5252 case cricket::kIceConnectionFailed:
5253 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5254 break;
5255 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005256 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005257 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005258 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005259 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005260 break;
5261 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005262 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005263 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005264 if (ice_connection_state_ !=
5265 PeerConnectionInterface::kIceConnectionConnected) {
5266 // If jumping directly from "checking" to "connected",
5267 // signal "connected" first.
5268 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5269 }
5270 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005271 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005272 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005273 break;
5274 default:
5275 RTC_NOTREACHED();
5276 }
5277}
5278
5279void PeerConnection::OnTransportControllerCandidatesGathered(
5280 const std::string& transport_name,
5281 const cricket::Candidates& candidates) {
5282 RTC_DCHECK(signaling_thread()->IsCurrent());
5283 int sdp_mline_index;
5284 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005285 RTC_LOG(LS_ERROR)
5286 << "OnTransportControllerCandidatesGathered: content name "
5287 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005288 return;
5289 }
5290
5291 for (cricket::Candidates::const_iterator citer = candidates.begin();
5292 citer != candidates.end(); ++citer) {
5293 // Use transport_name as the candidate media id.
5294 std::unique_ptr<JsepIceCandidate> candidate(
5295 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5296 if (local_description()) {
5297 mutable_local_description()->AddCandidate(candidate.get());
5298 }
5299 OnIceCandidate(std::move(candidate));
5300 }
5301}
5302
5303void PeerConnection::OnTransportControllerCandidatesRemoved(
5304 const std::vector<cricket::Candidate>& candidates) {
5305 RTC_DCHECK(signaling_thread()->IsCurrent());
5306 // Sanity check.
5307 for (const cricket::Candidate& candidate : candidates) {
5308 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005309 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005310 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005311 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005312 return;
5313 }
5314 }
5315
5316 if (local_description()) {
5317 mutable_local_description()->RemoveCandidates(candidates);
5318 }
5319 OnIceCandidatesRemoved(candidates);
5320}
5321
5322void PeerConnection::OnTransportControllerDtlsHandshakeError(
5323 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005324 RTC_HISTOGRAM_ENUMERATION(
5325 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5326 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005327}
5328
Steve Antoned10bd92017-12-05 10:52:59 -08005329void PeerConnection::EnableSending() {
5330 for (auto transceiver : transceivers_) {
5331 cricket::BaseChannel* channel = transceiver->internal()->channel();
5332 if (channel && !channel->enabled()) {
5333 channel->Enable(true);
5334 }
Steve Anton75737c02017-11-06 10:37:17 -08005335 }
5336
Steve Anton4171afb2017-11-20 10:20:22 -08005337 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005338 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005339 }
Steve Anton75737c02017-11-06 10:37:17 -08005340}
5341
5342// Returns the media index for a local ice candidate given the content name.
5343bool PeerConnection::GetLocalCandidateMediaIndex(
5344 const std::string& content_name,
5345 int* sdp_mline_index) {
5346 if (!local_description() || !sdp_mline_index) {
5347 return false;
5348 }
5349
5350 bool content_found = false;
5351 const ContentInfos& contents = local_description()->description()->contents();
5352 for (size_t index = 0; index < contents.size(); ++index) {
5353 if (contents[index].name == content_name) {
5354 *sdp_mline_index = static_cast<int>(index);
5355 content_found = true;
5356 break;
5357 }
5358 }
5359 return content_found;
5360}
5361
5362bool PeerConnection::UseCandidatesInSessionDescription(
5363 const SessionDescriptionInterface* remote_desc) {
5364 if (!remote_desc) {
5365 return true;
5366 }
5367 bool ret = true;
5368
5369 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5370 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5371 for (size_t n = 0; n < candidates->count(); ++n) {
5372 const IceCandidateInterface* candidate = candidates->at(n);
5373 bool valid = false;
5374 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5375 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005376 RTC_LOG(LS_INFO)
5377 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005378 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005379 }
5380 continue;
5381 }
5382 ret = UseCandidate(candidate);
5383 if (!ret) {
5384 break;
5385 }
5386 }
5387 }
5388 return ret;
5389}
5390
5391bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5392 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5393 size_t remote_content_size =
5394 remote_description()->description()->contents().size();
5395 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005396 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005397 return false;
5398 }
5399
5400 cricket::ContentInfo content =
5401 remote_description()->description()->contents()[mediacontent_index];
5402 std::vector<cricket::Candidate> candidates;
5403 candidates.push_back(candidate->candidate());
5404 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005405 RTCError error =
5406 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005407 if (error.ok()) {
5408 // Candidates successfully submitted for checking.
5409 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5410 ice_connection_state_ ==
5411 PeerConnectionInterface::kIceConnectionDisconnected) {
5412 // If state is New, then the session has just gotten its first remote ICE
5413 // candidates, so go to Checking.
5414 // If state is Disconnected, the session is re-using old candidates or
5415 // receiving additional ones, so go to Checking.
5416 // If state is Connected, stay Connected.
5417 // TODO(bemasc): If state is Connected, and the new candidates are for a
5418 // newly added transport, then the state actually _should_ move to
5419 // checking. Add a way to distinguish that case.
5420 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5421 }
5422 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005423 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005424 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005425 }
5426 return true;
5427}
5428
5429void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005430 // Destroy video channel first since it may have a pointer to the
5431 // voice channel.
5432 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005433 if (!video_info || video_info->rejected) {
5434 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005435 }
5436
Steve Anton6fec8802017-12-04 10:37:29 -08005437 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5438 if (!audio_info || audio_info->rejected) {
5439 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005440 }
5441
5442 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5443 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005444 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005445 }
5446}
5447
Steve Antondcc3c022017-12-22 16:02:54 -08005448RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5449 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005450 const cricket::ContentGroup* bundle_group = nullptr;
5451 if (configuration_.bundle_policy ==
5452 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005453 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005454 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005455 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5456 "max-bundle configured but session description "
5457 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005458 }
5459 }
Steve Antondcc3c022017-12-22 16:02:54 -08005460 return std::move(bundle_group);
5461}
5462
5463RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005464 // Creating the media channels. Transports should already have been created
5465 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005466 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005467 if (voice && !voice->rejected &&
5468 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005469 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005470 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005471 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5472 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005473 }
5474 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5475 }
5476
Steve Antondcc3c022017-12-22 16:02:54 -08005477 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005478 if (video && !video->rejected &&
5479 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005480 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005481 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005482 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5483 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005484 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005485 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005486 }
5487
Steve Antondcc3c022017-12-22 16:02:54 -08005488 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005489 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5490 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005491 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005492 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5493 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005494 }
5495 }
5496
Steve Anton8a006912017-12-04 15:25:56 -08005497 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005498}
5499
Steve Anton4171afb2017-11-20 10:20:22 -08005500// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005501cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005502 const std::string& mid) {
5503 RtpTransportInternal* rtp_transport =
5504 transport_controller_->GetRtpTransport(mid);
5505 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005506 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005507 call_.get(), configuration_.media_config, rtp_transport,
5508 signaling_thread(), mid, SrtpRequired(),
5509 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005510 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005511 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005512 }
Steve Anton75737c02017-11-06 10:37:17 -08005513 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5514 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005515 voice_channel->SignalSentPacket.connect(this,
5516 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005517 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005518
Steve Antoneda6ccd2017-12-04 10:21:55 -08005519 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005520}
5521
Steve Anton4171afb2017-11-20 10:20:22 -08005522// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005523cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005524 const std::string& mid) {
5525 RtpTransportInternal* rtp_transport =
5526 transport_controller_->GetRtpTransport(mid);
5527 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005528 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005529 call_.get(), configuration_.media_config, rtp_transport,
5530 signaling_thread(), mid, SrtpRequired(),
5531 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005532 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005533 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005534 }
Steve Anton75737c02017-11-06 10:37:17 -08005535 video_channel->SignalDtlsSrtpSetupFailure.connect(
5536 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005537 video_channel->SignalSentPacket.connect(this,
5538 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005539 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005540
Steve Antoneda6ccd2017-12-04 10:21:55 -08005541 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005542}
5543
Zhi Huange830e682018-03-30 10:48:35 -07005544bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005545 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5546 if (sctp) {
5547 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005548 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005549 << "Trying to create SCTP transport, but didn't compile with "
5550 "SCTP support (HAVE_SCTP)";
5551 return false;
5552 }
5553 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005554 RTC_FROM_HERE,
5555 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005556 return false;
5557 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005558 for (const auto& channel : sctp_data_channels_) {
5559 channel->OnTransportChannelCreated();
5560 }
Steve Anton75737c02017-11-06 10:37:17 -08005561 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005562 RtpTransportInternal* rtp_transport =
5563 transport_controller_->GetRtpTransport(mid);
5564 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005565 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005566 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5567 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005568 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005569 return false;
5570 }
Steve Anton75737c02017-11-06 10:37:17 -08005571 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5572 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5573 rtp_data_channel_->SignalSentPacket.connect(
5574 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005575 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005576 }
5577
Steve Anton75737c02017-11-06 10:37:17 -08005578 return true;
5579}
5580
5581Call::Stats PeerConnection::GetCallStats() {
5582 if (!worker_thread()->IsCurrent()) {
5583 return worker_thread()->Invoke<Call::Stats>(
5584 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5585 }
5586 if (call_) {
5587 return call_->GetStats();
5588 } else {
5589 return Call::Stats();
5590 }
5591}
5592
Zhi Huange830e682018-03-30 10:48:35 -07005593bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005594 RTC_DCHECK(network_thread()->IsCurrent());
5595 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005596 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005597 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005598 RTC_DCHECK(dtls_transport);
5599 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005600 RTC_DCHECK(sctp_transport_);
5601 sctp_invoker_.reset(new rtc::AsyncInvoker());
5602 sctp_transport_->SignalReadyToSendData.connect(
5603 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5604 sctp_transport_->SignalDataReceived.connect(
5605 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005606 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5607 // another thread. Would be nice if there was a helper class similar to
5608 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5609 // code.
5610 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5611 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5612 sctp_transport_->SignalClosingProcedureComplete.connect(
5613 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005614 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005615 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005616 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005617}
5618
5619void PeerConnection::DestroySctpTransport_n() {
5620 RTC_DCHECK(network_thread()->IsCurrent());
5621 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005622 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005623 sctp_invoker_.reset(nullptr);
5624 sctp_ready_to_send_data_ = false;
5625}
5626
5627void PeerConnection::OnSctpTransportReadyToSendData_n() {
5628 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5629 RTC_DCHECK(network_thread()->IsCurrent());
5630 // Note: Cannot use rtc::Bind here because it will grab a reference to
5631 // PeerConnection and potentially cause PeerConnection to live longer than
5632 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5633 // be destroyed before PeerConnection is destroyed, and at that point all
5634 // pending tasks will be cleared.
5635 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5636 OnSctpTransportReadyToSendData_s(true);
5637 });
5638}
5639
5640void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5641 RTC_DCHECK(signaling_thread()->IsCurrent());
5642 sctp_ready_to_send_data_ = ready;
5643 SignalSctpReadyToSendData(ready);
5644}
5645
5646void PeerConnection::OnSctpTransportDataReceived_n(
5647 const cricket::ReceiveDataParams& params,
5648 const rtc::CopyOnWriteBuffer& payload) {
5649 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5650 RTC_DCHECK(network_thread()->IsCurrent());
5651 // Note: Cannot use rtc::Bind here because it will grab a reference to
5652 // PeerConnection and potentially cause PeerConnection to live longer than
5653 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5654 // be destroyed before PeerConnection is destroyed, and at that point all
5655 // pending tasks will be cleared.
5656 sctp_invoker_->AsyncInvoke<void>(
5657 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5658 OnSctpTransportDataReceived_s(params, payload);
5659 });
5660}
5661
5662void PeerConnection::OnSctpTransportDataReceived_s(
5663 const cricket::ReceiveDataParams& params,
5664 const rtc::CopyOnWriteBuffer& payload) {
5665 RTC_DCHECK(signaling_thread()->IsCurrent());
5666 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5667 // Received OPEN message; parse and signal that a new data channel should
5668 // be created.
5669 std::string label;
5670 InternalDataChannelInit config;
5671 config.id = params.ssrc;
5672 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005673 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5674 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005675 return;
5676 }
5677 config.open_handshake_role = InternalDataChannelInit::kAcker;
5678 OnDataChannelOpenMessage(label, config);
5679 } else {
5680 // Otherwise just forward the signal.
5681 SignalSctpDataReceived(params, payload);
5682 }
5683}
5684
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005685void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005686 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5687 RTC_DCHECK(network_thread()->IsCurrent());
5688 sctp_invoker_->AsyncInvoke<void>(
5689 RTC_FROM_HERE, signaling_thread(),
5690 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005691 &SignalSctpClosingProcedureStartedRemotely, sid));
5692}
5693
5694void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5695 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5696 RTC_DCHECK(network_thread()->IsCurrent());
5697 sctp_invoker_->AsyncInvoke<void>(
5698 RTC_FROM_HERE, signaling_thread(),
5699 rtc::Bind(&sigslot::signal1<int>::operator(),
5700 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005701}
5702
5703// Returns false if bundle is enabled and rtcp_mux is disabled.
5704bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5705 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5706 if (!bundle_enabled)
5707 return true;
5708
5709 const cricket::ContentGroup* bundle_group =
5710 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5711 RTC_DCHECK(bundle_group != NULL);
5712
5713 const cricket::ContentInfos& contents = desc->contents();
5714 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5715 citer != contents.end(); ++citer) {
5716 const cricket::ContentInfo* content = (&*citer);
5717 RTC_DCHECK(content != NULL);
5718 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005719 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005720 if (!HasRtcpMuxEnabled(content))
5721 return false;
5722 }
5723 }
5724 // RTCP-MUX is enabled in all the contents.
5725 return true;
5726}
5727
5728bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005729 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005730}
5731
Steve Anton8a006912017-12-04 15:25:56 -08005732RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005733 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005734 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005735 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005736 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005737 }
5738
5739 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005741 }
5742
Steve Anton3828c062017-12-06 10:34:51 -08005743 SdpType type = sdesc->GetType();
5744 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5745 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005746 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005747 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005748 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005749 }
5750
5751 // Verify crypto settings.
5752 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005753 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5754 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005755 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005756 if (!crypto_error.ok()) {
5757 return crypto_error;
5758 }
Steve Anton75737c02017-11-06 10:37:17 -08005759 }
5760
5761 // Verify ice-ufrag and ice-pwd.
5762 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005763 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5764 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005765 }
5766
5767 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005768 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5769 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005770 }
5771
5772 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5773 // m-lines that do not rtcp-mux enabled.
5774
5775 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005776 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005777 // With an answer we want to compare the new answer session description with
5778 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005779 const cricket::SessionDescription* offer_desc =
5780 (source == cricket::CS_LOCAL) ? remote_description()->description()
5781 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005782 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5783 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5784 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005785 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5786 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005787 }
5788 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005789 // The re-offers should respect the order of m= sections in current
5790 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005791 // With a re-offer, either the current local or current remote descriptions
5792 // could be the most up to date, so we would like to check against both of
5793 // them if they exist. It could be the case that one of them has a 0 port
5794 // for a media section, but the other does not. This is important to check
5795 // against in the case that we are recycling an m= section.
5796 const cricket::SessionDescription* current_desc = nullptr;
5797 const cricket::SessionDescription* secondary_current_desc = nullptr;
5798 if (local_description()) {
5799 current_desc = local_description()->description();
5800 if (remote_description()) {
5801 secondary_current_desc = remote_description()->description();
5802 }
5803 } else if (remote_description()) {
5804 current_desc = remote_description()->description();
5805 }
Steve Anton75737c02017-11-06 10:37:17 -08005806 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005807 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5808 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005809 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5810 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005811 }
5812 }
5813
Steve Antonba42e992018-04-09 14:10:01 -07005814 if (IsUnifiedPlan()) {
5815 // Ensure that each audio and video media section has at most one
5816 // "StreamParams". This will return an error if receiving a session
5817 // description from a "Plan B" endpoint which adds multiple tracks of the
5818 // same type. With Unified Plan, there can only be at most one track per
5819 // media section.
5820 for (const ContentInfo& content : sdesc->description()->contents()) {
5821 const MediaContentDescription& desc = *content.description;
5822 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5823 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5824 desc.streams().size() > 1u) {
5825 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5826 "Media section has more than one track specified "
5827 "with a=ssrc lines which is not supported with "
5828 "Unified Plan.");
5829 }
5830 }
5831 }
5832
Steve Anton8a006912017-12-04 15:25:56 -08005833 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005834}
5835
Steve Anton3828c062017-12-06 10:34:51 -08005836bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005837 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005838 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005839 return (state == PeerConnectionInterface::kStable) ||
5840 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005841 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005842 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005843 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5844 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5845 }
5846}
5847
Steve Anton3828c062017-12-06 10:34:51 -08005848bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005849 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005850 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005851 return (state == PeerConnectionInterface::kStable) ||
5852 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005853 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005854 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005855 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5856 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5857 }
5858}
5859
Steve Antonf8470812017-12-04 10:46:21 -08005860const char* PeerConnection::SessionErrorToString(SessionError error) const {
5861 switch (error) {
5862 case SessionError::kNone:
5863 return "ERROR_NONE";
5864 case SessionError::kContent:
5865 return "ERROR_CONTENT";
5866 case SessionError::kTransport:
5867 return "ERROR_TRANSPORT";
5868 }
5869 RTC_NOTREACHED();
5870 return "";
5871}
5872
Steve Anton75737c02017-11-06 10:37:17 -08005873std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02005874 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08005875 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5876 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02005877 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08005878}
5879
Steve Anton8e20f172018-03-06 10:55:04 -08005880void PeerConnection::ReportSdpFormatReceived(
5881 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005882 int num_audio_mlines = 0;
5883 int num_video_mlines = 0;
5884 int num_audio_tracks = 0;
5885 int num_video_tracks = 0;
5886 for (const ContentInfo& content : remote_offer.description()->contents()) {
5887 cricket::MediaType media_type = content.media_description()->type();
5888 int num_tracks = std::max(
5889 1, static_cast<int>(content.media_description()->streams().size()));
5890 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5891 num_audio_mlines += 1;
5892 num_audio_tracks += num_tracks;
5893 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5894 num_video_mlines += 1;
5895 num_video_tracks += num_tracks;
5896 }
5897 }
5898 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5899 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5900 format = kSdpFormatReceivedComplexUnifiedPlan;
5901 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5902 format = kSdpFormatReceivedComplexPlanB;
5903 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5904 format = kSdpFormatReceivedSimple;
5905 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005906 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5907 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005908}
5909
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005910void PeerConnection::NoteUsageEvent(UsageEvent event) {
5911 RTC_DCHECK_RUN_ON(signaling_thread());
5912 usage_event_accumulator_ |= static_cast<int>(event);
5913}
5914
5915void PeerConnection::ReportUsagePattern() const {
5916 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005917 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5918 usage_event_accumulator_,
5919 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005920 const int bad_bits =
5921 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5922 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5923 const int good_bits =
5924 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5925 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5926 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5927 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5928 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005929 // If called after close(), we can't report, because observer may have
5930 // been deallocated, and therefore pointer is null. Write to log instead.
5931 if (observer_) {
5932 Observer()->OnInterestingUsage(usage_event_accumulator_);
5933 } else {
5934 RTC_LOG(LS_INFO) << "Interesting usage signature "
5935 << usage_event_accumulator_
5936 << " observed after observer shutdown";
5937 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005938 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005939}
5940
Steve Anton0ffaaa22018-02-23 10:31:30 -08005941void PeerConnection::ReportNegotiatedSdpSemantics(
5942 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005943 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005944 switch (answer.description()->msid_signaling()) {
5945 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005946 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005947 break;
5948 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005949 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005950 break;
5951 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005952 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005953 break;
5954 case cricket::kMsidSignalingMediaSection |
5955 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005956 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005957 break;
5958 default:
5959 RTC_NOTREACHED();
5960 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005961 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5962 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005963}
5964
Steve Anton75737c02017-11-06 10:37:17 -08005965// We need to check the local/remote description for the Transport instead of
5966// the session, because a new Transport added during renegotiation may have
5967// them unset while the session has them set from the previous negotiation.
5968// Not doing so may trigger the auto generation of transport description and
5969// mess up DTLS identity information, ICE credential, etc.
5970bool PeerConnection::ReadyToUseRemoteCandidate(
5971 const IceCandidateInterface* candidate,
5972 const SessionDescriptionInterface* remote_desc,
5973 bool* valid) {
5974 *valid = true;
5975
5976 const SessionDescriptionInterface* current_remote_desc =
5977 remote_desc ? remote_desc : remote_description();
5978
5979 if (!current_remote_desc) {
5980 return false;
5981 }
5982
5983 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5984 size_t remote_content_size =
5985 current_remote_desc->description()->contents().size();
5986 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005987 RTC_LOG(LS_ERROR)
5988 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5989 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005990
5991 *valid = false;
5992 return false;
5993 }
5994
5995 cricket::ContentInfo content =
5996 current_remote_desc->description()->contents()[mediacontent_index];
5997
5998 const std::string transport_name = GetTransportName(content.name);
5999 if (transport_name.empty()) {
6000 return false;
6001 }
Zhi Huange830e682018-03-30 10:48:35 -07006002 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006003}
6004
6005bool PeerConnection::SrtpRequired() const {
6006 return dtls_enabled_ ||
6007 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6008}
6009
6010void PeerConnection::OnTransportControllerGatheringState(
6011 cricket::IceGatheringState state) {
6012 RTC_DCHECK(signaling_thread()->IsCurrent());
6013 if (state == cricket::kIceGatheringGathering) {
6014 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6015 } else if (state == cricket::kIceGatheringComplete) {
6016 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6017 }
6018}
6019
6020void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006021 std::map<std::string, std::set<cricket::MediaType>>
6022 media_types_by_transport_name;
6023 for (auto transceiver : transceivers_) {
6024 if (transceiver->internal()->channel()) {
6025 const std::string& transport_name =
6026 transceiver->internal()->channel()->transport_name();
6027 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006028 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006029 }
Steve Anton75737c02017-11-06 10:37:17 -08006030 }
6031 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006032 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6033 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006034 }
Zhi Huange830e682018-03-30 10:48:35 -07006035
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006036 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006037 if (transport_name) {
6038 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006039 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006040 }
Zhi Huange830e682018-03-30 10:48:35 -07006041
Steve Antonc7b964c2018-02-01 14:39:45 -08006042 for (const auto& entry : media_types_by_transport_name) {
6043 const std::string& transport_name = entry.first;
6044 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006045 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006046 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006047 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006048 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006049 }
6050 }
6051}
6052// Walk through the ConnectionInfos to gather best connection usage
6053// for IPv4 and IPv6.
6054void PeerConnection::ReportBestConnectionState(
6055 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006056 for (const cricket::TransportChannelStats& channel_stats :
6057 stats.channel_stats) {
6058 for (const cricket::ConnectionInfo& connection_info :
6059 channel_stats.connection_infos) {
6060 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006061 continue;
6062 }
6063
Steve Antonc7b964c2018-02-01 14:39:45 -08006064 const cricket::Candidate& local = connection_info.local_candidate;
6065 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006066
6067 // Increment the counter for IceCandidatePairType.
6068 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6069 (local.type() == RELAY_PORT_TYPE &&
6070 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006071 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6072 GetIceCandidatePairCounter(local, remote),
6073 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006074 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006075 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6076 GetIceCandidatePairCounter(local, remote),
6077 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006078 } else {
6079 RTC_CHECK(0);
6080 }
Steve Anton75737c02017-11-06 10:37:17 -08006081
6082 // Increment the counter for IP type.
6083 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006084 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6085 kBestConnections_IPv4,
6086 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006087 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006088 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6089 kBestConnections_IPv6,
6090 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006091 } else {
6092 RTC_CHECK(0);
6093 }
6094
6095 return;
6096 }
6097 }
6098}
6099
6100void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006101 const cricket::TransportStats& stats,
6102 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006103 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6104 return;
6105 }
6106
6107 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6108 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6109 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6110 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6111 return;
6112 }
6113
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006114 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6115 for (cricket::MediaType media_type : media_types) {
6116 switch (media_type) {
6117 case cricket::MEDIA_TYPE_AUDIO:
6118 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6119 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6120 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6121 break;
6122 case cricket::MEDIA_TYPE_VIDEO:
6123 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6124 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6125 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6126 break;
6127 case cricket::MEDIA_TYPE_DATA:
6128 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6129 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6130 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6131 break;
6132 default:
6133 RTC_NOTREACHED();
6134 continue;
6135 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006136 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006137 }
6138
6139 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6140 for (cricket::MediaType media_type : media_types) {
6141 switch (media_type) {
6142 case cricket::MEDIA_TYPE_AUDIO:
6143 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6144 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6145 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6146 break;
6147 case cricket::MEDIA_TYPE_VIDEO:
6148 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6149 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6150 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6151 break;
6152 case cricket::MEDIA_TYPE_DATA:
6153 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6154 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6155 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6156 break;
6157 default:
6158 RTC_NOTREACHED();
6159 continue;
6160 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006161 }
Steve Anton75737c02017-11-06 10:37:17 -08006162 }
6163}
6164
6165void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6166 RTC_DCHECK(worker_thread()->IsCurrent());
6167 RTC_DCHECK(call_);
6168 call_->OnSentPacket(sent_packet);
6169}
6170
6171const std::string PeerConnection::GetTransportName(
6172 const std::string& content_name) {
6173 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006174 if (channel) {
6175 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006176 }
Steve Anton6fec8802017-12-04 10:37:29 -08006177 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006178 RTC_DCHECK(sctp_mid_);
6179 if (content_name == *sctp_mid_) {
6180 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006181 }
6182 }
6183 // Return an empty string if failed to retrieve the transport name.
6184 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006185}
6186
Steve Anton6fec8802017-12-04 10:37:29 -08006187void PeerConnection::DestroyTransceiverChannel(
6188 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6189 transceiver) {
6190 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006191
Steve Anton6fec8802017-12-04 10:37:29 -08006192 cricket::BaseChannel* channel = transceiver->internal()->channel();
6193 if (channel) {
6194 transceiver->internal()->SetChannel(nullptr);
6195 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006196 }
6197}
6198
6199void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006200 if (rtp_data_channel_) {
6201 OnDataChannelDestroyed();
6202 DestroyBaseChannel(rtp_data_channel_);
6203 rtp_data_channel_ = nullptr;
6204 }
6205
6206 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6207 // grab a reference to this PeerConnection. If this is called from the
6208 // PeerConnection destructor, the RefCountedObject vtable will have already
6209 // been destroyed (since it is a subclass of PeerConnection) and using
6210 // rtc::Bind will cause "Pure virtual function called" error to appear.
6211
6212 if (sctp_transport_) {
6213 OnDataChannelDestroyed();
6214 network_thread()->Invoke<void>(RTC_FROM_HERE,
6215 [this] { DestroySctpTransport_n(); });
6216 }
6217}
6218
6219void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6220 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006221 switch (channel->media_type()) {
6222 case cricket::MEDIA_TYPE_AUDIO:
6223 channel_manager()->DestroyVoiceChannel(
6224 static_cast<cricket::VoiceChannel*>(channel));
6225 break;
6226 case cricket::MEDIA_TYPE_VIDEO:
6227 channel_manager()->DestroyVideoChannel(
6228 static_cast<cricket::VideoChannel*>(channel));
6229 break;
6230 case cricket::MEDIA_TYPE_DATA:
6231 channel_manager()->DestroyRtpDataChannel(
6232 static_cast<cricket::RtpDataChannel*>(channel));
6233 break;
6234 default:
6235 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6236 break;
6237 }
Zhi Huange830e682018-03-30 10:48:35 -07006238}
Steve Anton6fec8802017-12-04 10:37:29 -08006239
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006240bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006241 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006242 RtpTransportInternal* rtp_transport,
6243 cricket::DtlsTransportInternal* dtls_transport) {
6244 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006245 auto base_channel = GetChannel(mid);
6246 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006247 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006248 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006249 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006250 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006251 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006252 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006253}
6254
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006255PeerConnectionObserver* PeerConnection::Observer() const {
6256 // In earlier production code, the pointer was not cleared on close,
6257 // which might have led to undefined behavior if the observer was not
6258 // deallocated, or strange crashes if it was.
6259 // We use CHECK in order to catch such behavior if it exists.
6260 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6261 RTC_CHECK(observer_);
6262 return observer_;
6263}
6264
Harald Alvestrand89061872018-01-02 14:08:34 +01006265void PeerConnection::ClearStatsCache() {
6266 if (stats_collector_) {
6267 stats_collector_->ClearCachedStatsReport();
6268 }
6269}
6270
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006271void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006272 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6273 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006274}
6275
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006276} // namespace webrtc