blob: 6d67329242d75c1ca8256d07a4514c72d9f40287 [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"
25#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080026#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020027#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "logging/rtc_event_log/rtc_event_log.h"
29#include "media/sctp/sctptransport.h"
30#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080031#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "pc/channelmanager.h"
33#include "pc/dtmfsender.h"
34#include "pc/mediastream.h"
35#include "pc/mediastreamobserver.h"
36#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080037#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/rtpreceiver.h"
39#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080040#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080041#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020042#include "pc/streamcollection.h"
43#include "pc/videocapturertracksource.h"
44#include "pc/videotrack.h"
45#include "rtc_base/bind.h"
46#include "rtc_base/checks.h"
47#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010048#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020049#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020050#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020051#include "rtc_base/stringutils.h"
52#include "rtc_base/trace_event.h"
53#include "system_wrappers/include/clock.h"
54#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070055#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000056
Steve Anton75737c02017-11-06 10:37:17 -080057using cricket::ContentInfo;
58using cricket::ContentInfos;
59using cricket::MediaContentDescription;
60using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080061using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080062using cricket::TransportInfo;
63
64using cricket::LOCAL_PORT_TYPE;
65using cricket::STUN_PORT_TYPE;
66using cricket::RELAY_PORT_TYPE;
67using cricket::PRFLX_PORT_TYPE;
68
Steve Antonba818672017-11-06 10:21:57 -080069namespace webrtc {
70
Steve Anton75737c02017-11-06 10:37:17 -080071// Error messages
72const char kBundleWithoutRtcpMux[] =
73 "rtcp-mux must be enabled when BUNDLE "
74 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080075const char kInvalidCandidates[] = "Description contains invalid candidates.";
76const char kInvalidSdp[] = "Invalid session description.";
77const char kMlineMismatchInAnswer[] =
78 "The order of m-lines in answer doesn't match order in offer. Rejecting "
79 "answer.";
80const char kMlineMismatchInSubsequentOffer[] =
81 "The order of m-lines in subsequent offer doesn't match order from "
82 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080083const char kSdpWithoutDtlsFingerprint[] =
84 "Called with SDP without DTLS fingerprint.";
85const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
86const char kSdpWithoutIceUfragPwd[] =
87 "Called with SDP without ice-ufrag and ice-pwd.";
88const char kSessionError[] = "Session error code: ";
89const char kSessionErrorDesc[] = "Session error description: ";
90const char kDtlsSrtpSetupFailureRtp[] =
91 "Couldn't set up DTLS-SRTP on RTP channel.";
92const char kDtlsSrtpSetupFailureRtcp[] =
93 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000094
Steve Anton75737c02017-11-06 10:37:17 -080095namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000096
Seth Hampson845e8782018-03-02 11:34:10 -080097static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080098static const char kDefaultAudioSenderId[] = "defaulta0";
99static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700100
zhihuang8f65cdf2016-05-06 18:40:30 -0700101// The length of RTCP CNAMEs.
102static const int kRtcpCnameLength = 16;
103
Steve Antonad182762018-09-05 20:22:40 +0000104enum {
105 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
106 MSG_SET_SESSIONDESCRIPTION_FAILED,
107 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
108 MSG_GETSTATS,
109 MSG_FREE_DATACHANNELS,
110 MSG_REPORT_USAGE_PATTERN,
111};
112
Harald Alvestrand19793842018-06-25 12:03:50 +0200113static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
114
Steve Antonad182762018-09-05 20:22:40 +0000115struct SetSessionDescriptionMsg : public rtc::MessageData {
116 explicit SetSessionDescriptionMsg(
117 webrtc::SetSessionDescriptionObserver* observer)
118 : observer(observer) {}
119
120 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
121 RTCError error;
122};
123
124struct CreateSessionDescriptionMsg : public rtc::MessageData {
125 explicit CreateSessionDescriptionMsg(
126 webrtc::CreateSessionDescriptionObserver* observer)
127 : observer(observer) {}
128
129 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
130 RTCError error;
131};
132
133struct GetStatsMsg : public rtc::MessageData {
134 GetStatsMsg(webrtc::StatsObserver* observer,
135 webrtc::MediaStreamTrackInterface* track)
136 : observer(observer), track(track) {}
137 rtc::scoped_refptr<webrtc::StatsObserver> observer;
138 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
139};
140
deadbeefab9b2d12015-10-14 11:33:11 -0700141// Check if we can send |new_stream| on a PeerConnection.
142bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
143 webrtc::MediaStreamInterface* new_stream) {
144 if (!new_stream || !current_streams) {
145 return false;
146 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700147 if (current_streams->find(new_stream->id()) != nullptr) {
148 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100149 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700150 return false;
151 }
152 return true;
153}
154
deadbeef5e97fb52015-10-15 12:49:08 -0700155// If the direction is "recvonly" or "inactive", treat the description
156// as containing no streams.
157// See: https://code.google.com/p/webrtc/issues/detail?id=5054
158std::vector<cricket::StreamParams> GetActiveStreams(
159 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800160 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700161 ? desc->streams()
162 : std::vector<cricket::StreamParams>();
163}
164
deadbeefab9b2d12015-10-14 11:33:11 -0700165bool IsValidOfferToReceiveMedia(int value) {
166 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
167 return (value >= Options::kUndefined) &&
168 (value <= Options::kMaxOfferToReceiveMedia);
169}
170
zhihuang1c378ed2017-08-17 14:10:50 -0700171// Add options to |[audio/video]_media_description_options| from |senders|.
172void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700173 const std::vector<rtc::scoped_refptr<
174 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700175 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200176 cricket::MediaDescriptionOptions* video_media_description_options,
177 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700178 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700179 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
180 if (audio_media_description_options) {
181 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700182 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700183 }
184 } else {
185 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
186 if (video_media_description_options) {
187 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200188 sender->id(), sender->internal()->stream_ids(),
189 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700190 }
191 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700192 }
zhihuang1c378ed2017-08-17 14:10:50 -0700193}
olka3c747662017-08-17 06:50:32 -0700194
zhihuang1c378ed2017-08-17 14:10:50 -0700195// Add options to |session_options| from |rtp_data_channels|.
196void AddRtpDataChannelOptions(
197 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
198 rtp_data_channels,
199 cricket::MediaDescriptionOptions* data_media_description_options) {
200 if (!data_media_description_options) {
201 return;
202 }
deadbeefab9b2d12015-10-14 11:33:11 -0700203 // Check for data channels.
204 for (const auto& kv : rtp_data_channels) {
205 const DataChannel* channel = kv.second;
206 if (channel->state() == DataChannel::kConnecting ||
207 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700208 // Legacy RTP data channels are signaled with the track/stream ID set to
209 // the data channel's label.
210 data_media_description_options->AddRtpDataChannel(channel->label(),
211 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700212 }
213 }
214}
215
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700216uint32_t ConvertIceTransportTypeToCandidateFilter(
217 PeerConnectionInterface::IceTransportsType type) {
218 switch (type) {
219 case PeerConnectionInterface::kNone:
220 return cricket::CF_NONE;
221 case PeerConnectionInterface::kRelay:
222 return cricket::CF_RELAY;
223 case PeerConnectionInterface::kNoHost:
224 return (cricket::CF_ALL & ~cricket::CF_HOST);
225 case PeerConnectionInterface::kAll:
226 return cricket::CF_ALL;
227 default:
nissec80e7412017-01-11 05:56:46 -0800228 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700229 }
230 return cricket::CF_NONE;
231}
232
deadbeef293e9262017-01-11 12:28:30 -0800233// Helper to set an error and return from a method.
234bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
235 if (error) {
236 error->set_type(type);
237 }
238 return type == webrtc::RTCErrorType::NONE;
239}
240
Steve Anton038834f2017-07-14 15:59:59 -0700241bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700242 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700243 if (error_out) {
244 *error_out = std::move(error);
245 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700246 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700247}
248
Steve Antonba818672017-11-06 10:21:57 -0800249std::string GetSignalingStateString(
250 PeerConnectionInterface::SignalingState state) {
251 switch (state) {
252 case PeerConnectionInterface::kStable:
253 return "kStable";
254 case PeerConnectionInterface::kHaveLocalOffer:
255 return "kHaveLocalOffer";
256 case PeerConnectionInterface::kHaveLocalPrAnswer:
257 return "kHavePrAnswer";
258 case PeerConnectionInterface::kHaveRemoteOffer:
259 return "kHaveRemoteOffer";
260 case PeerConnectionInterface::kHaveRemotePrAnswer:
261 return "kHaveRemotePrAnswer";
262 case PeerConnectionInterface::kClosed:
263 return "kClosed";
264 }
265 RTC_NOTREACHED();
266 return "";
267}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700268
Steve Anton75737c02017-11-06 10:37:17 -0800269IceCandidatePairType GetIceCandidatePairCounter(
270 const cricket::Candidate& local,
271 const cricket::Candidate& remote) {
272 const auto& l = local.type();
273 const auto& r = remote.type();
274 const auto& host = LOCAL_PORT_TYPE;
275 const auto& srflx = STUN_PORT_TYPE;
276 const auto& relay = RELAY_PORT_TYPE;
277 const auto& prflx = PRFLX_PORT_TYPE;
278 if (l == host && r == host) {
279 bool local_private = IPIsPrivate(local.address().ipaddr());
280 bool remote_private = IPIsPrivate(remote.address().ipaddr());
281 if (local_private) {
282 if (remote_private) {
283 return kIceCandidatePairHostPrivateHostPrivate;
284 } else {
285 return kIceCandidatePairHostPrivateHostPublic;
286 }
287 } else {
288 if (remote_private) {
289 return kIceCandidatePairHostPublicHostPrivate;
290 } else {
291 return kIceCandidatePairHostPublicHostPublic;
292 }
293 }
294 }
295 if (l == host && r == srflx)
296 return kIceCandidatePairHostSrflx;
297 if (l == host && r == relay)
298 return kIceCandidatePairHostRelay;
299 if (l == host && r == prflx)
300 return kIceCandidatePairHostPrflx;
301 if (l == srflx && r == host)
302 return kIceCandidatePairSrflxHost;
303 if (l == srflx && r == srflx)
304 return kIceCandidatePairSrflxSrflx;
305 if (l == srflx && r == relay)
306 return kIceCandidatePairSrflxRelay;
307 if (l == srflx && r == prflx)
308 return kIceCandidatePairSrflxPrflx;
309 if (l == relay && r == host)
310 return kIceCandidatePairRelayHost;
311 if (l == relay && r == srflx)
312 return kIceCandidatePairRelaySrflx;
313 if (l == relay && r == relay)
314 return kIceCandidatePairRelayRelay;
315 if (l == relay && r == prflx)
316 return kIceCandidatePairRelayPrflx;
317 if (l == prflx && r == host)
318 return kIceCandidatePairPrflxHost;
319 if (l == prflx && r == srflx)
320 return kIceCandidatePairPrflxSrflx;
321 if (l == prflx && r == relay)
322 return kIceCandidatePairPrflxRelay;
323 return kIceCandidatePairMax;
324}
325
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800326// Logic to decide if an m= section can be recycled. This means that the new
327// m= section is not rejected, but the old local or remote m= section is
328// rejected. |old_content_one| and |old_content_two| refer to the m= section
329// of the old remote and old local descriptions in no particular order.
330// We need to check both the old local and remote because either
331// could be the most current from the latest negotation.
332bool IsMediaSectionBeingRecycled(SdpType type,
333 const ContentInfo& content,
334 const ContentInfo* old_content_one,
335 const ContentInfo* old_content_two) {
336 return type == SdpType::kOffer && !content.rejected &&
337 ((old_content_one && old_content_one->rejected) ||
338 (old_content_two && old_content_two->rejected));
339}
340
Steve Anton75737c02017-11-06 10:37:17 -0800341// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800342// |current_desc|. The number of m= sections in |new_desc| should be no
343// less than |current_desc|. In the case of checking an answer's
344// |new_desc|, the |current_desc| is the last offer that was set as the
345// local or remote. In the case of checking an offer's |new_desc| we
346// check against the local and remote descriptions stored from the last
347// negotiation, because either of these could be the most up to date for
348// possible rejected m sections. These are the |current_desc| and
349// |secondary_current_desc|.
350bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
351 const SessionDescription* secondary_current_desc,
352 const SessionDescription& new_desc,
353 const SdpType type) {
354 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800355 return false;
356 }
357
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800358 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
359 const cricket::ContentInfo* secondary_content_info = nullptr;
360 if (secondary_current_desc &&
361 i < secondary_current_desc->contents().size()) {
362 secondary_content_info = &secondary_current_desc->contents()[i];
363 }
364 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
365 &current_desc.contents()[i],
366 secondary_content_info)) {
367 // For new offer descriptions, if the media section can be recycled, it's
368 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800369 continue;
370 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800371 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800372 return false;
373 }
374 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800375 new_desc.contents()[i].media_description();
376 const MediaContentDescription* current_desc_mdesc =
377 current_desc.contents()[i].media_description();
378 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800379 return false;
380 }
381 }
382 return true;
383}
384
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800385bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
386 const SessionDescription& desc2) {
387 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800388}
389
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700390void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
391 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200392 // Array of structs needed to map {KeyExchangeProtocolType,
393 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
394 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
395 static constexpr struct {
396 KeyExchangeProtocolType protocol_type;
397 cricket::MediaType media_type;
398 KeyExchangeProtocolMedia protocol_media;
399 } kEnumCounterKeyProtocolMediaMap[] = {
400 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
401 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
402 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
403 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
404 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
405 kEnumCounterKeyProtocolMediaTypeDtlsData},
406 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
407 kEnumCounterKeyProtocolMediaTypeSdesAudio},
408 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
409 kEnumCounterKeyProtocolMediaTypeSdesVideo},
410 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
411 kEnumCounterKeyProtocolMediaTypeSdesData},
412 };
413
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700414 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
415 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100416
Mirko Bonadeiab499822018-09-11 10:43:20 +0200417 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
418 if (i.protocol_type == protocol_type && i.media_type == media_type) {
419 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
420 i.protocol_media,
421 kEnumCounterKeyProtocolMediaTypeMax);
422 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100423 }
424}
425
Harald Alvestrand76829d72018-07-18 23:24:36 +0200426void NoteAddIceCandidateResult(int result) {
427 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
428 kAddIceCandidateMax);
429}
430
Steve Anton75737c02017-11-06 10:37:17 -0800431// Checks that each non-rejected content has SDES crypto keys or a DTLS
432// fingerprint, unless it's in a BUNDLE group, in which case only the
433// BUNDLE-tag section (first media section/description in the BUNDLE group)
434// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
435// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
436// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700437RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800438 const cricket::ContentGroup* bundle =
439 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800440 for (const cricket::ContentInfo& content_info : desc->contents()) {
441 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800442 continue;
443 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100444 // Note what media is used with each crypto protocol, for all sections.
445 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
446 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700447 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800448 const std::string& mid = content_info.name;
449 if (bundle && bundle->HasContentName(mid) &&
450 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800451 // This isn't the first media section in the BUNDLE group, so it's not
452 // required to have crypto attributes, since only the crypto attributes
453 // from the first section actually get used.
454 continue;
455 }
456
457 // If the content isn't rejected or bundled into another m= section, crypto
458 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800459 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800460 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800461 if (!media || !tinfo) {
462 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800463 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800464 }
465 if (dtls_enabled) {
466 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100467 RTC_LOG(LS_WARNING)
468 << "Session description must have DTLS fingerprint if "
469 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800470 return RTCError(RTCErrorType::INVALID_PARAMETER,
471 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800472 }
473 } else {
474 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100475 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800476 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800477 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800478 }
479 }
480 }
Steve Anton8a006912017-12-04 15:25:56 -0800481 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800482}
483
484// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
485// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
486// media section/description in the BUNDLE group) needs a ufrag and pwd.
487bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
488 const cricket::ContentGroup* bundle =
489 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800490 for (const cricket::ContentInfo& content_info : desc->contents()) {
491 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800492 continue;
493 }
Steve Anton8a006912017-12-04 15:25:56 -0800494 const std::string& mid = content_info.name;
495 if (bundle && bundle->HasContentName(mid) &&
496 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800497 // This isn't the first media section in the BUNDLE group, so it's not
498 // required to have ufrag/password, since only the ufrag/password from
499 // the first section actually get used.
500 continue;
501 }
502
503 // If the content isn't rejected or bundled into another m= section,
504 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800505 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800506 if (!tinfo) {
507 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100508 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800509 return false;
510 }
511 if (tinfo->description.ice_ufrag.empty() ||
512 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100513 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800514 return false;
515 }
516 }
517 return true;
518}
519
520bool GetTrackIdBySsrc(const SessionDescription* session_description,
521 uint32_t ssrc,
522 std::string* track_id) {
523 RTC_DCHECK(track_id != NULL);
524
Steve Antonb1c1de12017-12-21 15:14:30 -0800525 const cricket::AudioContentDescription* audio_desc =
526 cricket::GetFirstAudioContentDescription(session_description);
527 if (audio_desc) {
528 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800529 if (found) {
530 *track_id = found->id;
531 return true;
532 }
533 }
534
Steve Antonb1c1de12017-12-21 15:14:30 -0800535 const cricket::VideoContentDescription* video_desc =
536 cricket::GetFirstVideoContentDescription(session_description);
537 if (video_desc) {
538 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800539 if (found) {
540 *track_id = found->id;
541 return true;
542 }
543 }
544 return false;
545}
546
547// Get the SCTP port out of a SessionDescription.
548// Return -1 if not found.
549int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800550 const cricket::DataContentDescription* data_desc =
551 GetFirstDataContentDescription(session_description);
552 RTC_DCHECK(data_desc);
553 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800554 return -1;
555 }
Steve Anton75737c02017-11-06 10:37:17 -0800556 std::string value;
557 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
558 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800559 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800560 if (!codec.Matches(match_pattern)) {
561 continue;
562 }
563 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
564 return rtc::FromString<int>(value);
565 }
566 }
567 return -1;
568}
569
Steve Anton75737c02017-11-06 10:37:17 -0800570// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
571bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
572 const SessionDescriptionInterface* new_desc,
573 const std::string& content_name) {
574 if (!old_desc) {
575 return false;
576 }
577 const SessionDescription* new_sd = new_desc->description();
578 const SessionDescription* old_sd = old_desc->description();
579 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
580 if (!cinfo || cinfo->rejected) {
581 return false;
582 }
583 // If the content isn't rejected, check if ufrag and password has changed.
584 const cricket::TransportDescription* new_transport_desc =
585 new_sd->GetTransportDescriptionByName(content_name);
586 const cricket::TransportDescription* old_transport_desc =
587 old_sd->GetTransportDescriptionByName(content_name);
588 if (!new_transport_desc || !old_transport_desc) {
589 // No transport description exists. This is not an ICE restart.
590 return false;
591 }
592 if (cricket::IceCredentialsChanged(
593 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
594 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100595 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
596 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800597 return true;
598 }
599 return false;
600}
601
Steve Anton80dd7b52018-02-16 17:08:42 -0800602// Generates a string error message for SetLocalDescription/SetRemoteDescription
603// from an RTCError.
604std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
605 SdpType type,
606 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200607 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800608 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
609 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200610 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800611}
612
Seth Hampson5b4f0752018-04-02 16:31:36 -0700613std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
614 std::string output = "streams=[";
615 const char* separator = "";
616 for (const auto& stream_id : stream_ids) {
617 output.append(separator).append(stream_id);
618 separator = ", ";
619 }
620 output.append("]");
621 return output;
622}
623
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200624absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700625 int rtc_configuration_parameter) {
626 if (rtc_configuration_parameter ==
627 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200628 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700629 }
630 return rtc_configuration_parameter;
631}
632
Steve Anton75737c02017-11-06 10:37:17 -0800633} // namespace
634
Henrik Boström31638672017-11-23 17:48:32 +0100635// Upon completion, posts a task to execute the callback of the
636// SetSessionDescriptionObserver asynchronously on the same thread. At this
637// point, the state of the peer connection might no longer reflect the effects
638// of the SetRemoteDescription operation, as the peer connection could have been
639// modified during the post.
640// TODO(hbos): Remove this class once we remove the version of
641// PeerConnectionInterface::SetRemoteDescription() that takes a
642// SetSessionDescriptionObserver as an argument.
643class PeerConnection::SetRemoteDescriptionObserverAdapter
644 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
645 public:
646 SetRemoteDescriptionObserverAdapter(
647 rtc::scoped_refptr<PeerConnection> pc,
648 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
649 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
650
651 // SetRemoteDescriptionObserverInterface implementation.
652 void OnSetRemoteDescriptionComplete(RTCError error) override {
653 if (error.ok())
654 pc_->PostSetSessionDescriptionSuccess(wrapper_);
655 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100656 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100657 }
658
659 private:
660 rtc::scoped_refptr<PeerConnection> pc_;
661 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
662};
663
deadbeef293e9262017-01-11 12:28:30 -0800664bool PeerConnectionInterface::RTCConfiguration::operator==(
665 const PeerConnectionInterface::RTCConfiguration& o) const {
666 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700667 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800668 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000669 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700670 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800671 BundlePolicy bundle_policy;
672 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700673 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
674 int ice_candidate_pool_size;
675 bool disable_ipv6;
676 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700677 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100678 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700679 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200680 absl::optional<int> screencast_min_bitrate;
681 absl::optional<bool> combined_audio_video_bwe;
682 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800683 TcpCandidatePolicy tcp_candidate_policy;
684 CandidateNetworkPolicy candidate_network_policy;
685 int audio_jitter_buffer_max_packets;
686 bool audio_jitter_buffer_fast_accelerate;
687 int ice_connection_receiving_timeout;
688 int ice_backup_candidate_pair_ping_interval;
689 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800690 bool prioritize_most_likely_ice_candidate_pairs;
691 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800692 bool prune_turn_ports;
693 bool presume_writable_when_fully_relayed;
694 bool enable_ice_renomination;
695 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200696 absl::optional<int> ice_check_interval_strong_connectivity;
697 absl::optional<int> ice_check_interval_weak_connectivity;
698 absl::optional<int> ice_check_min_interval;
699 absl::optional<int> ice_unwritable_timeout;
700 absl::optional<int> ice_unwritable_min_checks;
701 absl::optional<int> stun_candidate_keepalive_interval;
702 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200703 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800704 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200705 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700706 bool active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800707 };
708 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
709 "Did you add something to RTCConfiguration and forget to "
710 "update operator==?");
711 return type == o.type && servers == o.servers &&
712 bundle_policy == o.bundle_policy &&
713 rtcp_mux_policy == o.rtcp_mux_policy &&
714 tcp_candidate_policy == o.tcp_candidate_policy &&
715 candidate_network_policy == o.candidate_network_policy &&
716 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
717 audio_jitter_buffer_fast_accelerate ==
718 o.audio_jitter_buffer_fast_accelerate &&
719 ice_connection_receiving_timeout ==
720 o.ice_connection_receiving_timeout &&
721 ice_backup_candidate_pair_ping_interval ==
722 o.ice_backup_candidate_pair_ping_interval &&
723 continual_gathering_policy == o.continual_gathering_policy &&
724 certificates == o.certificates &&
725 prioritize_most_likely_ice_candidate_pairs ==
726 o.prioritize_most_likely_ice_candidate_pairs &&
727 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800728 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700729 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100730 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800731 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800732 screencast_min_bitrate == o.screencast_min_bitrate &&
733 combined_audio_video_bwe == o.combined_audio_video_bwe &&
734 enable_dtls_srtp == o.enable_dtls_srtp &&
735 ice_candidate_pool_size == o.ice_candidate_pool_size &&
736 prune_turn_ports == o.prune_turn_ports &&
737 presume_writable_when_fully_relayed ==
738 o.presume_writable_when_fully_relayed &&
739 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800740 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800741 ice_check_interval_strong_connectivity ==
742 o.ice_check_interval_strong_connectivity &&
743 ice_check_interval_weak_connectivity ==
744 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700745 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700746 ice_unwritable_timeout == o.ice_unwritable_timeout &&
747 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800748 stun_candidate_keepalive_interval ==
749 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200750 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800751 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800752 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700753 network_preference == o.network_preference &&
754 active_reset_srtp_params == o.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -0800755}
756
757bool PeerConnectionInterface::RTCConfiguration::operator!=(
758 const PeerConnectionInterface::RTCConfiguration& o) const {
759 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800760}
761
zhihuang8f65cdf2016-05-06 18:40:30 -0700762// Generate a RTCP CNAME when a PeerConnection is created.
763std::string GenerateRtcpCname() {
764 std::string cname;
765 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100766 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800767 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700768 }
769 return cname;
770}
771
zhihuang1c378ed2017-08-17 14:10:50 -0700772bool ValidateOfferAnswerOptions(
773 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
774 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
775 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700776}
777
zhihuang1c378ed2017-08-17 14:10:50 -0700778// From |rtc_options|, fill parts of |session_options| shared by all generated
779// m= sections (in other words, nothing that involves a map/array).
780void ExtractSharedMediaSessionOptions(
781 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
782 cricket::MediaSessionOptions* session_options) {
783 session_options->vad_enabled = rtc_options.voice_activity_detection;
784 session_options->bundle_enabled = rtc_options.use_rtp_mux;
785}
zhihuanga77e6bb2017-08-14 18:17:48 -0700786
zhihuang38ede132017-06-15 12:52:32 -0700787PeerConnection::PeerConnection(PeerConnectionFactory* factory,
788 std::unique_ptr<RtcEventLog> event_log,
789 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000790 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700791 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700792 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700793 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700794 remote_streams_(StreamCollection::Create()),
795 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000796
797PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100798 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800799 RTC_DCHECK_RUN_ON(signaling_thread());
800
Steve Anton8af21862017-12-15 11:20:13 -0800801 // Need to stop transceivers before destroying the stats collector because
802 // AudioRtpSender has a reference to the StatsCollector it will update when
803 // stopping.
804 for (auto transceiver : transceivers_) {
805 transceiver->Stop();
806 }
Steve Anton4171afb2017-11-20 10:20:22 -0800807
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700808 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800809 if (stats_collector_) {
810 stats_collector_->WaitForPendingRequest();
811 stats_collector_ = nullptr;
812 }
Steve Anton75737c02017-11-06 10:37:17 -0800813
Steve Anton8af21862017-12-15 11:20:13 -0800814 // Don't destroy BaseChannels until after stats has been cleaned up so that
815 // the last stats request can still read from the channels.
816 DestroyAllChannels();
817
Mirko Bonadei675513b2017-11-09 11:09:25 +0100818 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800819
820 webrtc_session_desc_factory_.reset();
821 sctp_invoker_.reset();
822 sctp_factory_.reset();
823 transport_controller_.reset();
824
deadbeef91dd5672016-05-18 16:55:30 -0700825 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700826 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700827 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700828 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700829 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700830 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800831 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700832 event_log_.reset();
833 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000834}
835
Steve Anton8af21862017-12-15 11:20:13 -0800836void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800837 // Destroy video channels first since they may have a pointer to a voice
838 // channel.
839 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800840 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800841 DestroyTransceiverChannel(transceiver);
842 }
843 }
844 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800845 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800846 DestroyTransceiverChannel(transceiver);
847 }
848 }
849 DestroyDataChannel();
850}
851
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000852bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000853 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700854 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100855 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700856
857 RTCError config_error = ValidateConfiguration(configuration);
858 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100859 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700860 return false;
861 }
862
Benjamin Wrightcab58882018-05-02 15:12:47 -0700863 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100864 RTC_LOG(LS_ERROR)
865 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100866 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800867 return false;
868 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200869
Benjamin Wrightcab58882018-05-02 15:12:47 -0700870 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800871 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100872 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100873 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800874 return false;
875 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700876
Benjamin Wrightcab58882018-05-02 15:12:47 -0700877 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700878 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700879 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700880 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800881
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200882 cricket::ServerAddresses stun_servers;
883 std::vector<cricket::RelayServerConfig> turn_servers;
884
885 RTCErrorType parse_error =
886 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
887 if (parse_error != RTCErrorType::NONE) {
888 return false;
889 }
890
deadbeef91dd5672016-05-18 16:55:30 -0700891 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700892 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700893 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200894 RTC_FROM_HERE,
895 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
896 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000897 return false;
898 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200899 // If initialization was successful, note if STUN or TURN servers
900 // were supplied.
901 if (!stun_servers.empty()) {
902 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
903 }
904 if (!turn_servers.empty()) {
905 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
906 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700908 // Send information about IPv4/IPv6 status.
909 PeerConnectionAddressFamilyCounter address_family;
910 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
911 address_family = kPeerConnection_IPv6;
912 } else {
913 address_family = kPeerConnection_IPv4;
914 }
915 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
916 kPeerConnectionAddressFamilyCounter_Max);
917
Zhi Huange830e682018-03-30 10:48:35 -0700918 const PeerConnectionFactoryInterface::Options& options = factory_->options();
919
Steve Anton75737c02017-11-06 10:37:17 -0800920 // RFC 3264: The numeric value of the session id and version in the
921 // o line MUST be representable with a "64 bit signed integer".
922 // Due to this constraint session id |session_id_| is max limited to
923 // LLONG_MAX.
924 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700925 JsepTransportController::Config config;
926 config.redetermine_role_on_ice_restart =
927 configuration.redetermine_role_on_ice_restart;
928 config.ssl_max_version = factory_->options().ssl_max_version;
929 config.disable_encryption = options.disable_encryption;
930 config.bundle_policy = configuration.bundle_policy;
931 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
932 config.crypto_options = options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700933 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700934 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700935#if defined(ENABLE_EXTERNAL_AUTH)
936 config.enable_external_auth = true;
937#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700938 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Zhi Huange830e682018-03-30 10:48:35 -0700939 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700940 signaling_thread(), network_thread(), port_allocator_.get(),
941 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700942 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800943 this, &PeerConnection::OnTransportControllerConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -0700944 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800945 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -0700946 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800947 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -0700948 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800949 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
950 transport_controller_->SignalDtlsHandshakeError.connect(
951 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
952
953 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700954
deadbeefab9b2d12015-10-14 11:33:11 -0700955 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700956 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000957
Steve Antonba818672017-11-06 10:21:57 -0800958 configuration_ = configuration;
959
Steve Anton75737c02017-11-06 10:37:17 -0800960 // Obtain a certificate from RTCConfiguration if any were provided (optional).
961 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
962 if (!configuration.certificates.empty()) {
963 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
964 // just picking the first one. The decision should be made based on the DTLS
965 // handshake. The DTLS negotiations need to know about all certificates.
966 certificate = configuration.certificates[0];
967 }
968
Steve Antond25da372017-11-06 14:50:29 -0800969 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800970
971 if (options.disable_encryption) {
972 dtls_enabled_ = false;
973 } else {
974 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -0700975 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -0800976 // |configuration| can override the default |dtls_enabled_| value.
977 if (configuration.enable_dtls_srtp) {
978 dtls_enabled_ = *(configuration.enable_dtls_srtp);
979 }
980 }
981
982 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
983 // It takes precendence over the disable_sctp_data_channels
984 // PeerConnectionFactoryInterface::Options.
985 if (configuration.enable_rtp_data_channel) {
986 data_channel_type_ = cricket::DCT_RTP;
987 } else {
988 // DTLS has to be enabled to use SCTP.
989 if (!options.disable_sctp_data_channels && dtls_enabled_) {
990 data_channel_type_ = cricket::DCT_SCTP;
991 }
992 }
993
994 video_options_.screencast_min_bitrate_kbps =
995 configuration.screencast_min_bitrate;
996 audio_options_.combined_audio_video_bwe =
997 configuration.combined_audio_video_bwe;
998
999 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001000 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001001
1002 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001003 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001004
1005 // Whether the certificate generator/certificate is null or not determines
1006 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1007 // the right instructions by clearing the variables if needed.
1008 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001009 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001010 certificate = nullptr;
1011 } else if (certificate) {
1012 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001013 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001014 }
1015
1016 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1017 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001018 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001019 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1020 this, &PeerConnection::OnCertificateReady);
1021
1022 if (options.disable_encryption) {
1023 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1024 }
1025
1026 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1027 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028
Steve Anton4171afb2017-11-20 10:20:22 -08001029 // Add default audio/video transceivers for Plan B SDP.
1030 if (!IsUnifiedPlan()) {
1031 transceivers_.push_back(
1032 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1033 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1034 transceivers_.push_back(
1035 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1036 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1037 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001038 int delay_ms =
1039 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001040 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1041 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042 return true;
1043}
1044
Steve Anton038834f2017-07-14 15:59:59 -07001045RTCError PeerConnection::ValidateConfiguration(
1046 const RTCConfiguration& config) const {
1047 if (config.ice_regather_interval_range &&
1048 config.continual_gathering_policy == GATHER_ONCE) {
1049 return RTCError(RTCErrorType::INVALID_PARAMETER,
1050 "ice_regather_interval_range specified but continual "
1051 "gathering policy is GATHER_ONCE");
1052 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001053 auto result =
1054 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1055 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001056}
1057
Yves Gerey665174f2018-06-19 15:03:05 +02001058rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001059 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1060 "Plan SdpSemantics. Please use GetSenders "
1061 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001062 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001063}
1064
Yves Gerey665174f2018-06-19 15:03:05 +02001065rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001066 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1067 "Plan SdpSemantics. Please use GetReceivers "
1068 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001069 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001070}
1071
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001072bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001073 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1074 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001075 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001076 if (IsClosed()) {
1077 return false;
1078 }
deadbeefab9b2d12015-10-14 11:33:11 -07001079 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001080 return false;
1081 }
deadbeefab9b2d12015-10-14 11:33:11 -07001082
1083 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001084 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1085 observer->SignalAudioTrackAdded.connect(this,
1086 &PeerConnection::OnAudioTrackAdded);
1087 observer->SignalAudioTrackRemoved.connect(
1088 this, &PeerConnection::OnAudioTrackRemoved);
1089 observer->SignalVideoTrackAdded.connect(this,
1090 &PeerConnection::OnVideoTrackAdded);
1091 observer->SignalVideoTrackRemoved.connect(
1092 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001093 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001094
deadbeefab9b2d12015-10-14 11:33:11 -07001095 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001096 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001097 }
1098 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001099 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001100 }
1101
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001102 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001103 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001104 return true;
1105}
1106
1107void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001108 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1109 "Plan SdpSemantics. Please use RemoveTrack "
1110 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001111 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001112 if (!IsClosed()) {
1113 for (const auto& track : local_stream->GetAudioTracks()) {
1114 RemoveAudioTrack(track.get(), local_stream);
1115 }
1116 for (const auto& track : local_stream->GetVideoTracks()) {
1117 RemoveVideoTrack(track.get(), local_stream);
1118 }
deadbeefab9b2d12015-10-14 11:33:11 -07001119 }
deadbeefab9b2d12015-10-14 11:33:11 -07001120 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001121 stream_observers_.erase(
1122 std::remove_if(
1123 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001124 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001125 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001126 }),
1127 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001128
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001129 if (IsClosed()) {
1130 return;
1131 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001132 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001133}
1134
Steve Anton2d6c76a2018-01-05 17:10:52 -08001135RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001136 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001137 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001138 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001139 if (!track) {
1140 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1141 }
1142 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1143 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1144 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1145 "Track has invalid kind: " + track->kind());
1146 }
Steve Antonf9381f02017-12-14 10:23:57 -08001147 if (IsClosed()) {
1148 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1149 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001150 }
Steve Anton4171afb2017-11-20 10:20:22 -08001151 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001152 LOG_AND_RETURN_ERROR(
1153 RTCErrorType::INVALID_PARAMETER,
1154 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001155 }
Steve Antonf9381f02017-12-14 10:23:57 -08001156 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001157 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1158 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001159 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001160 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001161 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001162 }
1163 return sender_or_error;
1164}
deadbeefe1f9d832016-01-14 15:35:42 -08001165
Steve Antonf9381f02017-12-14 10:23:57 -08001166RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1167PeerConnection::AddTrackPlanB(
1168 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001169 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001170 if (stream_ids.size() > 1u) {
1171 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1172 "AddTrack with more than one stream is not "
1173 "supported with Plan B semantics.");
1174 }
1175 std::vector<std::string> adjusted_stream_ids = stream_ids;
1176 if (adjusted_stream_ids.empty()) {
1177 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1178 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001179 cricket::MediaType media_type =
1180 (track->kind() == MediaStreamTrackInterface::kAudioKind
1181 ? cricket::MEDIA_TYPE_AUDIO
1182 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001183 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001184 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001185 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001186 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001187 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001188 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001189 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001190 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001191 if (sender_info) {
1192 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001193 }
Steve Antonf9381f02017-12-14 10:23:57 -08001194 } else {
1195 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001196 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001197 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001198 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001199 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001200 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001201 if (sender_info) {
1202 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001203 }
deadbeefe1f9d832016-01-14 15:35:42 -08001204 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001205 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001206}
deadbeefe1f9d832016-01-14 15:35:42 -08001207
Steve Antonf9381f02017-12-14 10:23:57 -08001208RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1209PeerConnection::AddTrackUnifiedPlan(
1210 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001211 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001212 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1213 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001214 RTC_LOG(LS_INFO) << "Reusing an existing "
1215 << cricket::MediaTypeToString(transceiver->media_type())
1216 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001217 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001218 transceiver->internal()->set_direction(
1219 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001220 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001221 transceiver->internal()->set_direction(
1222 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001223 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001224 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001225 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001226 } else {
1227 cricket::MediaType media_type =
1228 (track->kind() == MediaStreamTrackInterface::kAudioKind
1229 ? cricket::MEDIA_TYPE_AUDIO
1230 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001231 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1232 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001233 std::string sender_id = track->id();
1234 // Avoid creating a sender with an existing ID by generating a random ID.
1235 // This can happen if this is the second time AddTrack has created a sender
1236 // for this track.
1237 if (FindSenderById(sender_id)) {
1238 sender_id = rtc::CreateRandomUuid();
1239 }
Florent Castelli892acf02018-10-01 22:47:20 +02001240 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001241 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1242 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001243 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001244 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001245 }
Steve Antonf9381f02017-12-14 10:23:57 -08001246 return transceiver->sender();
1247}
1248
1249rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1250PeerConnection::FindFirstTransceiverForAddedTrack(
1251 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1252 RTC_DCHECK(track);
1253 for (auto transceiver : transceivers_) {
1254 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001255 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001256 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001257 !transceiver->internal()->has_ever_been_used_to_send() &&
1258 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001259 return transceiver;
1260 }
1261 }
1262 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001263}
1264
1265bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1266 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001267 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001268}
1269
Steve Anton24db5732018-07-23 10:27:33 -07001270RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001271 rtc::scoped_refptr<RtpSenderInterface> sender) {
1272 if (!sender) {
1273 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1274 }
deadbeefe1f9d832016-01-14 15:35:42 -08001275 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001276 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1277 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001278 }
Steve Antonf9381f02017-12-14 10:23:57 -08001279 if (IsUnifiedPlan()) {
1280 auto transceiver = FindTransceiverBySender(sender);
1281 if (!transceiver || !sender->track()) {
1282 return RTCError::OK();
1283 }
1284 sender->SetTrack(nullptr);
1285 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001286 transceiver->internal()->set_direction(
1287 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001288 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001289 transceiver->internal()->set_direction(
1290 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001291 }
Steve Anton4171afb2017-11-20 10:20:22 -08001292 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001293 bool removed;
1294 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1295 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1296 } else {
1297 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1298 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1299 }
1300 if (!removed) {
1301 LOG_AND_RETURN_ERROR(
1302 RTCErrorType::INVALID_PARAMETER,
1303 "Couldn't find sender " + sender->id() + " to remove.");
1304 }
Steve Anton4171afb2017-11-20 10:20:22 -08001305 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001306 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001307 return RTCError::OK();
1308}
1309
1310rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1311PeerConnection::FindTransceiverBySender(
1312 rtc::scoped_refptr<RtpSenderInterface> sender) {
1313 for (auto transceiver : transceivers_) {
1314 if (transceiver->sender() == sender) {
1315 return transceiver;
1316 }
1317 }
1318 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001319}
1320
Steve Anton9158ef62017-11-27 13:01:52 -08001321RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1322PeerConnection::AddTransceiver(
1323 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1324 return AddTransceiver(track, RtpTransceiverInit());
1325}
1326
1327RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1328PeerConnection::AddTransceiver(
1329 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1330 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001331 RTC_CHECK(IsUnifiedPlan())
1332 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001333 if (!track) {
1334 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1335 }
1336 cricket::MediaType media_type;
1337 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1338 media_type = cricket::MEDIA_TYPE_AUDIO;
1339 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1340 media_type = cricket::MEDIA_TYPE_VIDEO;
1341 } else {
1342 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1343 "Track kind is not audio or video");
1344 }
1345 return AddTransceiver(media_type, track, init);
1346}
1347
1348RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1349PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1350 return AddTransceiver(media_type, RtpTransceiverInit());
1351}
1352
1353RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1354PeerConnection::AddTransceiver(cricket::MediaType media_type,
1355 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001356 RTC_CHECK(IsUnifiedPlan())
1357 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001358 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1359 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1360 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1361 "media type is not audio or video");
1362 }
1363 return AddTransceiver(media_type, nullptr, init);
1364}
1365
1366RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1367PeerConnection::AddTransceiver(
1368 cricket::MediaType media_type,
1369 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001370 const RtpTransceiverInit& init,
1371 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001372 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1373 media_type == cricket::MEDIA_TYPE_VIDEO));
1374 if (track) {
1375 RTC_DCHECK_EQ(media_type,
1376 (track->kind() == MediaStreamTrackInterface::kAudioKind
1377 ? cricket::MEDIA_TYPE_AUDIO
1378 : cricket::MEDIA_TYPE_VIDEO));
1379 }
1380
1381 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001382 if (init.send_encodings.size() > 1) {
1383 LOG_AND_RETURN_ERROR(
1384 RTCErrorType::UNSUPPORTED_PARAMETER,
1385 "Attempted to create an encoder with more than 1 encoding parameter.");
1386 }
1387
1388 for (const auto& encoding : init.send_encodings) {
1389 if (encoding.ssrc.has_value()) {
1390 LOG_AND_RETURN_ERROR(
1391 RTCErrorType::UNSUPPORTED_PARAMETER,
1392 "Attempted to set an unimplemented parameter of RtpParameters.");
1393 }
1394 }
1395
1396 RtpParameters parameters;
1397 parameters.encodings = init.send_encodings;
1398 if (UnimplementedRtpParameterHasValue(parameters)) {
1399 LOG_AND_RETURN_ERROR(
1400 RTCErrorType::UNSUPPORTED_PARAMETER,
1401 "Attempted to set an unimplemented parameter of RtpParameters.");
1402 }
Steve Anton9158ef62017-11-27 13:01:52 -08001403
Steve Anton3d954a62018-04-02 11:27:23 -07001404 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1405 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001406 // Set the sender ID equal to the track ID if the track is specified unless
1407 // that sender ID is already in use.
1408 std::string sender_id =
1409 (track && !FindSenderById(track->id()) ? track->id()
1410 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001411 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1412 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001413 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1414 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1415 transceiver->internal()->set_direction(init.direction);
1416
Steve Anton22da89f2018-01-25 13:58:07 -08001417 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001418 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001419 }
Steve Antonf9381f02017-12-14 10:23:57 -08001420
1421 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1422}
1423
Steve Anton02ee47c2018-01-10 16:26:06 -08001424rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1425PeerConnection::CreateSender(
1426 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001427 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001428 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001429 const std::vector<std::string>& stream_ids,
1430 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001431 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001432 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1433 RTC_DCHECK(!track ||
1434 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1435 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1436 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001437 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001438 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001439 } else {
1440 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1441 RTC_DCHECK(!track ||
1442 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1443 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001444 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001445 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001446 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001447 bool set_track_succeeded = sender->SetTrack(track);
1448 RTC_DCHECK(set_track_succeeded);
1449 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001450 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001451 return sender;
1452}
1453
1454rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1455PeerConnection::CreateReceiver(cricket::MediaType media_type,
1456 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001457 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1458 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001459 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001460 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001461 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1462 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001463 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001464 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001465 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001466 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001467 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1468 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001469 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001470 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001471 return receiver;
1472}
1473
1474rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1475PeerConnection::CreateAndAddTransceiver(
1476 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1477 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1478 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001479 // Ensure that the new sender does not have an ID that is already in use by
1480 // another sender.
1481 // Allow receiver IDs to conflict since those come from remote SDP (which
1482 // could be invalid, but should not cause a crash).
1483 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001484 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1485 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001486 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001487 transceiver->internal()->SignalNegotiationNeeded.connect(
1488 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001489 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001490}
1491
Steve Anton52d86772018-02-20 15:48:12 -08001492void PeerConnection::OnNegotiationNeeded() {
1493 RTC_DCHECK_RUN_ON(signaling_thread());
1494 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001495 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001496}
1497
deadbeeffac06552015-11-25 11:26:01 -08001498rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001499 const std::string& kind,
1500 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001501 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1502 "Plan SdpSemantics. Please use AddTransceiver "
1503 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001504 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001505 if (IsClosed()) {
1506 return nullptr;
1507 }
Steve Anton4171afb2017-11-20 10:20:22 -08001508
Seth Hampson5b4f0752018-04-02 16:31:36 -07001509 // Internally we need to have one stream with Plan B semantics, so we
1510 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001511 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001512 if (stream_id.empty()) {
1513 stream_ids.push_back(rtc::CreateRandomUuid());
1514 RTC_LOG(LS_INFO)
1515 << "No stream_id specified for sender. Generated stream ID: "
1516 << stream_ids[0];
1517 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001518 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 }
1520
Steve Anton4171afb2017-11-20 10:20:22 -08001521 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001522 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001523 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001524 auto* audio_sender = new AudioRtpSender(
1525 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001526 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001527 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001528 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001529 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001530 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001531 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001532 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001533 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001534 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001535 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001536 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001537 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001538 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001539 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001540 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001541 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001542
deadbeefe1f9d832016-01-14 15:35:42 -08001543 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001544}
1545
deadbeef70ab1a12015-09-28 16:53:55 -07001546std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1547 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001548 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001549 for (auto sender : GetSendersInternal()) {
1550 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001551 }
1552 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001553}
1554
Steve Anton4171afb2017-11-20 10:20:22 -08001555std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1556PeerConnection::GetSendersInternal() const {
1557 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1558 all_senders;
1559 for (auto transceiver : transceivers_) {
1560 auto senders = transceiver->internal()->senders();
1561 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1562 }
1563 return all_senders;
1564}
1565
deadbeef70ab1a12015-09-28 16:53:55 -07001566std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1567PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001568 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001569 for (const auto& receiver : GetReceiversInternal()) {
1570 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001571 }
1572 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001573}
1574
Steve Anton4171afb2017-11-20 10:20:22 -08001575std::vector<
1576 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1577PeerConnection::GetReceiversInternal() const {
1578 std::vector<
1579 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1580 all_receivers;
1581 for (auto transceiver : transceivers_) {
1582 auto receivers = transceiver->internal()->receivers();
1583 all_receivers.insert(all_receivers.end(), receivers.begin(),
1584 receivers.end());
1585 }
1586 return all_receivers;
1587}
1588
Steve Anton9158ef62017-11-27 13:01:52 -08001589std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1590PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001591 RTC_CHECK(IsUnifiedPlan())
1592 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001593 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1594 for (auto transceiver : transceivers_) {
1595 all_transceivers.push_back(transceiver);
1596 }
1597 return all_transceivers;
1598}
1599
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001600bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001601 MediaStreamTrackInterface* track,
1602 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001603 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001604 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001605 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001606 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001607 return false;
1608 }
1609
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001610 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001611 // The StatsCollector is used to tell if a track is valid because it may
1612 // remember tracks that the PeerConnection previously removed.
1613 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001614 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1615 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001616 return false;
1617 }
Steve Antonad182762018-09-05 20:22:40 +00001618 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1619 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001620 return true;
1621}
1622
hbos74e1a4f2016-09-15 23:33:01 -07001623void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001624 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001625 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001626 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001627 stats_collector_->GetStatsReport(callback);
1628}
1629
Henrik Boström1df1bf82018-03-20 13:24:20 +01001630void PeerConnection::GetStats(
1631 rtc::scoped_refptr<RtpSenderInterface> selector,
1632 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1633 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1634 RTC_DCHECK(callback);
1635 RTC_DCHECK(stats_collector_);
1636 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1637 if (selector) {
1638 for (const auto& proxy_transceiver : transceivers_) {
1639 for (const auto& proxy_sender :
1640 proxy_transceiver->internal()->senders()) {
1641 if (proxy_sender == selector) {
1642 internal_sender = proxy_sender->internal();
1643 break;
1644 }
1645 }
1646 if (internal_sender)
1647 break;
1648 }
1649 }
1650 // If there is no |internal_sender| then |selector| is either null or does not
1651 // belong to the PeerConnection (in Plan B, senders can be removed from the
1652 // PeerConnection). This means that "all the stats objects representing the
1653 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1654 // produces an empty stats report.
1655 stats_collector_->GetStatsReport(internal_sender, callback);
1656}
1657
1658void PeerConnection::GetStats(
1659 rtc::scoped_refptr<RtpReceiverInterface> selector,
1660 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1661 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1662 RTC_DCHECK(callback);
1663 RTC_DCHECK(stats_collector_);
1664 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1665 if (selector) {
1666 for (const auto& proxy_transceiver : transceivers_) {
1667 for (const auto& proxy_receiver :
1668 proxy_transceiver->internal()->receivers()) {
1669 if (proxy_receiver == selector) {
1670 internal_receiver = proxy_receiver->internal();
1671 break;
1672 }
1673 }
1674 if (internal_receiver)
1675 break;
1676 }
1677 }
1678 // If there is no |internal_receiver| then |selector| is either null or does
1679 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1680 // the PeerConnection). This means that "all the stats objects representing
1681 // the selector" is an empty set. Invoking GetStatsReport() with a null
1682 // selector produces an empty stats report.
1683 stats_collector_->GetStatsReport(internal_receiver, callback);
1684}
1685
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001686PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1687 return signaling_state_;
1688}
1689
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001690PeerConnectionInterface::IceConnectionState
1691PeerConnection::ice_connection_state() {
1692 return ice_connection_state_;
1693}
1694
1695PeerConnectionInterface::IceGatheringState
1696PeerConnection::ice_gathering_state() {
1697 return ice_gathering_state_;
1698}
1699
Yves Gerey665174f2018-06-19 15:03:05 +02001700rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001701 const std::string& label,
1702 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001703 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001704
deadbeefab9b2d12015-10-14 11:33:11 -07001705 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001706
kwibergd1fe2812016-04-27 06:47:29 -07001707 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001708 if (config) {
1709 internal_config.reset(new InternalDataChannelInit(*config));
1710 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001711 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001712 InternalCreateDataChannel(label, internal_config.get()));
1713 if (!channel.get()) {
1714 return nullptr;
1715 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001716
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001717 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1718 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001719 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001720 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001721 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001722 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723 return DataChannelProxy::Create(signaling_thread(), channel.get());
1724}
1725
1726void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001727 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001728 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001729
nisse7ce109a2017-01-31 00:57:56 -08001730 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001731 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001732 return;
1733 }
deadbeefab9b2d12015-10-14 11:33:11 -07001734
Steve Anton8d3444d2017-10-20 15:30:51 -07001735 if (IsClosed()) {
1736 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001737 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001738 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001739 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001740 return;
1741 }
1742
zhihuang1c378ed2017-08-17 14:10:50 -07001743 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001744 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001745 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001746 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001747 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001748 return;
1749 }
1750
Steve Anton22da89f2018-01-25 13:58:07 -08001751 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1752 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1753 if (IsUnifiedPlan()) {
1754 RTCError error = HandleLegacyOfferOptions(options);
1755 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001756 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001757 return;
1758 }
1759 }
1760
zhihuang1c378ed2017-08-17 14:10:50 -07001761 cricket::MediaSessionOptions session_options;
1762 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001763 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764}
1765
Steve Anton22da89f2018-01-25 13:58:07 -08001766RTCError PeerConnection::HandleLegacyOfferOptions(
1767 const RTCOfferAnswerOptions& options) {
1768 RTC_DCHECK(IsUnifiedPlan());
1769
1770 if (options.offer_to_receive_audio == 0) {
1771 RemoveRecvDirectionFromReceivingTransceiversOfType(
1772 cricket::MEDIA_TYPE_AUDIO);
1773 } else if (options.offer_to_receive_audio == 1) {
1774 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1775 } else if (options.offer_to_receive_audio > 1) {
1776 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1777 "offer_to_receive_audio > 1 is not supported.");
1778 }
1779
1780 if (options.offer_to_receive_video == 0) {
1781 RemoveRecvDirectionFromReceivingTransceiversOfType(
1782 cricket::MEDIA_TYPE_VIDEO);
1783 } else if (options.offer_to_receive_video == 1) {
1784 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1785 } else if (options.offer_to_receive_video > 1) {
1786 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1787 "offer_to_receive_video > 1 is not supported.");
1788 }
1789
1790 return RTCError::OK();
1791}
1792
1793void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1794 cricket::MediaType media_type) {
1795 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001796 RtpTransceiverDirection new_direction =
1797 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1798 if (new_direction != transceiver->direction()) {
1799 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1800 << " transceiver (MID="
1801 << transceiver->mid().value_or("<not set>") << ") from "
1802 << RtpTransceiverDirectionToString(
1803 transceiver->direction())
1804 << " to "
1805 << RtpTransceiverDirectionToString(new_direction)
1806 << " since CreateOffer specified offer_to_receive=0";
1807 transceiver->internal()->set_direction(new_direction);
1808 }
Steve Anton22da89f2018-01-25 13:58:07 -08001809 }
1810}
1811
1812void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1813 cricket::MediaType media_type) {
1814 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001815 RTC_LOG(LS_INFO)
1816 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1817 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001818 RtpTransceiverInit init;
1819 init.direction = RtpTransceiverDirection::kRecvOnly;
1820 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1821 }
1822}
1823
1824std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1825PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1826 std::vector<
1827 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1828 receiving_transceivers;
1829 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001830 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001831 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1832 receiving_transceivers.push_back(transceiver);
1833 }
1834 }
1835 return receiving_transceivers;
1836}
1837
htaa2a49d92016-03-04 02:51:39 -08001838void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1839 const RTCOfferAnswerOptions& options) {
1840 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001841 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001842 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001843 return;
1844 }
1845
Steve Antondffead82018-02-06 10:31:29 -08001846 if (!(signaling_state_ == kHaveRemoteOffer ||
1847 signaling_state_ == kHaveLocalPrAnswer)) {
1848 std::string error =
1849 "PeerConnection cannot create an answer in a state other than "
1850 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001851 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001852 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001853 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001854 return;
1855 }
1856
Steve Antondffead82018-02-06 10:31:29 -08001857 // The remote description should be set if we're in the right state.
1858 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001859
Steve Anton22da89f2018-01-25 13:58:07 -08001860 if (IsUnifiedPlan()) {
1861 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1862 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1863 "supported with Unified Plan semantics. Use the "
1864 "RtpTransceiver API instead.";
1865 }
1866 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1867 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1868 "supported with Unified Plan semantics. Use the "
1869 "RtpTransceiver API instead.";
1870 }
1871 }
1872
htaa2a49d92016-03-04 02:51:39 -08001873 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001874 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001875
Steve Antond25da372017-11-06 14:50:29 -08001876 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001877}
1878
1879void PeerConnection::SetLocalDescription(
1880 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001881 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001882 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001883
Steve Anton80dd7b52018-02-16 17:08:42 -08001884 // The SetLocalDescription contract is that we take ownership of the session
1885 // description regardless of the outcome, so wrap it in a unique_ptr right
1886 // away. Ideally, SetLocalDescription's signature will be changed to take the
1887 // description as a unique_ptr argument to formalize this agreement.
1888 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1889
nisse7ce109a2017-01-31 00:57:56 -08001890 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001891 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001892 return;
1893 }
Steve Anton8a006912017-12-04 15:25:56 -08001894
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001895 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001896 PostSetSessionDescriptionFailure(
1897 observer,
1898 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001899 return;
1900 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001901
Steve Anton80dd7b52018-02-16 17:08:42 -08001902 // If a session error has occurred the PeerConnection is in a possibly
1903 // inconsistent state so fail right away.
1904 if (session_error() != SessionError::kNone) {
1905 std::string error_message = GetSessionErrorMsg();
1906 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001907 PostSetSessionDescriptionFailure(
1908 observer,
1909 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001910 return;
1911 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001912
Steve Anton80dd7b52018-02-16 17:08:42 -08001913 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1914 if (!error.ok()) {
1915 std::string error_message = GetSetDescriptionErrorMessage(
1916 cricket::CS_LOCAL, desc->GetType(), error);
1917 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001918 PostSetSessionDescriptionFailure(
1919 observer,
1920 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001921 return;
1922 }
1923
1924 // Grab the description type before moving ownership to ApplyLocalDescription,
1925 // which may destroy it before returning.
1926 const SdpType type = desc->GetType();
1927
1928 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001929 // |desc| may be destroyed at this point.
1930
1931 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001932 // If ApplyLocalDescription fails, the PeerConnection could be in an
1933 // inconsistent state, so act conservatively here and set the session error
1934 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1935 SetSessionError(SessionError::kContent, error.message());
1936 std::string error_message =
1937 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1938 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001939 PostSetSessionDescriptionFailure(
1940 observer,
1941 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001942 return;
1943 }
Steve Anton8a006912017-12-04 15:25:56 -08001944 RTC_DCHECK(local_description());
1945
1946 PostSetSessionDescriptionSuccess(observer);
1947
Steve Antonad182762018-09-05 20:22:40 +00001948 // MaybeStartGathering needs to be called after posting
1949 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1950 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001951 transport_controller_->MaybeStartGathering();
1952
Steve Antona3a92c22017-12-07 10:27:41 -08001953 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001954 // TODO(deadbeef): We already had to hop to the network thread for
1955 // MaybeStartGathering...
1956 network_thread()->Invoke<void>(
1957 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1958 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001959 // Make UMA notes about what was agreed to.
1960 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001961 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001962 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001963}
1964
1965RTCError PeerConnection::ApplyLocalDescription(
1966 std::unique_ptr<SessionDescriptionInterface> desc) {
1967 RTC_DCHECK_RUN_ON(signaling_thread());
1968 RTC_DCHECK(desc);
1969
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 // Update stats here so that we have the most recent stats for tracks and
1971 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001972 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001973
Steve Antondcc3c022017-12-22 16:02:54 -08001974 // Take a reference to the old local description since it's used below to
1975 // compare against the new local description. When setting the new local
1976 // description, grab ownership of the replaced session description in case it
1977 // is the same as |old_local_description|, to keep it alive for the duration
1978 // of the method.
1979 const SessionDescriptionInterface* old_local_description =
1980 local_description();
1981 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001982 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001983 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001984 replaced_local_description = pending_local_description_
1985 ? std::move(pending_local_description_)
1986 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001987 current_local_description_ = std::move(desc);
1988 pending_local_description_ = nullptr;
1989 current_remote_description_ = std::move(pending_remote_description_);
1990 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001991 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001992 pending_local_description_ = std::move(desc);
1993 }
1994 // The session description to apply now must be accessed by
1995 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001996 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001997
Zhi Huange830e682018-03-30 10:48:35 -07001998 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1999 if (!error.ok()) {
2000 return error;
2001 }
2002
Steve Antondcc3c022017-12-22 16:02:54 -08002003 if (IsUnifiedPlan()) {
2004 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002005 cricket::CS_LOCAL, *local_description(), old_local_description,
2006 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002007 if (!error.ok()) {
2008 return error;
2009 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002010 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2011 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002012 for (auto transceiver : transceivers_) {
2013 const ContentInfo* content =
2014 FindMediaSectionForTransceiver(transceiver, local_description());
2015 if (!content) {
2016 continue;
2017 }
2018 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002019 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2020 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002021 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002022 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2023 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2024 // "recvonly", process the removal of a remote track for the media
2025 // description, given transceiver, removeList, and muteTracks.
2026 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2027 (transceiver->internal()->fired_direction() &&
2028 RtpTransceiverDirectionHasRecv(
2029 *transceiver->internal()->fired_direction()))) {
2030 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2031 &removed_streams);
2032 }
2033 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2034 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002035 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002036 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002037 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002038 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002039 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002040 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002041 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002042 }
2043 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002044 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002045 }
2046 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002047 // Media channels will be created only when offer is set. These may use new
2048 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002049 if (type == SdpType::kOffer) {
2050 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2051 // description is applied. Restore back to old description.
2052 RTCError error = CreateChannels(*local_description()->description());
2053 if (!error.ok()) {
2054 return error;
2055 }
2056 }
Steve Antondcc3c022017-12-22 16:02:54 -08002057 // Remove unused channels if MediaContentDescription is rejected.
2058 RemoveUnusedChannels(local_description()->description());
2059 }
Steve Anton8a006912017-12-04 15:25:56 -08002060
Zhi Huange830e682018-03-30 10:48:35 -07002061 error = UpdateSessionState(type, cricket::CS_LOCAL,
2062 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002063 if (!error.ok()) {
2064 return error;
2065 }
Steve Antondcc3c022017-12-22 16:02:54 -08002066
Steve Anton8a006912017-12-04 15:25:56 -08002067 if (remote_description()) {
2068 // Now that we have a local description, we can push down remote candidates.
2069 UseCandidatesInSessionDescription(remote_description());
2070 }
2071
2072 pending_ice_restarts_.clear();
2073 if (session_error() != SessionError::kNone) {
2074 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2075 }
2076
deadbeefab9b2d12015-10-14 11:33:11 -07002077 // If setting the description decided our SSL role, allocate any necessary
2078 // SCTP sids.
2079 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002080 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002081 AllocateSctpSids(role);
2082 }
2083
Steve Antond3679212018-01-17 17:41:02 -08002084 if (IsUnifiedPlan()) {
2085 for (auto transceiver : transceivers_) {
2086 const ContentInfo* content =
2087 FindMediaSectionForTransceiver(transceiver, local_description());
2088 if (!content) {
2089 continue;
2090 }
Steve Anton74255ff2018-01-24 18:32:57 -08002091 const auto& streams = content->media_description()->streams();
2092 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002093 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002094 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002095 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002096 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002097 } else {
2098 // 0 is a special value meaning "this sender has no associated send
2099 // stream". Need to call this so the sender won't attempt to configure
2100 // a no longer existing stream and run into DCHECKs in the lower
2101 // layers.
2102 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002103 }
2104 }
2105 } else {
2106 // Plan B semantics.
2107
Steve Antondcc3c022017-12-22 16:02:54 -08002108 // Update state and SSRC of local MediaStreams and DataChannels based on the
2109 // local session description.
2110 const cricket::ContentInfo* audio_content =
2111 GetFirstAudioContent(local_description()->description());
2112 if (audio_content) {
2113 if (audio_content->rejected) {
2114 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2115 } else {
2116 const cricket::AudioContentDescription* audio_desc =
2117 audio_content->media_description()->as_audio();
2118 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2119 }
deadbeeffaac4972015-11-12 15:33:07 -08002120 }
deadbeefab9b2d12015-10-14 11:33:11 -07002121
Steve Antondcc3c022017-12-22 16:02:54 -08002122 const cricket::ContentInfo* video_content =
2123 GetFirstVideoContent(local_description()->description());
2124 if (video_content) {
2125 if (video_content->rejected) {
2126 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2127 } else {
2128 const cricket::VideoContentDescription* video_desc =
2129 video_content->media_description()->as_video();
2130 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2131 }
deadbeeffaac4972015-11-12 15:33:07 -08002132 }
deadbeefab9b2d12015-10-14 11:33:11 -07002133 }
2134
2135 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002136 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002137 if (data_content) {
2138 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002139 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002140 if (rtc::starts_with(data_desc->protocol().data(),
2141 cricket::kMediaProtocolRtpPrefix)) {
2142 UpdateLocalRtpDataChannels(data_desc->streams());
2143 }
2144 }
2145
Steve Anton8a006912017-12-04 15:25:56 -08002146 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002147}
2148
2149void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002150 SetSessionDescriptionObserver* observer,
2151 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002152 SetRemoteDescription(
2153 std::unique_ptr<SessionDescriptionInterface>(desc),
2154 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2155 new SetRemoteDescriptionObserverAdapter(this, observer)));
2156}
2157
2158void PeerConnection::SetRemoteDescription(
2159 std::unique_ptr<SessionDescriptionInterface> desc,
2160 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002161 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002162
nisse7ce109a2017-01-31 00:57:56 -08002163 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002164 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002165 return;
2166 }
Steve Anton8a006912017-12-04 15:25:56 -08002167
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002168 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002169 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002170 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002171 return;
2172 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002173
Steve Anton80dd7b52018-02-16 17:08:42 -08002174 // If a session error has occurred the PeerConnection is in a possibly
2175 // inconsistent state so fail right away.
2176 if (session_error() != SessionError::kNone) {
2177 std::string error_message = GetSessionErrorMsg();
2178 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2179 observer->OnSetRemoteDescriptionComplete(
2180 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2181 return;
2182 }
Steve Anton71439a62018-02-15 11:53:06 -08002183
Steve Antonba42e992018-04-09 14:10:01 -07002184 if (desc->GetType() == SdpType::kOffer) {
2185 // Report to UMA the format of the received offer.
2186 ReportSdpFormatReceived(*desc);
2187 }
2188
Steve Anton80dd7b52018-02-16 17:08:42 -08002189 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002190 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002191 std::string error_message = GetSetDescriptionErrorMessage(
2192 cricket::CS_REMOTE, desc->GetType(), error);
2193 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002194 observer->OnSetRemoteDescriptionComplete(
2195 RTCError(error.type(), std::move(error_message)));
2196 return;
2197 }
Steve Anton71439a62018-02-15 11:53:06 -08002198
Steve Anton80dd7b52018-02-16 17:08:42 -08002199 // Grab the description type before moving ownership to
2200 // ApplyRemoteDescription, which may destroy it before returning.
2201 const SdpType type = desc->GetType();
2202
2203 error = ApplyRemoteDescription(std::move(desc));
2204 // |desc| may be destroyed at this point.
2205
2206 if (!error.ok()) {
2207 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2208 // inconsistent state, so act conservatively here and set the session error
2209 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2210 SetSessionError(SessionError::kContent, error.message());
2211 std::string error_message =
2212 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2213 RTC_LOG(LS_ERROR) << error_message;
2214 observer->OnSetRemoteDescriptionComplete(
2215 RTCError(error.type(), std::move(error_message)));
2216 return;
2217 }
2218 RTC_DCHECK(remote_description());
2219
2220 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002221 // TODO(deadbeef): We already had to hop to the network thread for
2222 // MaybeStartGathering...
2223 network_thread()->Invoke<void>(
2224 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2225 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002226 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002227 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002228 }
2229
2230 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002231 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002232}
2233
2234RTCError PeerConnection::ApplyRemoteDescription(
2235 std::unique_ptr<SessionDescriptionInterface> desc) {
2236 RTC_DCHECK_RUN_ON(signaling_thread());
2237 RTC_DCHECK(desc);
2238
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239 // Update stats here so that we have the most recent stats for tracks and
2240 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002241 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002242
Steve Antondcc3c022017-12-22 16:02:54 -08002243 // Take a reference to the old remote description since it's used below to
2244 // compare against the new remote description. When setting the new remote
2245 // description, grab ownership of the replaced session description in case it
2246 // is the same as |old_remote_description|, to keep it alive for the duration
2247 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002248 const SessionDescriptionInterface* old_remote_description =
2249 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002250 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002251 SdpType type = desc->GetType();
2252 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002253 replaced_remote_description = pending_remote_description_
2254 ? std::move(pending_remote_description_)
2255 : std::move(current_remote_description_);
2256 current_remote_description_ = std::move(desc);
2257 pending_remote_description_ = nullptr;
2258 current_local_description_ = std::move(pending_local_description_);
2259 } else {
2260 replaced_remote_description = std::move(pending_remote_description_);
2261 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002262 }
Steve Anton8a006912017-12-04 15:25:56 -08002263 // The session description to apply now must be accessed by
2264 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002265 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002266
Zhi Huange830e682018-03-30 10:48:35 -07002267 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2268 if (!error.ok()) {
2269 return error;
2270 }
Steve Anton8a006912017-12-04 15:25:56 -08002271 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002272 if (IsUnifiedPlan()) {
2273 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002274 cricket::CS_REMOTE, *remote_description(), local_description(),
2275 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002276 if (!error.ok()) {
2277 return error;
2278 }
Steve Antondcc3c022017-12-22 16:02:54 -08002279 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002280 // Media channels will be created only when offer is set. These may use new
2281 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002282 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002283 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002284 // description is applied. Restore back to old description.
2285 RTCError error = CreateChannels(*remote_description()->description());
2286 if (!error.ok()) {
2287 return error;
2288 }
2289 }
Steve Antondcc3c022017-12-22 16:02:54 -08002290 // Remove unused channels if MediaContentDescription is rejected.
2291 RemoveUnusedChannels(remote_description()->description());
2292 }
Steve Anton8a006912017-12-04 15:25:56 -08002293
Zhi Huange830e682018-03-30 10:48:35 -07002294 // NOTE: Candidates allocation will be initiated only when
2295 // SetLocalDescription is called.
2296 error = UpdateSessionState(type, cricket::CS_REMOTE,
2297 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002298 if (!error.ok()) {
2299 return error;
2300 }
2301
2302 if (local_description() &&
2303 !UseCandidatesInSessionDescription(remote_description())) {
2304 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2305 }
2306
2307 if (old_remote_description) {
2308 for (const cricket::ContentInfo& content :
2309 old_remote_description->description()->contents()) {
2310 // Check if this new SessionDescription contains new ICE ufrag and
2311 // password that indicates the remote peer requests an ICE restart.
2312 // TODO(deadbeef): When we start storing both the current and pending
2313 // remote description, this should reset pending_ice_restarts and compare
2314 // against the current description.
2315 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2316 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002317 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002318 pending_ice_restarts_.insert(content.name);
2319 }
2320 } else {
2321 // We retain all received candidates only if ICE is not restarted.
2322 // When ICE is restarted, all previous candidates belong to an old
2323 // generation and should not be kept.
2324 // TODO(deadbeef): This goes against the W3C spec which says the remote
2325 // description should only contain candidates from the last set remote
2326 // description plus any candidates added since then. We should remove
2327 // this once we're sure it won't break anything.
2328 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2329 old_remote_description, content.name, mutable_remote_description());
2330 }
2331 }
2332 }
2333
2334 if (session_error() != SessionError::kNone) {
2335 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2336 }
2337
2338 // Set the the ICE connection state to connecting since the connection may
2339 // become writable with peer reflexive candidates before any remote candidate
2340 // is signaled.
2341 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2342 // is to have a new signal the indicates a change in checking state from the
2343 // transport and expose a new checking() member from transport that can be
2344 // read to determine the current checking state. The existing SignalConnecting
2345 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002346 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002347 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002348 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2349 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2350 }
2351
deadbeefab9b2d12015-10-14 11:33:11 -07002352 // If setting the description decided our SSL role, allocate any necessary
2353 // SCTP sids.
2354 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002355 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002356 AllocateSctpSids(role);
2357 }
2358
Steve Antondcc3c022017-12-22 16:02:54 -08002359 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002360 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002361 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002362 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002363 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002364 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002365 for (auto transceiver : transceivers_) {
2366 const ContentInfo* content =
2367 FindMediaSectionForTransceiver(transceiver, remote_description());
2368 if (!content) {
2369 continue;
2370 }
2371 const MediaContentDescription* media_desc = content->media_description();
2372 RtpTransceiverDirection local_direction =
2373 RtpTransceiverDirectionReversed(media_desc->direction());
2374 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2375 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2376 // transceiver's current direction is neither sendrecv nor recvonly,
2377 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002378 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002379 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002380 // The remote description has signaled the stream IDs.
2381 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002382 }
Steve Antondcc3c022017-12-22 16:02:54 -08002383 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002384 (!transceiver->fired_direction() ||
2385 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002386 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002387 << content->name << " (added to "
2388 << GetStreamIdsString(stream_ids) << ").";
2389
2390 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2391 for (const std::string& stream_id : stream_ids) {
2392 rtc::scoped_refptr<MediaStreamInterface> stream =
2393 remote_streams_->find(stream_id);
2394 if (!stream) {
2395 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2396 MediaStream::Create(stream_id));
2397 remote_streams_->AddStream(stream);
2398 added_streams.push_back(stream);
2399 }
2400 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002401 }
Steve Anton3172c032018-05-03 15:30:18 -07002402 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002403 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2404 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002405 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002406 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002407 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002408 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2409 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2410 // removal of a remote track for the media description, given transceiver,
2411 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002412 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002413 (transceiver->fired_direction() &&
2414 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2415 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2416 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002417 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002418 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2419 transceiver->internal()->set_fired_direction(local_direction);
2420 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2421 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002422 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002423 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2424 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002425 transceiver->internal()->set_current_direction(local_direction);
2426 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002427 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2428 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002429 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002430 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2431 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002432 transceiver->Stop();
2433 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002434 if (!content->rejected &&
2435 RtpTransceiverDirectionHasRecv(local_direction)) {
2436 // Set ssrc to 0 in the case of an unsignalled ssrc.
2437 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002438 if (!media_desc->streams().empty() &&
2439 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002440 ssrc = media_desc->streams()[0].first_ssrc();
2441 }
2442 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002443 }
Steve Antondcc3c022017-12-22 16:02:54 -08002444 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002445 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002446 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002447 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002448 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002449 observer->OnTrack(transceiver);
2450 observer->OnAddTrack(transceiver->receiver(),
2451 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002452 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002453 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002454 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002455 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002456 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002457 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002458 }
2459 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002460 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002461 }
Steve Antondcc3c022017-12-22 16:02:54 -08002462 }
2463
Henrik Boströmfdb92012017-11-09 19:55:44 +01002464 const cricket::ContentInfo* audio_content =
2465 GetFirstAudioContent(remote_description()->description());
2466 const cricket::ContentInfo* video_content =
2467 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002468 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002469 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002470 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002471 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002472 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002473 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002474
2475 // Check if the descriptions include streams, just in case the peer supports
2476 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002477 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002478 (audio_desc && !audio_desc->streams().empty()) ||
2479 (video_desc && !video_desc->streams().empty())) {
2480 remote_peer_supports_msid_ = true;
2481 }
deadbeefab9b2d12015-10-14 11:33:11 -07002482
2483 // We wait to signal new streams until we finish processing the description,
2484 // since only at that point will new streams have all their tracks.
2485 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2486
Steve Antondcc3c022017-12-22 16:02:54 -08002487 if (!IsUnifiedPlan()) {
2488 // TODO(steveanton): When removing RTP senders/receivers in response to a
2489 // rejected media section, there is some cleanup logic that expects the
2490 // voice/ video channel to still be set. But in this method the voice/video
2491 // channel would have been destroyed by the SetRemoteDescription caller
2492 // above so the cleanup that relies on them fails to run. The RemoveSenders
2493 // calls should be moved to right before the DestroyChannel calls to fix
2494 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002495
Steve Antondcc3c022017-12-22 16:02:54 -08002496 // Find all audio rtp streams and create corresponding remote AudioTracks
2497 // and MediaStreams.
2498 if (audio_content) {
2499 if (audio_content->rejected) {
2500 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2501 } else {
2502 bool default_audio_track_needed =
2503 !remote_peer_supports_msid_ &&
2504 RtpTransceiverDirectionHasSend(audio_desc->direction());
2505 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2506 default_audio_track_needed, audio_desc->type(),
2507 new_streams);
2508 }
deadbeeffaac4972015-11-12 15:33:07 -08002509 }
deadbeefab9b2d12015-10-14 11:33:11 -07002510
Steve Antondcc3c022017-12-22 16:02:54 -08002511 // Find all video rtp streams and create corresponding remote VideoTracks
2512 // and MediaStreams.
2513 if (video_content) {
2514 if (video_content->rejected) {
2515 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2516 } else {
2517 bool default_video_track_needed =
2518 !remote_peer_supports_msid_ &&
2519 RtpTransceiverDirectionHasSend(video_desc->direction());
2520 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2521 default_video_track_needed, video_desc->type(),
2522 new_streams);
2523 }
deadbeeffaac4972015-11-12 15:33:07 -08002524 }
deadbeefab9b2d12015-10-14 11:33:11 -07002525
Steve Antondcc3c022017-12-22 16:02:54 -08002526 // Update the DataChannels with the information from the remote peer.
2527 if (data_desc) {
2528 if (rtc::starts_with(data_desc->protocol().data(),
2529 cricket::kMediaProtocolRtpPrefix)) {
2530 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2531 }
deadbeefab9b2d12015-10-14 11:33:11 -07002532 }
deadbeefab9b2d12015-10-14 11:33:11 -07002533
Steve Antondcc3c022017-12-22 16:02:54 -08002534 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002535 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002536 for (size_t i = 0; i < new_streams->count(); ++i) {
2537 MediaStreamInterface* new_stream = new_streams->at(i);
2538 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002539 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002540 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2541 }
deadbeefab9b2d12015-10-14 11:33:11 -07002542
Steve Antondcc3c022017-12-22 16:02:54 -08002543 UpdateEndedRemoteMediaStreams();
2544 }
deadbeefab9b2d12015-10-14 11:33:11 -07002545
Steve Anton8a006912017-12-04 15:25:56 -08002546 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002547}
2548
Steve Anton0f5400a2018-07-17 14:25:36 -07002549void PeerConnection::ProcessRemovalOfRemoteTrack(
2550 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2551 transceiver,
2552 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2553 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2554 RTC_DCHECK(transceiver->mid());
2555 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2556 << *transceiver->mid();
2557 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2558 transceiver->internal()->receiver_internal()->streams();
2559 // This will remove the remote track from the streams.
2560 transceiver->internal()->receiver_internal()->set_stream_ids({});
2561 remove_list->push_back(transceiver);
2562 // Remove any streams that no longer have tracks.
2563 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2564 // of streams, see if the stream was removed by checking if this was the
2565 // last receiver with that stream ID.
2566 for (auto stream : media_streams) {
2567 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2568 remote_streams_->RemoveStream(stream);
2569 removed_streams->push_back(stream);
2570 }
2571 }
2572}
2573
Steve Antondcc3c022017-12-22 16:02:54 -08002574RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2575 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002576 const SessionDescriptionInterface& new_session,
2577 const SessionDescriptionInterface* old_local_description,
2578 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002579 RTC_DCHECK(IsUnifiedPlan());
2580
Steve Anton7464fca2018-01-19 11:10:37 -08002581 const cricket::ContentGroup* bundle_group = nullptr;
2582 if (new_session.GetType() == SdpType::kOffer) {
2583 auto bundle_group_or_error =
2584 GetEarlyBundleGroup(*new_session.description());
2585 if (!bundle_group_or_error.ok()) {
2586 return bundle_group_or_error.MoveError();
2587 }
2588 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002589 }
Steve Antondcc3c022017-12-22 16:02:54 -08002590
Steve Antondcc3c022017-12-22 16:02:54 -08002591 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002592 for (size_t i = 0; i < new_contents.size(); ++i) {
2593 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002594 cricket::MediaType media_type = new_content.media_description()->type();
2595 seen_mids_.insert(new_content.name);
2596 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2597 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002598 const cricket::ContentInfo* old_local_content = nullptr;
2599 if (old_local_description &&
2600 i < old_local_description->description()->contents().size()) {
2601 old_local_content =
2602 &old_local_description->description()->contents()[i];
2603 }
2604 const cricket::ContentInfo* old_remote_content = nullptr;
2605 if (old_remote_description &&
2606 i < old_remote_description->description()->contents().size()) {
2607 old_remote_content =
2608 &old_remote_description->description()->contents()[i];
2609 }
Steve Antondcc3c022017-12-22 16:02:54 -08002610 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002611 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2612 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002613 if (!transceiver_or_error.ok()) {
2614 return transceiver_or_error.MoveError();
2615 }
2616 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002617 RTCError error =
2618 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2619 if (!error.ok()) {
2620 return error;
2621 }
2622 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002623 if (GetDataMid() && new_content.name != *GetDataMid()) {
2624 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002625 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2626 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002627 continue;
2628 }
2629 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2630 if (!error.ok()) {
2631 return error;
2632 }
Steve Antondcc3c022017-12-22 16:02:54 -08002633 } else {
2634 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2635 "Unknown section type.");
2636 }
2637 }
2638
2639 return RTCError::OK();
2640}
2641
2642RTCError PeerConnection::UpdateTransceiverChannel(
2643 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2644 transceiver,
2645 const cricket::ContentInfo& content,
2646 const cricket::ContentGroup* bundle_group) {
2647 RTC_DCHECK(IsUnifiedPlan());
2648 RTC_DCHECK(transceiver);
2649 cricket::BaseChannel* channel = transceiver->internal()->channel();
2650 if (content.rejected) {
2651 if (channel) {
2652 transceiver->internal()->SetChannel(nullptr);
2653 DestroyBaseChannel(channel);
2654 }
2655 } else {
2656 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002657 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002658 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002659 } else {
Steve Anton69470252018-02-09 11:43:08 -08002660 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002661 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002662 }
2663 if (!channel) {
2664 LOG_AND_RETURN_ERROR(
2665 RTCErrorType::INTERNAL_ERROR,
2666 "Failed to create channel for mid=" + content.name);
2667 }
2668 transceiver->internal()->SetChannel(channel);
2669 }
2670 }
2671 return RTCError::OK();
2672}
2673
Steve Antonfa2260d2017-12-28 16:38:23 -08002674RTCError PeerConnection::UpdateDataChannel(
2675 cricket::ContentSource source,
2676 const cricket::ContentInfo& content,
2677 const cricket::ContentGroup* bundle_group) {
2678 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002679 // If data channels are disabled, ignore this media section. CreateAnswer
2680 // will take care of rejecting it.
2681 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002682 }
2683 if (content.rejected) {
2684 DestroyDataChannel();
2685 } else {
2686 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002687 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002688 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2689 "Failed to create data channel.");
2690 }
2691 }
2692 if (source == cricket::CS_REMOTE) {
2693 const MediaContentDescription* data_desc = content.media_description();
2694 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2695 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2696 }
2697 }
2698 }
2699 return RTCError::OK();
2700}
2701
Steve Antondcc3c022017-12-22 16:02:54 -08002702RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2703PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002704 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002705 size_t mline_index,
2706 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002707 const ContentInfo* old_local_content,
2708 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002709 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002710 // If this is an offer then the m= section might be recycled. If the m=
2711 // section is being recycled (defined as: rejected in the current local or
2712 // remote description and not rejected in new description), dissociate the
2713 // currently associated RtpTransceiver by setting its mid property to null,
2714 // and discard the mapping between the transceiver and its m= section index.
2715 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2716 old_remote_content)) {
2717 // We want to dissociate the transceiver that has the rejected mid.
2718 const std::string& old_mid =
2719 (old_local_content && old_local_content->rejected)
2720 ? old_local_content->name
2721 : old_remote_content->name;
2722 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002723 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002724 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2725 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002726 old_transceiver->internal()->set_mid(absl::nullopt);
2727 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002728 }
2729 }
2730 const MediaContentDescription* media_desc = content.media_description();
2731 auto transceiver = GetAssociatedTransceiver(content.name);
2732 if (source == cricket::CS_LOCAL) {
2733 // Find the RtpTransceiver that corresponds to this m= section, using the
2734 // mapping between transceivers and m= section indices established when
2735 // creating the offer.
2736 if (!transceiver) {
2737 transceiver = GetTransceiverByMLineIndex(mline_index);
2738 }
2739 if (!transceiver) {
2740 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2741 "Unknown transceiver");
2742 }
2743 } else {
2744 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2745 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2746 // of the same type...
2747 if (!transceiver &&
2748 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2749 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2750 }
2751 // If no RtpTransceiver was found in the previous step, create one with a
2752 // recvonly direction.
2753 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002754 RTC_LOG(LS_INFO) << "Adding "
2755 << cricket::MediaTypeToString(media_desc->type())
2756 << " transceiver for MID=" << content.name
2757 << " at i=" << mline_index
2758 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002759 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002760 auto sender =
2761 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002762 std::string receiver_id;
2763 if (!media_desc->streams().empty()) {
2764 receiver_id = media_desc->streams()[0].id;
2765 } else {
2766 receiver_id = rtc::CreateRandomUuid();
2767 }
2768 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002769 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002770 transceiver->internal()->set_direction(
2771 RtpTransceiverDirection::kRecvOnly);
2772 }
2773 }
2774 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002775 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002776 LOG_AND_RETURN_ERROR(
2777 RTCErrorType::INVALID_PARAMETER,
2778 "Transceiver type does not match media description type.");
2779 }
2780 // Associate the found or created RtpTransceiver with the m= section by
2781 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2782 // section, and establish a mapping between the transceiver and the index of
2783 // the m= section.
2784 transceiver->internal()->set_mid(content.name);
2785 transceiver->internal()->set_mline_index(mline_index);
2786 return std::move(transceiver);
2787}
2788
2789rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2790PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2791 RTC_DCHECK(IsUnifiedPlan());
2792 for (auto transceiver : transceivers_) {
2793 if (transceiver->mid() == mid) {
2794 return transceiver;
2795 }
2796 }
2797 return nullptr;
2798}
2799
2800rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2801PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2802 RTC_DCHECK(IsUnifiedPlan());
2803 for (auto transceiver : transceivers_) {
2804 if (transceiver->internal()->mline_index() == mline_index) {
2805 return transceiver;
2806 }
2807 }
2808 return nullptr;
2809}
2810
2811rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2812PeerConnection::FindAvailableTransceiverToReceive(
2813 cricket::MediaType media_type) const {
2814 RTC_DCHECK(IsUnifiedPlan());
2815 // From JSEP section 5.10 (Applying a Remote Description):
2816 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2817 // the same type that were added to the PeerConnection by addTrack and are not
2818 // associated with any m= section and are not stopped, find the first such
2819 // RtpTransceiver.
2820 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002821 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002822 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2823 !transceiver->stopped()) {
2824 return transceiver;
2825 }
2826 }
2827 return nullptr;
2828}
2829
Steve Antoned10bd92017-12-05 10:52:59 -08002830const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2831 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2832 transceiver,
2833 const SessionDescriptionInterface* sdesc) const {
2834 RTC_DCHECK(transceiver);
2835 RTC_DCHECK(sdesc);
2836 if (IsUnifiedPlan()) {
2837 if (!transceiver->internal()->mid()) {
2838 // This transceiver is not associated with a media section yet.
2839 return nullptr;
2840 }
2841 return sdesc->description()->GetContentByName(
2842 *transceiver->internal()->mid());
2843 } else {
2844 // Plan B only allows at most one audio and one video section, so use the
2845 // first media section of that type.
2846 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002847 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002848 }
2849}
2850
deadbeef46c73892016-11-16 19:42:04 -08002851PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2852 return configuration_;
2853}
2854
deadbeef293e9262017-01-11 12:28:30 -08002855bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2856 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002857 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002858 if (IsClosed()) {
2859 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2860 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2861 }
2862
Qingsi Wanga2d60672018-04-11 16:57:45 -07002863 // According to JSEP, after setLocalDescription, changing the candidate pool
2864 // size is not allowed, and changing the set of ICE servers will not result
2865 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002866 if (local_description() && configuration.ice_candidate_pool_size !=
2867 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002868 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2869 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002870 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002871 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002872
deadbeef293e9262017-01-11 12:28:30 -08002873 // The simplest (and most future-compatible) way to tell if the config was
2874 // modified in an invalid way is to copy each property we do support
2875 // modifying, then use operator==. There are far more properties we don't
2876 // support modifying than those we do, and more could be added.
2877 RTCConfiguration modified_config = configuration_;
2878 modified_config.servers = configuration.servers;
2879 modified_config.type = configuration.type;
2880 modified_config.ice_candidate_pool_size =
2881 configuration.ice_candidate_pool_size;
2882 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002883 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002884 modified_config.ice_check_interval_strong_connectivity =
2885 configuration.ice_check_interval_strong_connectivity;
2886 modified_config.ice_check_interval_weak_connectivity =
2887 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002888 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2889 modified_config.ice_unwritable_min_checks =
2890 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002891 modified_config.stun_candidate_keepalive_interval =
2892 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002893 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002894 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002895 modified_config.active_reset_srtp_params =
2896 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002897 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002898 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002899 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2900 }
2901
Steve Anton038834f2017-07-14 15:59:59 -07002902 // Validate the modified configuration.
2903 RTCError validate_error = ValidateConfiguration(modified_config);
2904 if (!validate_error.ok()) {
2905 return SafeSetError(std::move(validate_error), error);
2906 }
2907
deadbeef293e9262017-01-11 12:28:30 -08002908 // Note that this isn't possible through chromium, since it's an unsigned
2909 // short in WebIDL.
2910 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002911 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002912 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2913 }
2914
2915 // Parse ICE servers before hopping to network thread.
2916 cricket::ServerAddresses stun_servers;
2917 std::vector<cricket::RelayServerConfig> turn_servers;
2918 RTCErrorType parse_error =
2919 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2920 if (parse_error != RTCErrorType::NONE) {
2921 return SafeSetError(parse_error, error);
2922 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002923 // Note if STUN or TURN servers were supplied.
2924 if (!stun_servers.empty()) {
2925 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2926 }
2927 if (!turn_servers.empty()) {
2928 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2929 }
deadbeef293e9262017-01-11 12:28:30 -08002930
2931 // In theory this shouldn't fail.
2932 if (!network_thread()->Invoke<bool>(
2933 RTC_FROM_HERE,
2934 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2935 stun_servers, turn_servers, modified_config.type,
2936 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002937 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002938 modified_config.turn_customizer,
2939 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002940 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002941 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2942 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002943
deadbeefd1a38b52016-12-10 13:15:33 -08002944 // As described in JSEP, calling setConfiguration with new ICE servers or
2945 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2946 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002947 if (modified_config.servers != configuration_.servers ||
2948 modified_config.type != configuration_.type ||
2949 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002950 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002951 }
skvladd1f5fda2017-02-03 16:54:05 -08002952
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002953 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002954
Zhi Huangb57e1692018-06-12 11:41:11 -07002955 if (configuration_.active_reset_srtp_params !=
2956 modified_config.active_reset_srtp_params) {
2957 transport_controller_->SetActiveResetSrtpParams(
2958 modified_config.active_reset_srtp_params);
2959 }
2960
deadbeef293e9262017-01-11 12:28:30 -08002961 configuration_ = modified_config;
2962 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002963}
2964
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002965bool PeerConnection::AddIceCandidate(
2966 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002967 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002968 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002969 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002970 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002971 return false;
2972 }
Steve Antond25da372017-11-06 14:50:29 -08002973
2974 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002975 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002976 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002977 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002978 return false;
2979 }
2980
2981 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002982 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002983 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002984 return false;
2985 }
2986
2987 bool valid = false;
2988 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2989 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002990 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002991 return false;
2992 }
2993
2994 // Add this candidate to the remote session description.
2995 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002996 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002997 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002998 return false;
2999 }
3000
3001 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003002 bool result = UseCandidate(ice_candidate);
3003 if (result) {
3004 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3005 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3006 } else {
3007 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3008 }
3009 return result;
Steve Antond25da372017-11-06 14:50:29 -08003010 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003011 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003012 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003013 return true;
3014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003015}
3016
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003017bool PeerConnection::RemoveIceCandidates(
3018 const std::vector<cricket::Candidate>& candidates) {
3019 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003020 if (IsClosed()) {
3021 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3022 return false;
3023 }
3024
Steve Antond25da372017-11-06 14:50:29 -08003025 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003026 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3027 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003028 return false;
3029 }
3030
3031 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003032 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003033 return false;
3034 }
3035
3036 size_t number_removed =
3037 mutable_remote_description()->RemoveCandidates(candidates);
3038 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003039 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003040 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003041 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003042 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003043 }
3044
3045 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003046 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3047 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003048 RTC_LOG(LS_ERROR)
3049 << "RemoveIceCandidates: Error when removing remote candidates: "
3050 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003051 }
3052 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003053}
3054
Niels Möller0c4f7be2018-05-07 14:01:37 +02003055RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003056 if (!worker_thread()->IsCurrent()) {
3057 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003058 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003059 }
3060
Niels Möller0c4f7be2018-05-07 14:01:37 +02003061 const bool has_min = bitrate.min_bitrate_bps.has_value();
3062 const bool has_start = bitrate.start_bitrate_bps.has_value();
3063 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003064 if (has_min && *bitrate.min_bitrate_bps < 0) {
3065 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3066 "min_bitrate_bps <= 0");
3067 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003068 if (has_start) {
3069 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003071 "start_bitrate_bps < min_bitrate_bps");
3072 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003073 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3074 "curent_bitrate_bps < 0");
3075 }
3076 }
3077 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003078 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003079 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003080 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003081 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3082 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3083 "max_bitrate_bps < min_bitrate_bps");
3084 } else if (*bitrate.max_bitrate_bps < 0) {
3085 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3086 "max_bitrate_bps < 0");
3087 }
3088 }
3089
zstein4b979802017-06-02 14:37:37 -07003090 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003091 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003092
3093 return RTCError::OK();
3094}
3095
Alex Narest78609d52017-10-20 10:37:47 +02003096void PeerConnection::SetBitrateAllocationStrategy(
3097 std::unique_ptr<rtc::BitrateAllocationStrategy>
3098 bitrate_allocation_strategy) {
3099 rtc::Thread* worker_thread = factory_->worker_thread();
3100 if (!worker_thread->IsCurrent()) {
3101 rtc::BitrateAllocationStrategy* strategy_raw =
3102 bitrate_allocation_strategy.release();
3103 auto functor = [this, strategy_raw]() {
3104 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003105 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003106 };
3107 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3108 return;
3109 }
3110 RTC_DCHECK(call_.get());
3111 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3112}
3113
henrika5f6bf242017-11-01 11:06:56 +01003114void PeerConnection::SetAudioPlayout(bool playout) {
3115 if (!worker_thread()->IsCurrent()) {
3116 worker_thread()->Invoke<void>(
3117 RTC_FROM_HERE,
3118 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3119 return;
3120 }
3121 auto audio_state =
3122 factory_->channel_manager()->media_engine()->GetAudioState();
3123 audio_state->SetPlayout(playout);
3124}
3125
3126void PeerConnection::SetAudioRecording(bool recording) {
3127 if (!worker_thread()->IsCurrent()) {
3128 worker_thread()->Invoke<void>(
3129 RTC_FROM_HERE,
3130 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3131 return;
3132 }
3133 auto audio_state =
3134 factory_->channel_manager()->media_engine()->GetAudioState();
3135 audio_state->SetRecording(recording);
3136}
3137
Steve Anton8c0f7a72017-10-03 10:03:10 -07003138std::unique_ptr<rtc::SSLCertificate>
3139PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003140 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3141 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003142 return nullptr;
3143 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003144 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003145}
3146
Zhi Huang70b820f2018-01-27 14:16:15 -08003147std::unique_ptr<rtc::SSLCertChain>
3148PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003149 auto audio_transceiver = GetFirstAudioTransceiver();
3150 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003151 return nullptr;
3152 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003153 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003154 audio_transceiver->internal()->channel()->transport_name());
3155}
3156
3157rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3158PeerConnection::GetFirstAudioTransceiver() const {
3159 for (auto transceiver : transceivers_) {
3160 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3161 return transceiver;
3162 }
3163 }
3164 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003165}
3166
ivoc14d5dbe2016-07-04 07:06:55 -07003167bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3168 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003169 // TODO(eladalon): It would be better to not allow negative values into PC.
3170 const size_t max_size = (max_size_bytes < 0)
3171 ? RtcEventLog::kUnlimitedOutput
3172 : rtc::saturated_cast<size_t>(max_size_bytes);
3173 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003174 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003175 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003176}
3177
Bjorn Tereliusde939432017-11-20 17:38:14 +01003178bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3179 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003180 // TODO(eladalon): In C++14, this can be done with a lambda.
3181 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003182 bool operator()() {
3183 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3184 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003185 PeerConnection* const pc;
3186 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003187 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003188 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003189 return worker_thread()->Invoke<bool>(
3190 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003191}
3192
3193void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003194 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003195 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3196}
3197
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003198const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003199 return pending_local_description_ ? pending_local_description_.get()
3200 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003201}
3202
3203const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003204 return pending_remote_description_ ? pending_remote_description_.get()
3205 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003206}
3207
deadbeeffe4a8a42016-12-20 17:56:17 -08003208const SessionDescriptionInterface* PeerConnection::current_local_description()
3209 const {
Steve Anton75737c02017-11-06 10:37:17 -08003210 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003211}
3212
3213const SessionDescriptionInterface* PeerConnection::current_remote_description()
3214 const {
Steve Anton75737c02017-11-06 10:37:17 -08003215 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003216}
3217
3218const SessionDescriptionInterface* PeerConnection::pending_local_description()
3219 const {
Steve Anton75737c02017-11-06 10:37:17 -08003220 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003221}
3222
3223const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3224 const {
Steve Anton75737c02017-11-06 10:37:17 -08003225 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003226}
3227
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003228void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003229 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003230 // Update stats here so that we have the most recent stats for tracks and
3231 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003232 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003233
Steve Anton75737c02017-11-06 10:37:17 -08003234 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003235 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003236
Steve Anton8af21862017-12-15 11:20:13 -08003237 for (auto transceiver : transceivers_) {
3238 transceiver->Stop();
3239 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003240
3241 // Ensure that all asynchronous stats requests are completed before destroying
3242 // the transport controller below.
3243 if (stats_collector_) {
3244 stats_collector_->WaitForPendingRequest();
3245 }
3246
3247 // Don't destroy BaseChannels until after stats has been cleaned up so that
3248 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003249 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003250
Qingsi Wang93a84392018-01-30 17:13:09 -08003251 // The event log is used in the transport controller, which must be outlived
3252 // by the former. CreateOffer by the peer connection is implemented
3253 // asynchronously and if the peer connection is closed without resetting the
3254 // WebRTC session description factory, the session description factory would
3255 // call the transport controller.
3256 webrtc_session_desc_factory_.reset();
3257 transport_controller_.reset();
3258
deadbeef42a42632017-03-10 15:18:00 -08003259 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003260 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3261 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003262
Steve Anton978b8762017-09-29 12:15:02 -07003263 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003264 call_.reset();
3265 // The event log must outlive call (and any other object that uses it).
3266 event_log_.reset();
3267 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003268 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003269 // The .h file says that observer can be discarded after close() returns.
3270 // Make sure this is true.
3271 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003272}
3273
Steve Antonad182762018-09-05 20:22:40 +00003274void PeerConnection::OnMessage(rtc::Message* msg) {
3275 switch (msg->message_id) {
3276 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3277 SetSessionDescriptionMsg* param =
3278 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3279 param->observer->OnSuccess();
3280 delete param;
3281 break;
3282 }
3283 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3284 SetSessionDescriptionMsg* param =
3285 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3286 param->observer->OnFailure(std::move(param->error));
3287 delete param;
3288 break;
3289 }
3290 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3291 CreateSessionDescriptionMsg* param =
3292 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3293 param->observer->OnFailure(std::move(param->error));
3294 delete param;
3295 break;
3296 }
3297 case MSG_GETSTATS: {
3298 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3299 StatsReports reports;
3300 stats_->GetStats(param->track, &reports);
3301 param->observer->OnComplete(reports);
3302 delete param;
3303 break;
3304 }
3305 case MSG_FREE_DATACHANNELS: {
3306 sctp_data_channels_to_free_.clear();
3307 break;
3308 }
3309 case MSG_REPORT_USAGE_PATTERN: {
3310 ReportUsagePattern();
3311 break;
3312 }
3313 default:
3314 RTC_NOTREACHED() << "Not implemented";
3315 break;
3316 }
3317}
3318
Steve Antonafb0bb72018-02-20 11:35:37 -08003319cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3320 RTC_DCHECK(!IsUnifiedPlan());
3321 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3322 GetAudioTransceiver()->internal()->channel());
3323 if (voice_channel) {
3324 return voice_channel->media_channel();
3325 } else {
3326 return nullptr;
3327 }
3328}
3329
3330cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3331 RTC_DCHECK(!IsUnifiedPlan());
3332 auto* video_channel = static_cast<cricket::VideoChannel*>(
3333 GetVideoTransceiver()->internal()->channel());
3334 if (video_channel) {
3335 return video_channel->media_channel();
3336 } else {
3337 return nullptr;
3338 }
3339}
3340
Steve Anton4171afb2017-11-20 10:20:22 -08003341void PeerConnection::CreateAudioReceiver(
3342 MediaStreamInterface* stream,
3343 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003344 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3345 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003346 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3347 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003348 auto* audio_receiver = new AudioRtpReceiver(
3349 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003350 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003351 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3352 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3353 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003354 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003355 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003356 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003357}
3358
Steve Anton4171afb2017-11-20 10:20:22 -08003359void PeerConnection::CreateVideoReceiver(
3360 MediaStreamInterface* stream,
3361 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003362 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3363 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003364 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3365 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003366 auto* video_receiver = new VideoRtpReceiver(
3367 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003368 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003369 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3370 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3371 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003372 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003373 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003374 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003375}
3376
deadbeef70ab1a12015-09-28 16:53:55 -07003377// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3378// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003379rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003380 const RtpSenderInfo& remote_sender_info) {
3381 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3382 if (!receiver) {
3383 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3384 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003385 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003386 }
Steve Anton4171afb2017-11-20 10:20:22 -08003387 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3388 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3389 } else {
3390 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3391 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003392 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003393}
3394
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003395void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3396 MediaStreamInterface* stream) {
3397 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003398 RTC_DCHECK(track);
3399 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003400 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003401 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003402 // We already have a sender for this track, so just change the stream_id
3403 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003404 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003405 return;
3406 }
3407
3408 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003409 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003410 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003411 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003412 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003413 // If the sender has already been configured in SDP, we call SetSsrc,
3414 // which will connect the sender to the underlying transport. This can
3415 // occur if a local session description that contains the ID of the sender
3416 // is set before AddStream is called. It can also occur if the local
3417 // session description is not changed and RemoveStream is called, and
3418 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003419 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003420 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003421 if (sender_info) {
3422 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003423 }
3424}
3425
3426// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3427// indefinitely, when we have unified plan SDP.
3428void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3429 MediaStreamInterface* stream) {
3430 RTC_DCHECK(!IsClosed());
3431 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003432 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003433 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3434 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003435 return;
3436 }
Steve Anton4171afb2017-11-20 10:20:22 -08003437 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003438}
3439
3440void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3441 MediaStreamInterface* stream) {
3442 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003443 RTC_DCHECK(track);
3444 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003445 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003446 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003447 // We already have a sender for this track, so just change the stream_id
3448 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003449 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003450 return;
3451 }
3452
3453 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003454 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003455 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003456 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003457 GetVideoTransceiver()->internal()->AddSender(new_sender);
3458 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003459 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003460 if (sender_info) {
3461 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003462 }
3463}
3464
3465void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3466 MediaStreamInterface* stream) {
3467 RTC_DCHECK(!IsClosed());
3468 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003469 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003470 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3471 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003472 return;
3473 }
Steve Anton4171afb2017-11-20 10:20:22 -08003474 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003475}
3476
Steve Antonba818672017-11-06 10:21:57 -08003477void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003478 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003479 if (ice_connection_state_ == new_state) {
3480 return;
3481 }
3482
deadbeefcbecd352015-09-23 11:50:27 -07003483 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003484 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003485 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003486 return;
3487 }
Steve Antonba818672017-11-06 10:21:57 -08003488
Mirko Bonadei675513b2017-11-09 11:09:25 +01003489 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3490 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003491 RTC_DCHECK(ice_connection_state_ !=
3492 PeerConnectionInterface::kIceConnectionClosed);
3493
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003494 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003495 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003496}
3497
3498void PeerConnection::OnIceGatheringChange(
3499 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003500 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003501 if (IsClosed()) {
3502 return;
3503 }
3504 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003505 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506}
3507
jbauch81bf7b02017-03-25 08:31:12 -07003508void PeerConnection::OnIceCandidate(
3509 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003510 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003511 if (IsClosed()) {
3512 return;
3513 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003514 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003515 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3516 candidate->candidate().address().IsPrivateIP()) {
3517 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3518 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003519 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520}
3521
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003522void PeerConnection::OnIceCandidatesRemoved(
3523 const std::vector<cricket::Candidate>& candidates) {
3524 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003525 if (IsClosed()) {
3526 return;
3527 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003528 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003529}
3530
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003531void PeerConnection::ChangeSignalingState(
3532 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003533 RTC_DCHECK(signaling_thread()->IsCurrent());
3534 if (signaling_state_ == signaling_state) {
3535 return;
3536 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003537 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3538 << GetSignalingStateString(signaling_state_)
3539 << " New state: "
3540 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003541 signaling_state_ = signaling_state;
3542 if (signaling_state == kClosed) {
3543 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003544 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003545 if (ice_gathering_state_ != kIceGatheringComplete) {
3546 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003547 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003548 }
3549 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003550 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003551}
3552
deadbeefeb459812015-12-15 19:24:43 -08003553void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3554 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003555 if (IsClosed()) {
3556 return;
3557 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003558 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003559 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003560}
3561
deadbeefeb459812015-12-15 19:24:43 -08003562void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3563 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003564 if (IsClosed()) {
3565 return;
3566 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003567 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003568 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003569}
3570
3571void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3572 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003573 if (IsClosed()) {
3574 return;
3575 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003576 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003577 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003578}
3579
3580void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3581 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003582 if (IsClosed()) {
3583 return;
3584 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003585 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003586 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003587}
3588
Henrik Boström31638672017-11-23 17:48:32 +01003589void PeerConnection::PostSetSessionDescriptionSuccess(
3590 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003591 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3592 signaling_thread()->Post(RTC_FROM_HERE, this,
3593 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003594}
3595
deadbeefab9b2d12015-10-14 11:33:11 -07003596void PeerConnection::PostSetSessionDescriptionFailure(
3597 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003598 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003599 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003600 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3601 msg->error = std::move(error);
3602 signaling_thread()->Post(RTC_FROM_HERE, this,
3603 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003604}
3605
3606void PeerConnection::PostCreateSessionDescriptionFailure(
3607 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003608 RTCError error) {
3609 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003610 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3611 msg->error = std::move(error);
3612 signaling_thread()->Post(RTC_FROM_HERE, this,
3613 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003614}
3615
zhihuang1c378ed2017-08-17 14:10:50 -07003616void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003617 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003618 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003619 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003620
Steve Antondcc3c022017-12-22 16:02:54 -08003621 if (IsUnifiedPlan()) {
3622 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3623 } else {
3624 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3625 }
3626
Steve Antonfa2260d2017-12-28 16:38:23 -08003627 // Intentionally unset the data channel type for RTP data channel with the
3628 // second condition. Otherwise the RTP data channels would be successfully
3629 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3630 // when building with chromium. We want to leave RTP data channels broken, so
3631 // people won't try to use them.
3632 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3633 session_options->data_channel_type = data_channel_type();
3634 }
3635
Steve Antondcc3c022017-12-22 16:02:54 -08003636 // Apply ICE restart flag and renomination flag.
3637 for (auto& options : session_options->media_description_options) {
3638 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3639 options.transport_options.enable_ice_renomination =
3640 configuration_.enable_ice_renomination;
3641 }
3642
3643 session_options->rtcp_cname = rtcp_cname_;
3644 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003645 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003646}
3647
3648void PeerConnection::GetOptionsForPlanBOffer(
3649 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3650 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003651 // Figure out transceiver directional preferences.
3652 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3653 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3654
3655 // By default, generate sendrecv/recvonly m= sections.
3656 bool recv_audio = true;
3657 bool recv_video = true;
3658
3659 // By default, only offer a new m= section if we have media to send with it.
3660 bool offer_new_audio_description = send_audio;
3661 bool offer_new_video_description = send_video;
3662 bool offer_new_data_description = HasDataChannels();
3663
3664 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003665 if (offer_answer_options.offer_to_receive_audio !=
3666 RTCOfferAnswerOptions::kUndefined) {
3667 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003668 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003669 offer_new_audio_description ||
3670 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003671 }
Steve Antondcc3c022017-12-22 16:02:54 -08003672 if (offer_answer_options.offer_to_receive_video !=
3673 RTCOfferAnswerOptions::kUndefined) {
3674 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003675 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003676 offer_new_video_description ||
3677 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003678 }
3679
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003680 absl::optional<size_t> audio_index;
3681 absl::optional<size_t> video_index;
3682 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003683 // If a current description exists, generate m= sections in the same order,
3684 // using the first audio/video/data section that appears and rejecting
3685 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003686 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003687 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003688 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003689 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3690 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3691 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003692 }
3693
zhihuang1c378ed2017-08-17 14:10:50 -07003694 // Add audio/video/data m= sections to the end if needed.
3695 if (!audio_index && offer_new_audio_description) {
3696 session_options->media_description_options.push_back(
3697 cricket::MediaDescriptionOptions(
3698 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003699 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3700 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003701 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003702 }
zhihuang1c378ed2017-08-17 14:10:50 -07003703 if (!video_index && offer_new_video_description) {
3704 session_options->media_description_options.push_back(
3705 cricket::MediaDescriptionOptions(
3706 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003707 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3708 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003709 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003710 }
zhihuang1c378ed2017-08-17 14:10:50 -07003711 if (!data_index && offer_new_data_description) {
3712 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003713 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003714 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003715 }
3716
3717 cricket::MediaDescriptionOptions* audio_media_description_options =
3718 !audio_index ? nullptr
3719 : &session_options->media_description_options[*audio_index];
3720 cricket::MediaDescriptionOptions* video_media_description_options =
3721 !video_index ? nullptr
3722 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003723
Steve Anton4171afb2017-11-20 10:20:22 -08003724 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003725 video_media_description_options,
3726 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003727}
3728
3729// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3730// and return a reference to it.
3731// Generated MIDs should be no more than 3 bytes long to take up less space in
3732// the RTP packet.
3733static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3734 RTC_DCHECK(used_mids);
3735 // We're boring: just generate MIDs 0, 1, 2, ...
3736 size_t i = 0;
3737 std::set<std::string>::iterator it;
3738 bool inserted;
3739 do {
3740 std::string mid = rtc::ToString(i++);
3741 auto insert_result = used_mids->insert(mid);
3742 it = insert_result.first;
3743 inserted = insert_result.second;
3744 } while (!inserted);
3745 return *it;
3746}
3747
3748static cricket::MediaDescriptionOptions
3749GetMediaDescriptionOptionsForTransceiver(
3750 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3751 transceiver,
3752 const std::string& mid) {
3753 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003754 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003755 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003756 // This behavior is specified in JSEP. The gist is that:
3757 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3758 // sendrecv.
3759 // 2. If the MSID is included, then it must be included in any subsequent
3760 // offer/answer exactly the same until the RtpTransceiver is stopped.
3761 if (!transceiver->stopped() &&
3762 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3763 transceiver->internal()->has_ever_been_used_to_send())) {
3764 cricket::SenderOptions sender_options;
3765 sender_options.track_id = transceiver->sender()->id();
3766 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003767 int num_send_encoding_layers =
3768 transceiver->sender()->init_send_encodings().size();
3769 sender_options.num_sim_layers =
3770 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003771 media_description_options.sender_options.push_back(sender_options);
3772 }
Steve Antondcc3c022017-12-22 16:02:54 -08003773 return media_description_options;
3774}
3775
3776void PeerConnection::GetOptionsForUnifiedPlanOffer(
3777 const RTCOfferAnswerOptions& offer_answer_options,
3778 cricket::MediaSessionOptions* session_options) {
3779 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3780 // Offers) and 5.2.2 (Subsequent Offers).
3781 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3782 const ContentInfos& local_contents =
3783 (local_description() ? local_description()->description()->contents()
3784 : ContentInfos());
3785 const ContentInfos& remote_contents =
3786 (remote_description() ? remote_description()->description()->contents()
3787 : ContentInfos());
3788 // The mline indices that can be recycled. New transceivers should reuse these
3789 // slots first.
3790 std::queue<size_t> recycleable_mline_indices;
3791 // Track the MIDs used in previous offer/answer exchanges and the current
3792 // offer so that new, unique MIDs are generated.
3793 std::set<std::string> used_mids = seen_mids_;
3794 // First, go through each media section that exists in either the local or
3795 // remote description and generate a media section in this offer for the
3796 // associated transceiver. If a media section can be recycled, generate a
3797 // default, rejected media section here that can be later overwritten.
3798 for (size_t i = 0;
3799 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3800 // Either |local_content| or |remote_content| is non-null.
3801 const ContentInfo* local_content =
3802 (i < local_contents.size() ? &local_contents[i] : nullptr);
3803 const ContentInfo* remote_content =
3804 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3805 bool had_been_rejected = (local_content && local_content->rejected) ||
3806 (remote_content && remote_content->rejected);
3807 const std::string& mid =
3808 (local_content ? local_content->name : remote_content->name);
3809 cricket::MediaType media_type =
3810 (local_content ? local_content->media_description()->type()
3811 : remote_content->media_description()->type());
3812 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3813 media_type == cricket::MEDIA_TYPE_VIDEO) {
3814 auto transceiver = GetAssociatedTransceiver(mid);
3815 RTC_CHECK(transceiver);
3816 // A media section is considered eligible for recycling if it is marked as
3817 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003818 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003819 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003820 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3821 RtpTransceiverDirection::kInactive,
3822 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003823 recycleable_mline_indices.push(i);
3824 } else {
3825 session_options->media_description_options.push_back(
3826 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3827 // CreateOffer shouldn't really cause any state changes in
3828 // PeerConnection, but we need a way to match new transceivers to new
3829 // media sections in SetLocalDescription and JSEP specifies this is done
3830 // by recording the index of the media section generated for the
3831 // transceiver in the offer.
3832 transceiver->internal()->set_mline_index(i);
3833 }
3834 } else {
3835 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003836 RTC_CHECK(GetDataMid());
3837 if (had_been_rejected || mid != *GetDataMid()) {
3838 session_options->media_description_options.push_back(
3839 GetMediaDescriptionOptionsForRejectedData(mid));
3840 } else {
3841 session_options->media_description_options.push_back(
3842 GetMediaDescriptionOptionsForActiveData(mid));
3843 }
Steve Antondcc3c022017-12-22 16:02:54 -08003844 }
3845 }
3846 // Next, look for transceivers that are newly added (that is, are not stopped
3847 // and not associated). Reuse media sections marked as recyclable first,
3848 // otherwise append to the end of the offer. New media sections should be
3849 // added in the order they were added to the PeerConnection.
3850 for (auto transceiver : transceivers_) {
3851 if (transceiver->mid() || transceiver->stopped()) {
3852 continue;
3853 }
3854 size_t mline_index;
3855 if (!recycleable_mline_indices.empty()) {
3856 mline_index = recycleable_mline_indices.front();
3857 recycleable_mline_indices.pop();
3858 session_options->media_description_options[mline_index] =
3859 GetMediaDescriptionOptionsForTransceiver(transceiver,
3860 AllocateMid(&used_mids));
3861 } else {
3862 mline_index = session_options->media_description_options.size();
3863 session_options->media_description_options.push_back(
3864 GetMediaDescriptionOptionsForTransceiver(transceiver,
3865 AllocateMid(&used_mids)));
3866 }
3867 // See comment above for why CreateOffer changes the transceiver's state.
3868 transceiver->internal()->set_mline_index(mline_index);
3869 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003870 // Lastly, add a m-section if we have local data channels and an m section
3871 // does not already exist.
3872 if (!GetDataMid() && HasDataChannels()) {
3873 session_options->media_description_options.push_back(
3874 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3875 }
Steve Antondcc3c022017-12-22 16:02:54 -08003876}
3877
3878void PeerConnection::GetOptionsForAnswer(
3879 const RTCOfferAnswerOptions& offer_answer_options,
3880 cricket::MediaSessionOptions* session_options) {
3881 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3882
3883 if (IsUnifiedPlan()) {
3884 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3885 } else {
3886 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3887 }
3888
Steve Antonfa2260d2017-12-28 16:38:23 -08003889 // Intentionally unset the data channel type for RTP data channel. Otherwise
3890 // the RTP data channels would be successfully negotiated by default and the
3891 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3892 // We want to leave RTP data channels broken, so people won't try to use them.
3893 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3894 session_options->data_channel_type = data_channel_type();
3895 }
3896
Steve Antondcc3c022017-12-22 16:02:54 -08003897 // Apply ICE renomination flag.
3898 for (auto& options : session_options->media_description_options) {
3899 options.transport_options.enable_ice_renomination =
3900 configuration_.enable_ice_renomination;
3901 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003902
3903 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003904 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003905 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003906}
3907
Steve Antondcc3c022017-12-22 16:02:54 -08003908void PeerConnection::GetOptionsForPlanBAnswer(
3909 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003910 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003911 // Figure out transceiver directional preferences.
3912 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3913 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3914
3915 // By default, generate sendrecv/recvonly m= sections. The direction is also
3916 // restricted by the direction in the offer.
3917 bool recv_audio = true;
3918 bool recv_video = true;
3919
3920 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003921 if (offer_answer_options.offer_to_receive_audio !=
3922 RTCOfferAnswerOptions::kUndefined) {
3923 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003924 }
Steve Antondcc3c022017-12-22 16:02:54 -08003925 if (offer_answer_options.offer_to_receive_video !=
3926 RTCOfferAnswerOptions::kUndefined) {
3927 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003928 }
3929
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003930 absl::optional<size_t> audio_index;
3931 absl::optional<size_t> video_index;
3932 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003933
3934 // Generate m= sections that match those in the offer.
3935 // Note that mediasession.cc will handle intersection our preferred
3936 // direction with the offered direction.
3937 GenerateMediaDescriptionOptions(
3938 remote_description(),
3939 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3940 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3941 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003942
3943 cricket::MediaDescriptionOptions* audio_media_description_options =
3944 !audio_index ? nullptr
3945 : &session_options->media_description_options[*audio_index];
3946 cricket::MediaDescriptionOptions* video_media_description_options =
3947 !video_index ? nullptr
3948 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003949
Steve Anton4171afb2017-11-20 10:20:22 -08003950 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003951 video_media_description_options,
3952 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003953}
zhihuangaf388472016-11-02 16:49:48 -07003954
Steve Antondcc3c022017-12-22 16:02:54 -08003955void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3956 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3957 cricket::MediaSessionOptions* session_options) {
3958 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3959 // Answers) and 5.3.2 (Subsequent Answers).
3960 RTC_DCHECK(remote_description());
3961 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3962 for (const ContentInfo& content :
3963 remote_description()->description()->contents()) {
3964 cricket::MediaType media_type = content.media_description()->type();
3965 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3966 media_type == cricket::MEDIA_TYPE_VIDEO) {
3967 auto transceiver = GetAssociatedTransceiver(content.name);
3968 RTC_CHECK(transceiver);
3969 session_options->media_description_options.push_back(
3970 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3971 } else {
3972 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003973 // Reject all data sections if data channels are disabled.
3974 // Reject a data section if it has already been rejected.
3975 // Reject all data sections except for the first one.
3976 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3977 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003978 session_options->media_description_options.push_back(
3979 GetMediaDescriptionOptionsForRejectedData(content.name));
3980 } else {
3981 session_options->media_description_options.push_back(
3982 GetMediaDescriptionOptionsForActiveData(content.name));
3983 }
Steve Antondcc3c022017-12-22 16:02:54 -08003984 }
3985 }
htaa2a49d92016-03-04 02:51:39 -08003986}
3987
zhihuang1c378ed2017-08-17 14:10:50 -07003988void PeerConnection::GenerateMediaDescriptionOptions(
3989 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003990 RtpTransceiverDirection audio_direction,
3991 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003992 absl::optional<size_t>* audio_index,
3993 absl::optional<size_t>* video_index,
3994 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003995 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003996 for (const cricket::ContentInfo& content :
3997 session_desc->description()->contents()) {
3998 if (IsAudioContent(&content)) {
3999 // If we already have an audio m= section, reject this extra one.
4000 if (*audio_index) {
4001 session_options->media_description_options.push_back(
4002 cricket::MediaDescriptionOptions(
4003 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004004 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004005 } else {
4006 session_options->media_description_options.push_back(
4007 cricket::MediaDescriptionOptions(
4008 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004009 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004010 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004011 }
4012 } else if (IsVideoContent(&content)) {
4013 // If we already have an video m= section, reject this extra one.
4014 if (*video_index) {
4015 session_options->media_description_options.push_back(
4016 cricket::MediaDescriptionOptions(
4017 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004018 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004019 } else {
4020 session_options->media_description_options.push_back(
4021 cricket::MediaDescriptionOptions(
4022 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004023 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004024 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004025 }
4026 } else {
4027 RTC_DCHECK(IsDataContent(&content));
4028 // If we already have an data m= section, reject this extra one.
4029 if (*data_index) {
4030 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004031 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004032 } else {
4033 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004034 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004035 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004036 }
4037 }
htaa2a49d92016-03-04 02:51:39 -08004038 }
deadbeefab9b2d12015-10-14 11:33:11 -07004039}
4040
Steve Antonfa2260d2017-12-28 16:38:23 -08004041cricket::MediaDescriptionOptions
4042PeerConnection::GetMediaDescriptionOptionsForActiveData(
4043 const std::string& mid) const {
4044 // Direction for data sections is meaningless, but legacy endpoints might
4045 // expect sendrecv.
4046 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4047 RtpTransceiverDirection::kSendRecv,
4048 /*stopped=*/false);
4049 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4050 return options;
4051}
4052
4053cricket::MediaDescriptionOptions
4054PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4055 const std::string& mid) const {
4056 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4057 RtpTransceiverDirection::kInactive,
4058 /*stopped=*/true);
4059 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4060 return options;
4061}
4062
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004063absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004064 switch (data_channel_type_) {
4065 case cricket::DCT_RTP:
4066 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004067 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004068 }
4069 return rtp_data_channel_->content_name();
4070 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004071 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004072 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004073 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004074 }
4075}
4076
Steve Anton4171afb2017-11-20 10:20:22 -08004077void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4078 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4079 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004080 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004081}
4082
Steve Anton4171afb2017-11-20 10:20:22 -08004083void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004084 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004085 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004086 cricket::MediaType media_type,
4087 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004088 RTC_DCHECK(!IsUnifiedPlan());
4089
Steve Anton4171afb2017-11-20 10:20:22 -08004090 std::vector<RtpSenderInfo>* current_senders =
4091 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004092
Steve Anton4171afb2017-11-20 10:20:22 -08004093 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004094 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004095 for (auto sender_it = current_senders->begin();
4096 sender_it != current_senders->end();
4097 /* incremented manually */) {
4098 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004099 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004100 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004101 std::string params_stream_id;
4102 if (params) {
4103 params_stream_id =
4104 (!params->first_stream_id().empty() ? params->first_stream_id()
4105 : kDefaultStreamId);
4106 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004107 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004108 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004109 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004110 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004111 sender_exists) {
4112 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004113 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004114 OnRemoteSenderRemoved(info, media_type);
4115 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004116 }
4117 }
4118
Steve Anton4171afb2017-11-20 10:20:22 -08004119 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004120 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004121 if (!params.has_ssrcs()) {
4122 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4123 // sender, this means it is coming from a Unified Plan endpoint,so we just
4124 // create a default.
4125 default_sender_needed = true;
4126 break;
4127 }
4128
Seth Hampson845e8782018-03-02 11:34:10 -08004129 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004130 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004131 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4132 // not supported in Plan B, we just take the first here and create the
4133 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004134 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004135 (!params.first_stream_id().empty() ? params.first_stream_id()
4136 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004137 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004138 uint32_t ssrc = params.first_ssrc();
4139
4140 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004141 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004142 if (!stream) {
4143 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004144 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004145 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004146 remote_streams_->AddStream(stream);
4147 new_streams->AddStream(stream);
4148 }
4149
Steve Anton4171afb2017-11-20 10:20:22 -08004150 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004151 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004152 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004153 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004154 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004155 }
4156 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004157
Steve Anton4171afb2017-11-20 10:20:22 -08004158 // Add default sender if necessary.
4159 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004160 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004161 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004162 if (!default_stream) {
4163 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004164 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004165 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004166 remote_streams_->AddStream(default_stream);
4167 new_streams->AddStream(default_stream);
4168 }
Steve Anton4171afb2017-11-20 10:20:22 -08004169 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4170 ? kDefaultAudioSenderId
4171 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004172 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004173 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004174 if (!default_sender_info) {
4175 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004176 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004177 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004178 }
4179 }
deadbeefab9b2d12015-10-14 11:33:11 -07004180}
4181
Steve Anton4171afb2017-11-20 10:20:22 -08004182void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4183 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004184 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4185 << " receiver for track_id=" << sender_info.sender_id
4186 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004187
Steve Anton3d954a62018-04-02 11:27:23 -07004188 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004189 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004190 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004191 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004192 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004193 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004194 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004195 }
4196}
4197
Steve Anton4171afb2017-11-20 10:20:22 -08004198void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4199 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004200 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4201 << " receiver for track_id=" << sender_info.sender_id
4202 << " and stream_id=" << sender_info.stream_id;
4203
Seth Hampson845e8782018-03-02 11:34:10 -08004204 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004205
Henrik Boström933d8b02017-10-10 10:05:16 -07004206 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004207 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004208 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4209 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004210 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004211 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004212 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004213 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004214 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004215 }
4216 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004217 // Stopping or destroying a VideoRtpReceiver will end the
4218 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004219 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004220 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004221 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004222 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004223 // There's no guarantee the track is still available, e.g. the track may
4224 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004225 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004226 }
4227 } else {
nisseede5da42017-01-12 05:15:36 -08004228 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004229 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004230 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004231 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004232 }
deadbeefab9b2d12015-10-14 11:33:11 -07004233}
4234
4235void PeerConnection::UpdateEndedRemoteMediaStreams() {
4236 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4237 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4238 MediaStreamInterface* stream = remote_streams_->at(i);
4239 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4240 streams_to_remove.push_back(stream);
4241 }
4242 }
4243
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004244 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004245 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004246 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004247 }
4248}
4249
Steve Anton4171afb2017-11-20 10:20:22 -08004250void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004251 const std::vector<cricket::StreamParams>& streams,
4252 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004253 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004254
Seth Hampson845e8782018-03-02 11:34:10 -08004255 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004256 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004257 for (auto sender_it = current_senders->begin();
4258 sender_it != current_senders->end();
4259 /* incremented manually */) {
4260 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004261 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004262 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4263 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004264 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004265 OnLocalSenderRemoved(info, media_type);
4266 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004267 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004268 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004269 }
4270 }
4271
Steve Anton4171afb2017-11-20 10:20:22 -08004272 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004273 for (const cricket::StreamParams& params : streams) {
4274 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004275 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004276 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004277 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004278 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004279 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004280 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004281 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004282 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004283 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004284 }
4285 }
4286}
4287
Steve Anton4171afb2017-11-20 10:20:22 -08004288void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4289 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004290 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004291 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004292 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004293 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4294 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004295 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004296 return;
4297 }
4298
deadbeeffac06552015-11-25 11:26:01 -08004299 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004300 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004301 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004302 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004303 }
deadbeeffac06552015-11-25 11:26:01 -08004304
Seth Hampson5b4f0752018-04-02 16:31:36 -07004305 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004306 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004307}
4308
Steve Anton4171afb2017-11-20 10:20:22 -08004309void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4310 cricket::MediaType media_type) {
4311 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004312 if (!sender) {
4313 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004314 // SessionDescriptions has been renegotiated.
4315 return;
4316 }
deadbeeffac06552015-11-25 11:26:01 -08004317
4318 // A sender has been removed from the SessionDescription but it's still
4319 // associated with the PeerConnection. This only occurs if the SDP doesn't
4320 // match with the calls to CreateSender, AddStream and RemoveStream.
4321 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004322 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004323 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004324 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004325 }
deadbeeffac06552015-11-25 11:26:01 -08004326
Steve Anton4171afb2017-11-20 10:20:22 -08004327 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004328}
4329
4330void PeerConnection::UpdateLocalRtpDataChannels(
4331 const cricket::StreamParamsVec& streams) {
4332 std::vector<std::string> existing_channels;
4333
4334 // Find new and active data channels.
4335 for (const cricket::StreamParams& params : streams) {
4336 // |it->sync_label| is actually the data channel label. The reason is that
4337 // we use the same naming of data channels as we do for
4338 // MediaStreams and Tracks.
4339 // For MediaStreams, the sync_label is the MediaStream label and the
4340 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004341 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004342 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004343 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004344 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004345 continue;
4346 }
4347 // Set the SSRC the data channel should use for sending.
4348 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4349 existing_channels.push_back(data_channel_it->first);
4350 }
4351
4352 UpdateClosingRtpDataChannels(existing_channels, true);
4353}
4354
4355void PeerConnection::UpdateRemoteRtpDataChannels(
4356 const cricket::StreamParamsVec& streams) {
4357 std::vector<std::string> existing_channels;
4358
4359 // Find new and active data channels.
4360 for (const cricket::StreamParams& params : streams) {
4361 // The data channel label is either the mslabel or the SSRC if the mslabel
4362 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004363 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004364 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004365 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004366 auto data_channel_it = rtp_data_channels_.find(label);
4367 if (data_channel_it == rtp_data_channels_.end()) {
4368 // This is a new data channel.
4369 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4370 } else {
4371 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4372 }
4373 existing_channels.push_back(label);
4374 }
4375
4376 UpdateClosingRtpDataChannels(existing_channels, false);
4377}
4378
4379void PeerConnection::UpdateClosingRtpDataChannels(
4380 const std::vector<std::string>& active_channels,
4381 bool is_local_update) {
4382 auto it = rtp_data_channels_.begin();
4383 while (it != rtp_data_channels_.end()) {
4384 DataChannel* data_channel = it->second;
4385 if (std::find(active_channels.begin(), active_channels.end(),
4386 data_channel->label()) != active_channels.end()) {
4387 ++it;
4388 continue;
4389 }
4390
4391 if (is_local_update) {
4392 data_channel->SetSendSsrc(0);
4393 } else {
4394 data_channel->RemotePeerRequestClose();
4395 }
4396
4397 if (data_channel->state() == DataChannel::kClosed) {
4398 rtp_data_channels_.erase(it);
4399 it = rtp_data_channels_.begin();
4400 } else {
4401 ++it;
4402 }
4403 }
4404}
4405
4406void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4407 uint32_t remote_ssrc) {
4408 rtc::scoped_refptr<DataChannel> channel(
4409 InternalCreateDataChannel(label, nullptr));
4410 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004411 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004412 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004413 return;
4414 }
4415 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004416 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4417 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004418 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004419}
4420
4421rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4422 const std::string& label,
4423 const InternalDataChannelInit* config) {
4424 if (IsClosed()) {
4425 return nullptr;
4426 }
Steve Anton75737c02017-11-06 10:37:17 -08004427 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004428 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004429 << "InternalCreateDataChannel: Data is not supported in this call.";
4430 return nullptr;
4431 }
4432 InternalDataChannelInit new_config =
4433 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004434 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004435 if (new_config.id < 0) {
4436 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004437 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004438 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004439 RTC_LOG(LS_ERROR)
4440 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004441 return nullptr;
4442 }
4443 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004444 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004445 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004446 return nullptr;
4447 }
4448 }
4449
Steve Anton75737c02017-11-06 10:37:17 -08004450 rtc::scoped_refptr<DataChannel> channel(
4451 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004452 if (!channel) {
4453 sid_allocator_.ReleaseSid(new_config.id);
4454 return nullptr;
4455 }
4456
4457 if (channel->data_channel_type() == cricket::DCT_RTP) {
4458 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004459 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4460 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004461 return nullptr;
4462 }
4463 rtp_data_channels_[channel->label()] = channel;
4464 } else {
4465 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4466 sctp_data_channels_.push_back(channel);
4467 channel->SignalClosed.connect(this,
4468 &PeerConnection::OnSctpDataChannelClosed);
4469 }
4470
Steve Anton2d8609c2018-01-23 16:38:46 -08004471 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004472 return channel;
4473}
4474
4475bool PeerConnection::HasDataChannels() const {
4476 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4477}
4478
4479void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4480 for (const auto& channel : sctp_data_channels_) {
4481 if (channel->id() < 0) {
4482 int sid;
4483 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004484 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004485 continue;
4486 }
4487 channel->SetSctpSid(sid);
4488 }
4489 }
4490}
4491
4492void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004493 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004494 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4495 ++it) {
4496 if (it->get() == channel) {
4497 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004498 // After the closing procedure is done, it's safe to use this ID for
4499 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004500 sid_allocator_.ReleaseSid(channel->id());
4501 }
deadbeefbd292462015-12-14 18:15:29 -08004502 // Since this method is triggered by a signal from the DataChannel,
4503 // we can't free it directly here; we need to free it asynchronously.
4504 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004505 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004506 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4507 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004508 return;
4509 }
4510 }
4511}
4512
deadbeefab9b2d12015-10-14 11:33:11 -07004513void PeerConnection::OnDataChannelDestroyed() {
4514 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4515 // DataChannel may callback to us and try to modify the list.
4516 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4517 temp_rtp_dcs.swap(rtp_data_channels_);
4518 for (const auto& kv : temp_rtp_dcs) {
4519 kv.second->OnTransportChannelDestroyed();
4520 }
4521
4522 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4523 temp_sctp_dcs.swap(sctp_data_channels_);
4524 for (const auto& channel : temp_sctp_dcs) {
4525 channel->OnTransportChannelDestroyed();
4526 }
4527}
4528
4529void PeerConnection::OnDataChannelOpenMessage(
4530 const std::string& label,
4531 const InternalDataChannelInit& config) {
4532 rtc::scoped_refptr<DataChannel> channel(
4533 InternalCreateDataChannel(label, &config));
4534 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004535 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004536 return;
4537 }
4538
deadbeefa601f5c2016-06-06 14:27:39 -07004539 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4540 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004541 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004542 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004543}
4544
Steve Anton4171afb2017-11-20 10:20:22 -08004545rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4546PeerConnection::GetAudioTransceiver() const {
4547 // This method only works with Plan B SDP, where there is a single
4548 // audio/video transceiver.
4549 RTC_DCHECK(!IsUnifiedPlan());
4550 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004551 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004552 return transceiver;
4553 }
4554 }
4555 RTC_NOTREACHED();
4556 return nullptr;
4557}
4558
4559rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4560PeerConnection::GetVideoTransceiver() const {
4561 // This method only works with Plan B SDP, where there is a single
4562 // audio/video transceiver.
4563 RTC_DCHECK(!IsUnifiedPlan());
4564 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004565 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004566 return transceiver;
4567 }
4568 }
4569 RTC_NOTREACHED();
4570 return nullptr;
4571}
4572
4573// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4574// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004575bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004576 switch (type) {
4577 case cricket::MEDIA_TYPE_AUDIO:
4578 return !GetAudioTransceiver()->internal()->senders().empty();
4579 case cricket::MEDIA_TYPE_VIDEO:
4580 return !GetVideoTransceiver()->internal()->senders().empty();
4581 case cricket::MEDIA_TYPE_DATA:
4582 return false;
4583 }
4584 RTC_NOTREACHED();
4585 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004586}
4587
Steve Anton4171afb2017-11-20 10:20:22 -08004588rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4589PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4590 for (auto transceiver : transceivers_) {
4591 for (auto sender : transceiver->internal()->senders()) {
4592 if (sender->track() == track) {
4593 return sender;
4594 }
4595 }
4596 }
4597 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004598}
4599
Steve Anton4171afb2017-11-20 10:20:22 -08004600rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4601PeerConnection::FindSenderById(const std::string& sender_id) const {
4602 for (auto transceiver : transceivers_) {
4603 for (auto sender : transceiver->internal()->senders()) {
4604 if (sender->id() == sender_id) {
4605 return sender;
4606 }
4607 }
4608 }
4609 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004610}
4611
Steve Anton4171afb2017-11-20 10:20:22 -08004612rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4613PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4614 for (auto transceiver : transceivers_) {
4615 for (auto receiver : transceiver->internal()->receivers()) {
4616 if (receiver->id() == receiver_id) {
4617 return receiver;
4618 }
4619 }
4620 }
4621 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004622}
4623
Steve Anton4171afb2017-11-20 10:20:22 -08004624std::vector<PeerConnection::RtpSenderInfo>*
4625PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4626 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4627 media_type == cricket::MEDIA_TYPE_VIDEO);
4628 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4629 ? &remote_audio_sender_infos_
4630 : &remote_video_sender_infos_;
4631}
4632
4633std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004634 cricket::MediaType media_type) {
4635 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4636 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004637 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4638 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004639}
4640
Steve Anton4171afb2017-11-20 10:20:22 -08004641const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4642 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004643 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004644 const std::string sender_id) const {
4645 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004646 if (sender_info.stream_id == stream_id &&
4647 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004648 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004649 }
4650 }
4651 return nullptr;
4652}
4653
4654DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4655 for (const auto& channel : sctp_data_channels_) {
4656 if (channel->id() == sid) {
4657 return channel;
4658 }
4659 }
4660 return nullptr;
4661}
4662
deadbeef91dd5672016-05-18 16:55:30 -07004663bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004664 const cricket::ServerAddresses& stun_servers,
4665 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004666 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004667 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004668 // To handle both internal and externally created port allocator, we will
4669 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004670 port_allocator_flags_ = port_allocator_->flags();
4671 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4672 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4673 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004674 // If the disable-IPv6 flag was specified, we'll not override it
4675 // by experiment.
4676 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004677 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004678 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4679 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004680 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004681 }
4682
zhihuangb09b3f92017-03-07 14:40:51 -08004683 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004684 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004685 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004686 }
4687
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004688 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004689 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004690 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004691 }
4692
honghaiz60347052016-05-31 18:29:12 -07004693 if (configuration.candidate_network_policy ==
4694 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004695 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004696 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004697 }
4698
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004699 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004700 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004701 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4702 }
4703
Qingsi Wanga2d60672018-04-11 16:57:45 -07004704 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004705 // No step delay is used while allocating ports.
4706 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4707 port_allocator_->set_candidate_filter(
4708 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004709 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004710
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004711 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004712 for (auto& turn_server : turn_servers_copy) {
4713 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004714 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004715 // Call this last since it may create pooled allocator sessions using the
4716 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004717 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004718 stun_servers, std::move(turn_servers_copy),
4719 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4720 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004721 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004722 return true;
4723}
4724
deadbeef91dd5672016-05-18 16:55:30 -07004725bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004726 const cricket::ServerAddresses& stun_servers,
4727 const std::vector<cricket::RelayServerConfig>& turn_servers,
4728 IceTransportsType type,
4729 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004730 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004731 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004732 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004733 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004734 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004735 // According to JSEP, after setLocalDescription, changing the candidate pool
4736 // size is not allowed, and changing the set of ICE servers will not result
4737 // in new candidates being gathered.
4738 if (local_description()) {
4739 port_allocator_->FreezeCandidatePool();
4740 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004741 // Add the custom tls turn servers if they exist.
4742 auto turn_servers_copy = turn_servers;
4743 for (auto& turn_server : turn_servers_copy) {
4744 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4745 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004746 // Call this last since it may create pooled allocator sessions using the
4747 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004748 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004749 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4750 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004751}
4752
Steve Antonba818672017-11-06 10:21:57 -08004753cricket::ChannelManager* PeerConnection::channel_manager() const {
4754 return factory_->channel_manager();
4755}
4756
Elad Alon99c3fe52017-10-13 16:29:40 +02004757bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004758 std::unique_ptr<RtcEventLogOutput> output,
4759 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004760 if (!event_log_) {
4761 return false;
4762 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004763 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004764}
4765
4766void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004767 if (event_log_) {
4768 event_log_->StopLogging();
4769 }
ivoc14d5dbe2016-07-04 07:06:55 -07004770}
nisseeaabdf62017-05-05 02:23:02 -07004771
Steve Anton75737c02017-11-06 10:37:17 -08004772cricket::BaseChannel* PeerConnection::GetChannel(
4773 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004774 for (auto transceiver : transceivers_) {
4775 cricket::BaseChannel* channel = transceiver->internal()->channel();
4776 if (channel && channel->content_name() == content_name) {
4777 return channel;
4778 }
Steve Anton75737c02017-11-06 10:37:17 -08004779 }
4780 if (rtp_data_channel() &&
4781 rtp_data_channel()->content_name() == content_name) {
4782 return rtp_data_channel();
4783 }
4784 return nullptr;
4785}
4786
4787bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4788 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004789 RTC_LOG(LS_INFO)
4790 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004791 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004792 return false;
4793 }
4794 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004795 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004796 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004797 return false;
4798 }
4799
Zhi Huange830e682018-03-30 10:48:35 -07004800 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4801 if (dtls_role) {
4802 *role = *dtls_role;
4803 return true;
4804 }
4805 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004806}
4807
4808bool PeerConnection::GetSslRole(const std::string& content_name,
4809 rtc::SSLRole* role) {
4810 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004811 RTC_LOG(LS_INFO)
4812 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004813 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004814 return false;
4815 }
4816
Zhi Huange830e682018-03-30 10:48:35 -07004817 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4818 if (dtls_role) {
4819 *role = *dtls_role;
4820 return true;
4821 }
4822 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004823}
4824
Steve Antonf8470812017-12-04 10:46:21 -08004825void PeerConnection::SetSessionError(SessionError error,
4826 const std::string& error_desc) {
4827 RTC_DCHECK_RUN_ON(signaling_thread());
4828 if (error != session_error_) {
4829 session_error_ = error;
4830 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004831 }
4832}
4833
Zhi Huange830e682018-03-30 10:48:35 -07004834RTCError PeerConnection::UpdateSessionState(
4835 SdpType type,
4836 cricket::ContentSource source,
4837 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004838 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004839
4840 // If there's already a pending error then no state transition should happen.
4841 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004842 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004843
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004844 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004845 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004846 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004847 }
4848
4849 // Update the signaling state according to the specified state machine (see
4850 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004851 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004852 ChangeSignalingState(source == cricket::CS_LOCAL
4853 ? PeerConnectionInterface::kHaveLocalOffer
4854 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004855 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004856 ChangeSignalingState(source == cricket::CS_LOCAL
4857 ? PeerConnectionInterface::kHaveLocalPrAnswer
4858 : PeerConnectionInterface::kHaveRemotePrAnswer);
4859 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004860 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004861 ChangeSignalingState(PeerConnectionInterface::kStable);
4862 }
4863
4864 // Update internal objects according to the session description's media
4865 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004866 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004867 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004868 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004869 }
4870
Steve Anton8a006912017-12-04 15:25:56 -08004871 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004872}
4873
Steve Anton8a006912017-12-04 15:25:56 -08004874RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004875 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004876 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004877 const SessionDescriptionInterface* sdesc =
4878 (source == cricket::CS_LOCAL ? local_description()
4879 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004880 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004881
4882 // Push down the new SDP media section for each audio/video transceiver.
4883 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004884 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004885 FindMediaSectionForTransceiver(transceiver, sdesc);
4886 cricket::BaseChannel* channel = transceiver->internal()->channel();
4887 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004888 continue;
4889 }
4890 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004891 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004892 if (!content_desc) {
4893 continue;
4894 }
4895 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004896 bool success = (source == cricket::CS_LOCAL)
4897 ? channel->SetLocalContent(content_desc, type, &error)
4898 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004899 if (!success) {
4900 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4901 }
4902 }
4903
4904 // If using the RtpDataChannel, push down the new SDP section for it too.
4905 if (rtp_data_channel_) {
4906 const ContentInfo* data_content =
4907 cricket::GetFirstDataContent(sdesc->description());
4908 if (data_content && !data_content->rejected) {
4909 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004910 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004911 if (data_desc) {
4912 std::string error;
4913 bool success =
4914 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004915 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004916 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004917 if (!success) {
4918 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4919 std::move(error));
4920 }
Steve Anton75737c02017-11-06 10:37:17 -08004921 }
4922 }
4923 }
Steve Antoned10bd92017-12-05 10:52:59 -08004924
Steve Anton75737c02017-11-06 10:37:17 -08004925 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4926 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4927 if (sctp_transport_ && local_description() && remote_description() &&
4928 cricket::GetFirstDataContent(local_description()->description()) &&
4929 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004930 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004931 RTC_FROM_HERE,
4932 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004933 if (!success) {
4934 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4935 "Failed to push down SCTP parameters.");
4936 }
Steve Anton75737c02017-11-06 10:37:17 -08004937 }
Steve Antoned10bd92017-12-05 10:52:59 -08004938
Steve Anton8a006912017-12-04 15:25:56 -08004939 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004940}
4941
4942bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4943 RTC_DCHECK(network_thread()->IsCurrent());
4944 RTC_DCHECK(local_description());
4945 RTC_DCHECK(remote_description());
4946 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4947 // When we support "max-message-size", that would also be pushed down here.
4948 return sctp_transport_->Start(
4949 GetSctpPort(local_description()->description()),
4950 GetSctpPort(remote_description()->description()));
4951}
4952
Steve Anton8a006912017-12-04 15:25:56 -08004953RTCError PeerConnection::PushdownTransportDescription(
4954 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004955 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004956 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004957
Zhi Huange830e682018-03-30 10:48:35 -07004958 if (source == cricket::CS_LOCAL) {
4959 const SessionDescriptionInterface* sdesc = local_description();
4960 RTC_DCHECK(sdesc);
4961 return transport_controller_->SetLocalDescription(type,
4962 sdesc->description());
4963 } else {
4964 const SessionDescriptionInterface* sdesc = remote_description();
4965 RTC_DCHECK(sdesc);
4966 return transport_controller_->SetRemoteDescription(type,
4967 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004968 }
Steve Anton75737c02017-11-06 10:37:17 -08004969}
4970
4971bool PeerConnection::GetTransportDescription(
4972 const SessionDescription* description,
4973 const std::string& content_name,
4974 cricket::TransportDescription* tdesc) {
4975 if (!description || !tdesc) {
4976 return false;
4977 }
4978 const TransportInfo* transport_info =
4979 description->GetTransportInfoByName(content_name);
4980 if (!transport_info) {
4981 return false;
4982 }
4983 *tdesc = transport_info->description;
4984 return true;
4985}
4986
Steve Anton75737c02017-11-06 10:37:17 -08004987cricket::IceConfig PeerConnection::ParseIceConfig(
4988 const PeerConnectionInterface::RTCConfiguration& config) const {
4989 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004990 switch (config.continual_gathering_policy) {
4991 case PeerConnectionInterface::GATHER_ONCE:
4992 gathering_policy = cricket::GATHER_ONCE;
4993 break;
4994 case PeerConnectionInterface::GATHER_CONTINUALLY:
4995 gathering_policy = cricket::GATHER_CONTINUALLY;
4996 break;
4997 default:
4998 RTC_NOTREACHED();
4999 gathering_policy = cricket::GATHER_ONCE;
5000 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005001
Steve Anton75737c02017-11-06 10:37:17 -08005002 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005003 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5004 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005005 ice_config.prioritize_most_likely_candidate_pairs =
5006 config.prioritize_most_likely_ice_candidate_pairs;
5007 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005008 RTCConfigurationToIceConfigOptionalInt(
5009 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005010 ice_config.continual_gathering_policy = gathering_policy;
5011 ice_config.presume_writable_when_fully_relayed =
5012 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005013 ice_config.ice_check_interval_strong_connectivity =
5014 config.ice_check_interval_strong_connectivity;
5015 ice_config.ice_check_interval_weak_connectivity =
5016 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005017 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005018 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005019 ice_config.regather_all_networks_interval_range =
5020 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005021 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005022 return ice_config;
5023}
5024
Steve Anton75737c02017-11-06 10:37:17 -08005025bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5026 std::string* track_id) {
5027 if (!local_description()) {
5028 return false;
5029 }
5030 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5031 track_id);
5032}
5033
5034bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5035 std::string* track_id) {
5036 if (!remote_description()) {
5037 return false;
5038 }
5039 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5040 track_id);
5041}
5042
5043bool PeerConnection::SendData(const cricket::SendDataParams& params,
5044 const rtc::CopyOnWriteBuffer& payload,
5045 cricket::SendDataResult* result) {
5046 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005047 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005048 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005049 return false;
5050 }
5051 return rtp_data_channel_
5052 ? rtp_data_channel_->SendData(params, payload, result)
5053 : network_thread()->Invoke<bool>(
5054 RTC_FROM_HERE,
5055 Bind(&cricket::SctpTransportInternal::SendData,
5056 sctp_transport_.get(), params, payload, result));
5057}
5058
5059bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5060 if (!rtp_data_channel_ && !sctp_transport_) {
5061 // Don't log an error here, because DataChannels are expected to call
5062 // ConnectDataChannel in this state. It's the only way to initially tell
5063 // whether or not the underlying transport is ready.
5064 return false;
5065 }
5066 if (rtp_data_channel_) {
5067 rtp_data_channel_->SignalReadyToSendData.connect(
5068 webrtc_data_channel, &DataChannel::OnChannelReady);
5069 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5070 &DataChannel::OnDataReceived);
5071 } else {
5072 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5073 &DataChannel::OnChannelReady);
5074 SignalSctpDataReceived.connect(webrtc_data_channel,
5075 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005076 SignalSctpClosingProcedureStartedRemotely.connect(
5077 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5078 SignalSctpClosingProcedureComplete.connect(
5079 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005080 }
5081 return true;
5082}
5083
5084void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5085 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005086 RTC_LOG(LS_ERROR)
5087 << "DisconnectDataChannel called when rtp_data_channel_ and "
5088 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005089 return;
5090 }
5091 if (rtp_data_channel_) {
5092 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5093 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5094 } else {
5095 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5096 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005097 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5098 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005099 }
5100}
5101
5102void PeerConnection::AddSctpDataStream(int sid) {
5103 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005104 RTC_LOG(LS_ERROR)
5105 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005106 return;
5107 }
5108 network_thread()->Invoke<void>(
5109 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5110 sctp_transport_.get(), sid));
5111}
5112
5113void PeerConnection::RemoveSctpDataStream(int sid) {
5114 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005115 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005116 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005117 return;
5118 }
5119 network_thread()->Invoke<void>(
5120 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5121 sctp_transport_.get(), sid));
5122}
5123
5124bool PeerConnection::ReadyToSendData() const {
5125 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5126 sctp_ready_to_send_data_;
5127}
5128
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005129absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005130 if (sctp_mid_ && transport_controller_) {
5131 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5132 if (dtls_transport) {
5133 return dtls_transport->transport_name();
5134 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005135 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005136 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005137 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005138}
5139
Qingsi Wang72a43a12018-02-20 16:03:18 -08005140cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5141 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005142 network_thread()->Invoke<void>(
5143 RTC_FROM_HERE,
5144 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5145 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005146 return candidate_states_list;
5147}
5148
Steve Anton5dfde182018-02-06 10:34:40 -08005149std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5150 const {
5151 std::map<std::string, std::string> transport_names_by_mid;
5152 for (auto transceiver : transceivers_) {
5153 cricket::BaseChannel* channel = transceiver->internal()->channel();
5154 if (channel) {
5155 transport_names_by_mid[channel->content_name()] =
5156 channel->transport_name();
5157 }
Steve Anton75737c02017-11-06 10:37:17 -08005158 }
Steve Anton5dfde182018-02-06 10:34:40 -08005159 if (rtp_data_channel_) {
5160 transport_names_by_mid[rtp_data_channel_->content_name()] =
5161 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005162 }
5163 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005164 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005165 RTC_DCHECK(transport_name);
5166 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005167 }
Steve Anton5dfde182018-02-06 10:34:40 -08005168 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005169}
5170
Steve Anton5dfde182018-02-06 10:34:40 -08005171std::map<std::string, cricket::TransportStats>
5172PeerConnection::GetTransportStatsByNames(
5173 const std::set<std::string>& transport_names) {
5174 if (!network_thread()->IsCurrent()) {
5175 return network_thread()
5176 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5177 RTC_FROM_HERE,
5178 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005179 }
Steve Anton5dfde182018-02-06 10:34:40 -08005180 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5181 for (const std::string& transport_name : transport_names) {
5182 cricket::TransportStats transport_stats;
5183 bool success =
5184 transport_controller_->GetStats(transport_name, &transport_stats);
5185 if (success) {
5186 transport_stats_by_name[transport_name] = std::move(transport_stats);
5187 } else {
5188 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5189 << transport_name;
5190 }
5191 }
5192 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005193}
5194
5195bool PeerConnection::GetLocalCertificate(
5196 const std::string& transport_name,
5197 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005198 if (!certificate) {
5199 return false;
5200 }
5201 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5202 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005203}
5204
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005205std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005206 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005207 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005208}
5209
5210cricket::DataChannelType PeerConnection::data_channel_type() const {
5211 return data_channel_type_;
5212}
5213
5214bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5215 return pending_ice_restarts_.find(content_name) !=
5216 pending_ice_restarts_.end();
5217}
5218
Steve Anton75737c02017-11-06 10:37:17 -08005219bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5220 return transport_controller_->NeedsIceRestart(content_name);
5221}
5222
5223void PeerConnection::OnCertificateReady(
5224 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5225 transport_controller_->SetLocalCertificate(certificate);
5226}
5227
5228void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005229 SetSessionError(SessionError::kTransport,
5230 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005231}
5232
5233void PeerConnection::OnTransportControllerConnectionState(
5234 cricket::IceConnectionState state) {
5235 switch (state) {
5236 case cricket::kIceConnectionConnecting:
5237 // If the current state is Connected or Completed, then there were
5238 // writable channels but now there are not, so the next state must
5239 // be Disconnected.
5240 // kIceConnectionConnecting is currently used as the default,
5241 // un-connected state by the TransportController, so its only use is
5242 // detecting disconnections.
5243 if (ice_connection_state_ ==
5244 PeerConnectionInterface::kIceConnectionConnected ||
5245 ice_connection_state_ ==
5246 PeerConnectionInterface::kIceConnectionCompleted) {
5247 SetIceConnectionState(
5248 PeerConnectionInterface::kIceConnectionDisconnected);
5249 }
5250 break;
5251 case cricket::kIceConnectionFailed:
5252 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5253 break;
5254 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005255 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005256 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005257 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005258 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005259 break;
5260 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005261 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005262 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005263 if (ice_connection_state_ !=
5264 PeerConnectionInterface::kIceConnectionConnected) {
5265 // If jumping directly from "checking" to "connected",
5266 // signal "connected" first.
5267 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5268 }
5269 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005270 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005271 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005272 break;
5273 default:
5274 RTC_NOTREACHED();
5275 }
5276}
5277
5278void PeerConnection::OnTransportControllerCandidatesGathered(
5279 const std::string& transport_name,
5280 const cricket::Candidates& candidates) {
5281 RTC_DCHECK(signaling_thread()->IsCurrent());
5282 int sdp_mline_index;
5283 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005284 RTC_LOG(LS_ERROR)
5285 << "OnTransportControllerCandidatesGathered: content name "
5286 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005287 return;
5288 }
5289
5290 for (cricket::Candidates::const_iterator citer = candidates.begin();
5291 citer != candidates.end(); ++citer) {
5292 // Use transport_name as the candidate media id.
5293 std::unique_ptr<JsepIceCandidate> candidate(
5294 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5295 if (local_description()) {
5296 mutable_local_description()->AddCandidate(candidate.get());
5297 }
5298 OnIceCandidate(std::move(candidate));
5299 }
5300}
5301
5302void PeerConnection::OnTransportControllerCandidatesRemoved(
5303 const std::vector<cricket::Candidate>& candidates) {
5304 RTC_DCHECK(signaling_thread()->IsCurrent());
5305 // Sanity check.
5306 for (const cricket::Candidate& candidate : candidates) {
5307 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005308 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005309 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005310 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005311 return;
5312 }
5313 }
5314
5315 if (local_description()) {
5316 mutable_local_description()->RemoveCandidates(candidates);
5317 }
5318 OnIceCandidatesRemoved(candidates);
5319}
5320
5321void PeerConnection::OnTransportControllerDtlsHandshakeError(
5322 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005323 RTC_HISTOGRAM_ENUMERATION(
5324 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5325 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005326}
5327
Steve Antoned10bd92017-12-05 10:52:59 -08005328void PeerConnection::EnableSending() {
5329 for (auto transceiver : transceivers_) {
5330 cricket::BaseChannel* channel = transceiver->internal()->channel();
5331 if (channel && !channel->enabled()) {
5332 channel->Enable(true);
5333 }
Steve Anton75737c02017-11-06 10:37:17 -08005334 }
5335
Steve Anton4171afb2017-11-20 10:20:22 -08005336 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005337 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005338 }
Steve Anton75737c02017-11-06 10:37:17 -08005339}
5340
5341// Returns the media index for a local ice candidate given the content name.
5342bool PeerConnection::GetLocalCandidateMediaIndex(
5343 const std::string& content_name,
5344 int* sdp_mline_index) {
5345 if (!local_description() || !sdp_mline_index) {
5346 return false;
5347 }
5348
5349 bool content_found = false;
5350 const ContentInfos& contents = local_description()->description()->contents();
5351 for (size_t index = 0; index < contents.size(); ++index) {
5352 if (contents[index].name == content_name) {
5353 *sdp_mline_index = static_cast<int>(index);
5354 content_found = true;
5355 break;
5356 }
5357 }
5358 return content_found;
5359}
5360
5361bool PeerConnection::UseCandidatesInSessionDescription(
5362 const SessionDescriptionInterface* remote_desc) {
5363 if (!remote_desc) {
5364 return true;
5365 }
5366 bool ret = true;
5367
5368 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5369 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5370 for (size_t n = 0; n < candidates->count(); ++n) {
5371 const IceCandidateInterface* candidate = candidates->at(n);
5372 bool valid = false;
5373 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5374 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005375 RTC_LOG(LS_INFO)
5376 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005377 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005378 }
5379 continue;
5380 }
5381 ret = UseCandidate(candidate);
5382 if (!ret) {
5383 break;
5384 }
5385 }
5386 }
5387 return ret;
5388}
5389
5390bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5391 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5392 size_t remote_content_size =
5393 remote_description()->description()->contents().size();
5394 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005395 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005396 return false;
5397 }
5398
5399 cricket::ContentInfo content =
5400 remote_description()->description()->contents()[mediacontent_index];
5401 std::vector<cricket::Candidate> candidates;
5402 candidates.push_back(candidate->candidate());
5403 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005404 RTCError error =
5405 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005406 if (error.ok()) {
5407 // Candidates successfully submitted for checking.
5408 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5409 ice_connection_state_ ==
5410 PeerConnectionInterface::kIceConnectionDisconnected) {
5411 // If state is New, then the session has just gotten its first remote ICE
5412 // candidates, so go to Checking.
5413 // If state is Disconnected, the session is re-using old candidates or
5414 // receiving additional ones, so go to Checking.
5415 // If state is Connected, stay Connected.
5416 // TODO(bemasc): If state is Connected, and the new candidates are for a
5417 // newly added transport, then the state actually _should_ move to
5418 // checking. Add a way to distinguish that case.
5419 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5420 }
5421 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005422 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005423 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005424 }
5425 return true;
5426}
5427
5428void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005429 // Destroy video channel first since it may have a pointer to the
5430 // voice channel.
5431 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005432 if (!video_info || video_info->rejected) {
5433 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005434 }
5435
Steve Anton6fec8802017-12-04 10:37:29 -08005436 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5437 if (!audio_info || audio_info->rejected) {
5438 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005439 }
5440
5441 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5442 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005443 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005444 }
5445}
5446
Steve Antondcc3c022017-12-22 16:02:54 -08005447RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5448 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005449 const cricket::ContentGroup* bundle_group = nullptr;
5450 if (configuration_.bundle_policy ==
5451 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005452 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005453 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005454 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5455 "max-bundle configured but session description "
5456 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005457 }
5458 }
Steve Antondcc3c022017-12-22 16:02:54 -08005459 return std::move(bundle_group);
5460}
5461
5462RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005463 // Creating the media channels. Transports should already have been created
5464 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005465 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005466 if (voice && !voice->rejected &&
5467 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005468 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005469 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005470 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5471 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005472 }
5473 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5474 }
5475
Steve Antondcc3c022017-12-22 16:02:54 -08005476 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005477 if (video && !video->rejected &&
5478 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005479 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005480 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005481 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5482 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005483 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005484 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005485 }
5486
Steve Antondcc3c022017-12-22 16:02:54 -08005487 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005488 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5489 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005490 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005491 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5492 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005493 }
5494 }
5495
Steve Anton8a006912017-12-04 15:25:56 -08005496 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005497}
5498
Steve Anton4171afb2017-11-20 10:20:22 -08005499// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005500cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005501 const std::string& mid) {
5502 RtpTransportInternal* rtp_transport =
5503 transport_controller_->GetRtpTransport(mid);
5504 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005505 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005506 call_.get(), configuration_.media_config, rtp_transport,
5507 signaling_thread(), mid, SrtpRequired(),
5508 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005509 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005510 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005511 }
Steve Anton75737c02017-11-06 10:37:17 -08005512 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5513 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005514 voice_channel->SignalSentPacket.connect(this,
5515 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005516 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005517
Steve Antoneda6ccd2017-12-04 10:21:55 -08005518 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005519}
5520
Steve Anton4171afb2017-11-20 10:20:22 -08005521// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005522cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005523 const std::string& mid) {
5524 RtpTransportInternal* rtp_transport =
5525 transport_controller_->GetRtpTransport(mid);
5526 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005527 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005528 call_.get(), configuration_.media_config, rtp_transport,
5529 signaling_thread(), mid, SrtpRequired(),
5530 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005531 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005532 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005533 }
Steve Anton75737c02017-11-06 10:37:17 -08005534 video_channel->SignalDtlsSrtpSetupFailure.connect(
5535 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005536 video_channel->SignalSentPacket.connect(this,
5537 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005538 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005539
Steve Antoneda6ccd2017-12-04 10:21:55 -08005540 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005541}
5542
Zhi Huange830e682018-03-30 10:48:35 -07005543bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005544 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5545 if (sctp) {
5546 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005547 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005548 << "Trying to create SCTP transport, but didn't compile with "
5549 "SCTP support (HAVE_SCTP)";
5550 return false;
5551 }
5552 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005553 RTC_FROM_HERE,
5554 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005555 return false;
5556 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005557 for (const auto& channel : sctp_data_channels_) {
5558 channel->OnTransportChannelCreated();
5559 }
Steve Anton75737c02017-11-06 10:37:17 -08005560 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005561 RtpTransportInternal* rtp_transport =
5562 transport_controller_->GetRtpTransport(mid);
5563 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005564 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005565 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5566 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005567 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005568 return false;
5569 }
Steve Anton75737c02017-11-06 10:37:17 -08005570 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5571 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5572 rtp_data_channel_->SignalSentPacket.connect(
5573 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005574 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005575 }
5576
Steve Anton75737c02017-11-06 10:37:17 -08005577 return true;
5578}
5579
5580Call::Stats PeerConnection::GetCallStats() {
5581 if (!worker_thread()->IsCurrent()) {
5582 return worker_thread()->Invoke<Call::Stats>(
5583 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5584 }
5585 if (call_) {
5586 return call_->GetStats();
5587 } else {
5588 return Call::Stats();
5589 }
5590}
5591
Zhi Huange830e682018-03-30 10:48:35 -07005592bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005593 RTC_DCHECK(network_thread()->IsCurrent());
5594 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005595 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005596 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005597 RTC_DCHECK(dtls_transport);
5598 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005599 RTC_DCHECK(sctp_transport_);
5600 sctp_invoker_.reset(new rtc::AsyncInvoker());
5601 sctp_transport_->SignalReadyToSendData.connect(
5602 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5603 sctp_transport_->SignalDataReceived.connect(
5604 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005605 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5606 // another thread. Would be nice if there was a helper class similar to
5607 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5608 // code.
5609 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5610 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5611 sctp_transport_->SignalClosingProcedureComplete.connect(
5612 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005613 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005614 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005615 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005616}
5617
5618void PeerConnection::DestroySctpTransport_n() {
5619 RTC_DCHECK(network_thread()->IsCurrent());
5620 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005621 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005622 sctp_invoker_.reset(nullptr);
5623 sctp_ready_to_send_data_ = false;
5624}
5625
5626void PeerConnection::OnSctpTransportReadyToSendData_n() {
5627 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5628 RTC_DCHECK(network_thread()->IsCurrent());
5629 // Note: Cannot use rtc::Bind here because it will grab a reference to
5630 // PeerConnection and potentially cause PeerConnection to live longer than
5631 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5632 // be destroyed before PeerConnection is destroyed, and at that point all
5633 // pending tasks will be cleared.
5634 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5635 OnSctpTransportReadyToSendData_s(true);
5636 });
5637}
5638
5639void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5640 RTC_DCHECK(signaling_thread()->IsCurrent());
5641 sctp_ready_to_send_data_ = ready;
5642 SignalSctpReadyToSendData(ready);
5643}
5644
5645void PeerConnection::OnSctpTransportDataReceived_n(
5646 const cricket::ReceiveDataParams& params,
5647 const rtc::CopyOnWriteBuffer& payload) {
5648 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5649 RTC_DCHECK(network_thread()->IsCurrent());
5650 // Note: Cannot use rtc::Bind here because it will grab a reference to
5651 // PeerConnection and potentially cause PeerConnection to live longer than
5652 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5653 // be destroyed before PeerConnection is destroyed, and at that point all
5654 // pending tasks will be cleared.
5655 sctp_invoker_->AsyncInvoke<void>(
5656 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5657 OnSctpTransportDataReceived_s(params, payload);
5658 });
5659}
5660
5661void PeerConnection::OnSctpTransportDataReceived_s(
5662 const cricket::ReceiveDataParams& params,
5663 const rtc::CopyOnWriteBuffer& payload) {
5664 RTC_DCHECK(signaling_thread()->IsCurrent());
5665 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5666 // Received OPEN message; parse and signal that a new data channel should
5667 // be created.
5668 std::string label;
5669 InternalDataChannelInit config;
5670 config.id = params.ssrc;
5671 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005672 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5673 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005674 return;
5675 }
5676 config.open_handshake_role = InternalDataChannelInit::kAcker;
5677 OnDataChannelOpenMessage(label, config);
5678 } else {
5679 // Otherwise just forward the signal.
5680 SignalSctpDataReceived(params, payload);
5681 }
5682}
5683
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005684void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005685 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5686 RTC_DCHECK(network_thread()->IsCurrent());
5687 sctp_invoker_->AsyncInvoke<void>(
5688 RTC_FROM_HERE, signaling_thread(),
5689 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005690 &SignalSctpClosingProcedureStartedRemotely, sid));
5691}
5692
5693void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5694 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5695 RTC_DCHECK(network_thread()->IsCurrent());
5696 sctp_invoker_->AsyncInvoke<void>(
5697 RTC_FROM_HERE, signaling_thread(),
5698 rtc::Bind(&sigslot::signal1<int>::operator(),
5699 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005700}
5701
5702// Returns false if bundle is enabled and rtcp_mux is disabled.
5703bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5704 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5705 if (!bundle_enabled)
5706 return true;
5707
5708 const cricket::ContentGroup* bundle_group =
5709 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5710 RTC_DCHECK(bundle_group != NULL);
5711
5712 const cricket::ContentInfos& contents = desc->contents();
5713 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5714 citer != contents.end(); ++citer) {
5715 const cricket::ContentInfo* content = (&*citer);
5716 RTC_DCHECK(content != NULL);
5717 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005718 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005719 if (!HasRtcpMuxEnabled(content))
5720 return false;
5721 }
5722 }
5723 // RTCP-MUX is enabled in all the contents.
5724 return true;
5725}
5726
5727bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005728 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005729}
5730
Steve Anton8a006912017-12-04 15:25:56 -08005731RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005732 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005733 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005734 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005735 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005736 }
5737
5738 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005739 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005740 }
5741
Steve Anton3828c062017-12-06 10:34:51 -08005742 SdpType type = sdesc->GetType();
5743 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5744 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005745 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005746 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005747 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005748 }
5749
5750 // Verify crypto settings.
5751 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005752 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5753 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005754 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005755 if (!crypto_error.ok()) {
5756 return crypto_error;
5757 }
Steve Anton75737c02017-11-06 10:37:17 -08005758 }
5759
5760 // Verify ice-ufrag and ice-pwd.
5761 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005762 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5763 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005764 }
5765
5766 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005767 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5768 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005769 }
5770
5771 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5772 // m-lines that do not rtcp-mux enabled.
5773
5774 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005775 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005776 // With an answer we want to compare the new answer session description with
5777 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005778 const cricket::SessionDescription* offer_desc =
5779 (source == cricket::CS_LOCAL) ? remote_description()->description()
5780 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005781 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5782 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5783 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005784 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5785 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005786 }
5787 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005788 // The re-offers should respect the order of m= sections in current
5789 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005790 // With a re-offer, either the current local or current remote descriptions
5791 // could be the most up to date, so we would like to check against both of
5792 // them if they exist. It could be the case that one of them has a 0 port
5793 // for a media section, but the other does not. This is important to check
5794 // against in the case that we are recycling an m= section.
5795 const cricket::SessionDescription* current_desc = nullptr;
5796 const cricket::SessionDescription* secondary_current_desc = nullptr;
5797 if (local_description()) {
5798 current_desc = local_description()->description();
5799 if (remote_description()) {
5800 secondary_current_desc = remote_description()->description();
5801 }
5802 } else if (remote_description()) {
5803 current_desc = remote_description()->description();
5804 }
Steve Anton75737c02017-11-06 10:37:17 -08005805 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005806 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5807 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005808 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5809 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005810 }
5811 }
5812
Steve Antonba42e992018-04-09 14:10:01 -07005813 if (IsUnifiedPlan()) {
5814 // Ensure that each audio and video media section has at most one
5815 // "StreamParams". This will return an error if receiving a session
5816 // description from a "Plan B" endpoint which adds multiple tracks of the
5817 // same type. With Unified Plan, there can only be at most one track per
5818 // media section.
5819 for (const ContentInfo& content : sdesc->description()->contents()) {
5820 const MediaContentDescription& desc = *content.description;
5821 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5822 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5823 desc.streams().size() > 1u) {
5824 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5825 "Media section has more than one track specified "
5826 "with a=ssrc lines which is not supported with "
5827 "Unified Plan.");
5828 }
5829 }
5830 }
5831
Steve Anton8a006912017-12-04 15:25:56 -08005832 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005833}
5834
Steve Anton3828c062017-12-06 10:34:51 -08005835bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005836 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005837 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005838 return (state == PeerConnectionInterface::kStable) ||
5839 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005840 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005841 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005842 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5843 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5844 }
5845}
5846
Steve Anton3828c062017-12-06 10:34:51 -08005847bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005848 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005849 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005850 return (state == PeerConnectionInterface::kStable) ||
5851 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005852 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005853 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005854 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5855 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5856 }
5857}
5858
Steve Antonf8470812017-12-04 10:46:21 -08005859const char* PeerConnection::SessionErrorToString(SessionError error) const {
5860 switch (error) {
5861 case SessionError::kNone:
5862 return "ERROR_NONE";
5863 case SessionError::kContent:
5864 return "ERROR_CONTENT";
5865 case SessionError::kTransport:
5866 return "ERROR_TRANSPORT";
5867 }
5868 RTC_NOTREACHED();
5869 return "";
5870}
5871
Steve Anton75737c02017-11-06 10:37:17 -08005872std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02005873 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08005874 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5875 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02005876 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08005877}
5878
Steve Anton8e20f172018-03-06 10:55:04 -08005879void PeerConnection::ReportSdpFormatReceived(
5880 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005881 int num_audio_mlines = 0;
5882 int num_video_mlines = 0;
5883 int num_audio_tracks = 0;
5884 int num_video_tracks = 0;
5885 for (const ContentInfo& content : remote_offer.description()->contents()) {
5886 cricket::MediaType media_type = content.media_description()->type();
5887 int num_tracks = std::max(
5888 1, static_cast<int>(content.media_description()->streams().size()));
5889 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5890 num_audio_mlines += 1;
5891 num_audio_tracks += num_tracks;
5892 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5893 num_video_mlines += 1;
5894 num_video_tracks += num_tracks;
5895 }
5896 }
5897 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5898 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5899 format = kSdpFormatReceivedComplexUnifiedPlan;
5900 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5901 format = kSdpFormatReceivedComplexPlanB;
5902 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5903 format = kSdpFormatReceivedSimple;
5904 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005905 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5906 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005907}
5908
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005909void PeerConnection::NoteUsageEvent(UsageEvent event) {
5910 RTC_DCHECK_RUN_ON(signaling_thread());
5911 usage_event_accumulator_ |= static_cast<int>(event);
5912}
5913
5914void PeerConnection::ReportUsagePattern() const {
5915 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005916 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5917 usage_event_accumulator_,
5918 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005919 const int bad_bits =
5920 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5921 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5922 const int good_bits =
5923 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5924 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5925 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5926 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5927 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005928 // If called after close(), we can't report, because observer may have
5929 // been deallocated, and therefore pointer is null. Write to log instead.
5930 if (observer_) {
5931 Observer()->OnInterestingUsage(usage_event_accumulator_);
5932 } else {
5933 RTC_LOG(LS_INFO) << "Interesting usage signature "
5934 << usage_event_accumulator_
5935 << " observed after observer shutdown";
5936 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005937 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005938}
5939
Steve Anton0ffaaa22018-02-23 10:31:30 -08005940void PeerConnection::ReportNegotiatedSdpSemantics(
5941 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005942 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005943 switch (answer.description()->msid_signaling()) {
5944 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005945 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005946 break;
5947 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005948 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005949 break;
5950 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005951 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005952 break;
5953 case cricket::kMsidSignalingMediaSection |
5954 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005955 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005956 break;
5957 default:
5958 RTC_NOTREACHED();
5959 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005960 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5961 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005962}
5963
Steve Anton75737c02017-11-06 10:37:17 -08005964// We need to check the local/remote description for the Transport instead of
5965// the session, because a new Transport added during renegotiation may have
5966// them unset while the session has them set from the previous negotiation.
5967// Not doing so may trigger the auto generation of transport description and
5968// mess up DTLS identity information, ICE credential, etc.
5969bool PeerConnection::ReadyToUseRemoteCandidate(
5970 const IceCandidateInterface* candidate,
5971 const SessionDescriptionInterface* remote_desc,
5972 bool* valid) {
5973 *valid = true;
5974
5975 const SessionDescriptionInterface* current_remote_desc =
5976 remote_desc ? remote_desc : remote_description();
5977
5978 if (!current_remote_desc) {
5979 return false;
5980 }
5981
5982 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5983 size_t remote_content_size =
5984 current_remote_desc->description()->contents().size();
5985 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005986 RTC_LOG(LS_ERROR)
5987 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5988 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005989
5990 *valid = false;
5991 return false;
5992 }
5993
5994 cricket::ContentInfo content =
5995 current_remote_desc->description()->contents()[mediacontent_index];
5996
5997 const std::string transport_name = GetTransportName(content.name);
5998 if (transport_name.empty()) {
5999 return false;
6000 }
Zhi Huange830e682018-03-30 10:48:35 -07006001 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006002}
6003
6004bool PeerConnection::SrtpRequired() const {
6005 return dtls_enabled_ ||
6006 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6007}
6008
6009void PeerConnection::OnTransportControllerGatheringState(
6010 cricket::IceGatheringState state) {
6011 RTC_DCHECK(signaling_thread()->IsCurrent());
6012 if (state == cricket::kIceGatheringGathering) {
6013 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6014 } else if (state == cricket::kIceGatheringComplete) {
6015 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6016 }
6017}
6018
6019void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006020 std::map<std::string, std::set<cricket::MediaType>>
6021 media_types_by_transport_name;
6022 for (auto transceiver : transceivers_) {
6023 if (transceiver->internal()->channel()) {
6024 const std::string& transport_name =
6025 transceiver->internal()->channel()->transport_name();
6026 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006027 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006028 }
Steve Anton75737c02017-11-06 10:37:17 -08006029 }
6030 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006031 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6032 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006033 }
Zhi Huange830e682018-03-30 10:48:35 -07006034
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006035 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006036 if (transport_name) {
6037 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006038 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006039 }
Zhi Huange830e682018-03-30 10:48:35 -07006040
Steve Antonc7b964c2018-02-01 14:39:45 -08006041 for (const auto& entry : media_types_by_transport_name) {
6042 const std::string& transport_name = entry.first;
6043 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006044 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006045 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006046 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006047 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006048 }
6049 }
6050}
6051// Walk through the ConnectionInfos to gather best connection usage
6052// for IPv4 and IPv6.
6053void PeerConnection::ReportBestConnectionState(
6054 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006055 for (const cricket::TransportChannelStats& channel_stats :
6056 stats.channel_stats) {
6057 for (const cricket::ConnectionInfo& connection_info :
6058 channel_stats.connection_infos) {
6059 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006060 continue;
6061 }
6062
Steve Antonc7b964c2018-02-01 14:39:45 -08006063 const cricket::Candidate& local = connection_info.local_candidate;
6064 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006065
6066 // Increment the counter for IceCandidatePairType.
6067 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6068 (local.type() == RELAY_PORT_TYPE &&
6069 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006070 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6071 GetIceCandidatePairCounter(local, remote),
6072 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006073 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006074 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6075 GetIceCandidatePairCounter(local, remote),
6076 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006077 } else {
6078 RTC_CHECK(0);
6079 }
Steve Anton75737c02017-11-06 10:37:17 -08006080
6081 // Increment the counter for IP type.
6082 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006083 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6084 kBestConnections_IPv4,
6085 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006086 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006087 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6088 kBestConnections_IPv6,
6089 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006090 } else {
6091 RTC_CHECK(0);
6092 }
6093
6094 return;
6095 }
6096 }
6097}
6098
6099void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006100 const cricket::TransportStats& stats,
6101 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006102 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6103 return;
6104 }
6105
6106 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6107 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6108 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6109 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6110 return;
6111 }
6112
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006113 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6114 for (cricket::MediaType media_type : media_types) {
6115 switch (media_type) {
6116 case cricket::MEDIA_TYPE_AUDIO:
6117 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6118 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6119 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6120 break;
6121 case cricket::MEDIA_TYPE_VIDEO:
6122 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6123 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6124 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6125 break;
6126 case cricket::MEDIA_TYPE_DATA:
6127 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6128 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6129 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6130 break;
6131 default:
6132 RTC_NOTREACHED();
6133 continue;
6134 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006135 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006136 }
6137
6138 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6139 for (cricket::MediaType media_type : media_types) {
6140 switch (media_type) {
6141 case cricket::MEDIA_TYPE_AUDIO:
6142 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6143 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6144 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6145 break;
6146 case cricket::MEDIA_TYPE_VIDEO:
6147 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6148 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6149 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6150 break;
6151 case cricket::MEDIA_TYPE_DATA:
6152 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6153 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6154 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6155 break;
6156 default:
6157 RTC_NOTREACHED();
6158 continue;
6159 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006160 }
Steve Anton75737c02017-11-06 10:37:17 -08006161 }
6162}
6163
6164void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6165 RTC_DCHECK(worker_thread()->IsCurrent());
6166 RTC_DCHECK(call_);
6167 call_->OnSentPacket(sent_packet);
6168}
6169
6170const std::string PeerConnection::GetTransportName(
6171 const std::string& content_name) {
6172 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006173 if (channel) {
6174 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006175 }
Steve Anton6fec8802017-12-04 10:37:29 -08006176 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006177 RTC_DCHECK(sctp_mid_);
6178 if (content_name == *sctp_mid_) {
6179 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006180 }
6181 }
6182 // Return an empty string if failed to retrieve the transport name.
6183 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006184}
6185
Steve Anton6fec8802017-12-04 10:37:29 -08006186void PeerConnection::DestroyTransceiverChannel(
6187 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6188 transceiver) {
6189 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006190
Steve Anton6fec8802017-12-04 10:37:29 -08006191 cricket::BaseChannel* channel = transceiver->internal()->channel();
6192 if (channel) {
6193 transceiver->internal()->SetChannel(nullptr);
6194 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006195 }
6196}
6197
6198void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006199 if (rtp_data_channel_) {
6200 OnDataChannelDestroyed();
6201 DestroyBaseChannel(rtp_data_channel_);
6202 rtp_data_channel_ = nullptr;
6203 }
6204
6205 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6206 // grab a reference to this PeerConnection. If this is called from the
6207 // PeerConnection destructor, the RefCountedObject vtable will have already
6208 // been destroyed (since it is a subclass of PeerConnection) and using
6209 // rtc::Bind will cause "Pure virtual function called" error to appear.
6210
6211 if (sctp_transport_) {
6212 OnDataChannelDestroyed();
6213 network_thread()->Invoke<void>(RTC_FROM_HERE,
6214 [this] { DestroySctpTransport_n(); });
6215 }
6216}
6217
6218void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6219 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006220 switch (channel->media_type()) {
6221 case cricket::MEDIA_TYPE_AUDIO:
6222 channel_manager()->DestroyVoiceChannel(
6223 static_cast<cricket::VoiceChannel*>(channel));
6224 break;
6225 case cricket::MEDIA_TYPE_VIDEO:
6226 channel_manager()->DestroyVideoChannel(
6227 static_cast<cricket::VideoChannel*>(channel));
6228 break;
6229 case cricket::MEDIA_TYPE_DATA:
6230 channel_manager()->DestroyRtpDataChannel(
6231 static_cast<cricket::RtpDataChannel*>(channel));
6232 break;
6233 default:
6234 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6235 break;
6236 }
Zhi Huange830e682018-03-30 10:48:35 -07006237}
Steve Anton6fec8802017-12-04 10:37:29 -08006238
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006239bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006240 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006241 RtpTransportInternal* rtp_transport,
6242 cricket::DtlsTransportInternal* dtls_transport) {
6243 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006244 auto base_channel = GetChannel(mid);
6245 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006246 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006247 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006248 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006249 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006250 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006251 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006252}
6253
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006254PeerConnectionObserver* PeerConnection::Observer() const {
6255 // In earlier production code, the pointer was not cleared on close,
6256 // which might have led to undefined behavior if the observer was not
6257 // deallocated, or strange crashes if it was.
6258 // We use CHECK in order to catch such behavior if it exists.
6259 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6260 RTC_CHECK(observer_);
6261 return observer_;
6262}
6263
Harald Alvestrand89061872018-01-02 14:08:34 +01006264void PeerConnection::ClearStatsCache() {
6265 if (stats_collector_) {
6266 stats_collector_->ClearCachedStatsReport();
6267 }
6268}
6269
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006270void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006271 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6272 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006273}
6274
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006275} // namespace webrtc