blob: 029d77939c3bd21dd80ab9fa2546f2c7ed077072 [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();
610 return oss.str();
611}
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 =
1184 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 }
1240 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.
1382
Steve Anton3d954a62018-04-02 11:27:23 -07001383 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1384 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001385 // Set the sender ID equal to the track ID if the track is specified unless
1386 // that sender ID is already in use.
1387 std::string sender_id =
1388 (track && !FindSenderById(track->id()) ? track->id()
1389 : rtc::CreateRandomUuid());
1390 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001391 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1392 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1393 transceiver->internal()->set_direction(init.direction);
1394
Steve Anton22da89f2018-01-25 13:58:07 -08001395 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001396 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001397 }
Steve Antonf9381f02017-12-14 10:23:57 -08001398
1399 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1400}
1401
Steve Anton02ee47c2018-01-10 16:26:06 -08001402rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1403PeerConnection::CreateSender(
1404 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001405 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001406 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001407 const std::vector<std::string>& stream_ids) {
Steve Anton9158ef62017-11-27 13:01:52 -08001408 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001409 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1410 RTC_DCHECK(!track ||
1411 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1412 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1413 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001414 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001415 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001416 } else {
1417 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1418 RTC_DCHECK(!track ||
1419 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1420 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001421 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001422 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001423 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001424 bool set_track_succeeded = sender->SetTrack(track);
1425 RTC_DCHECK(set_track_succeeded);
1426 sender->internal()->set_stream_ids(stream_ids);
Steve Anton02ee47c2018-01-10 16:26:06 -08001427 return sender;
1428}
1429
1430rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1431PeerConnection::CreateReceiver(cricket::MediaType media_type,
1432 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001433 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1434 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001435 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001436 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001437 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1438 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001439 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001440 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001441 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001442 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001443 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1444 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001445 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001446 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001447 return receiver;
1448}
1449
1450rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1451PeerConnection::CreateAndAddTransceiver(
1452 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1453 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1454 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001455 // Ensure that the new sender does not have an ID that is already in use by
1456 // another sender.
1457 // Allow receiver IDs to conflict since those come from remote SDP (which
1458 // could be invalid, but should not cause a crash).
1459 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001460 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1461 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001462 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001463 transceiver->internal()->SignalNegotiationNeeded.connect(
1464 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001465 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001466}
1467
Steve Anton52d86772018-02-20 15:48:12 -08001468void PeerConnection::OnNegotiationNeeded() {
1469 RTC_DCHECK_RUN_ON(signaling_thread());
1470 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001471 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001472}
1473
deadbeeffac06552015-11-25 11:26:01 -08001474rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001475 const std::string& kind,
1476 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001477 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1478 "Plan SdpSemantics. Please use AddTransceiver "
1479 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001480 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001481 if (IsClosed()) {
1482 return nullptr;
1483 }
Steve Anton4171afb2017-11-20 10:20:22 -08001484
Seth Hampson5b4f0752018-04-02 16:31:36 -07001485 // Internally we need to have one stream with Plan B semantics, so we
1486 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001487 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001488 if (stream_id.empty()) {
1489 stream_ids.push_back(rtc::CreateRandomUuid());
1490 RTC_LOG(LS_INFO)
1491 << "No stream_id specified for sender. Generated stream ID: "
1492 << stream_ids[0];
1493 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001494 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001495 }
1496
Steve Anton4171afb2017-11-20 10:20:22 -08001497 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001498 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001499 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001500 auto* audio_sender = new AudioRtpSender(
1501 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001502 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001503 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001504 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001505 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001506 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001507 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001508 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001509 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001510 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001511 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001512 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001513 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001514 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001515 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001516 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001517 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001518
deadbeefe1f9d832016-01-14 15:35:42 -08001519 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001520}
1521
deadbeef70ab1a12015-09-28 16:53:55 -07001522std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1523 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001524 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001525 for (auto sender : GetSendersInternal()) {
1526 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001527 }
1528 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001529}
1530
Steve Anton4171afb2017-11-20 10:20:22 -08001531std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1532PeerConnection::GetSendersInternal() const {
1533 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1534 all_senders;
1535 for (auto transceiver : transceivers_) {
1536 auto senders = transceiver->internal()->senders();
1537 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1538 }
1539 return all_senders;
1540}
1541
deadbeef70ab1a12015-09-28 16:53:55 -07001542std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1543PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001544 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001545 for (const auto& receiver : GetReceiversInternal()) {
1546 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001547 }
1548 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001549}
1550
Steve Anton4171afb2017-11-20 10:20:22 -08001551std::vector<
1552 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1553PeerConnection::GetReceiversInternal() const {
1554 std::vector<
1555 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1556 all_receivers;
1557 for (auto transceiver : transceivers_) {
1558 auto receivers = transceiver->internal()->receivers();
1559 all_receivers.insert(all_receivers.end(), receivers.begin(),
1560 receivers.end());
1561 }
1562 return all_receivers;
1563}
1564
Steve Anton9158ef62017-11-27 13:01:52 -08001565std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1566PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001567 RTC_CHECK(IsUnifiedPlan())
1568 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001569 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1570 for (auto transceiver : transceivers_) {
1571 all_transceivers.push_back(transceiver);
1572 }
1573 return all_transceivers;
1574}
1575
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001577 MediaStreamTrackInterface* track,
1578 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001579 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001580 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001581 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001582 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001583 return false;
1584 }
1585
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001586 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001587 // The StatsCollector is used to tell if a track is valid because it may
1588 // remember tracks that the PeerConnection previously removed.
1589 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001590 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1591 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001592 return false;
1593 }
Steve Antonad182762018-09-05 20:22:40 +00001594 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1595 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001596 return true;
1597}
1598
hbos74e1a4f2016-09-15 23:33:01 -07001599void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001600 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001601 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001602 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001603 stats_collector_->GetStatsReport(callback);
1604}
1605
Henrik Boström1df1bf82018-03-20 13:24:20 +01001606void PeerConnection::GetStats(
1607 rtc::scoped_refptr<RtpSenderInterface> selector,
1608 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1609 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1610 RTC_DCHECK(callback);
1611 RTC_DCHECK(stats_collector_);
1612 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1613 if (selector) {
1614 for (const auto& proxy_transceiver : transceivers_) {
1615 for (const auto& proxy_sender :
1616 proxy_transceiver->internal()->senders()) {
1617 if (proxy_sender == selector) {
1618 internal_sender = proxy_sender->internal();
1619 break;
1620 }
1621 }
1622 if (internal_sender)
1623 break;
1624 }
1625 }
1626 // If there is no |internal_sender| then |selector| is either null or does not
1627 // belong to the PeerConnection (in Plan B, senders can be removed from the
1628 // PeerConnection). This means that "all the stats objects representing the
1629 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1630 // produces an empty stats report.
1631 stats_collector_->GetStatsReport(internal_sender, callback);
1632}
1633
1634void PeerConnection::GetStats(
1635 rtc::scoped_refptr<RtpReceiverInterface> selector,
1636 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1637 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1638 RTC_DCHECK(callback);
1639 RTC_DCHECK(stats_collector_);
1640 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1641 if (selector) {
1642 for (const auto& proxy_transceiver : transceivers_) {
1643 for (const auto& proxy_receiver :
1644 proxy_transceiver->internal()->receivers()) {
1645 if (proxy_receiver == selector) {
1646 internal_receiver = proxy_receiver->internal();
1647 break;
1648 }
1649 }
1650 if (internal_receiver)
1651 break;
1652 }
1653 }
1654 // If there is no |internal_receiver| then |selector| is either null or does
1655 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1656 // the PeerConnection). This means that "all the stats objects representing
1657 // the selector" is an empty set. Invoking GetStatsReport() with a null
1658 // selector produces an empty stats report.
1659 stats_collector_->GetStatsReport(internal_receiver, callback);
1660}
1661
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001662PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1663 return signaling_state_;
1664}
1665
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001666PeerConnectionInterface::IceConnectionState
1667PeerConnection::ice_connection_state() {
1668 return ice_connection_state_;
1669}
1670
1671PeerConnectionInterface::IceGatheringState
1672PeerConnection::ice_gathering_state() {
1673 return ice_gathering_state_;
1674}
1675
Yves Gerey665174f2018-06-19 15:03:05 +02001676rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001677 const std::string& label,
1678 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001679 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001680
deadbeefab9b2d12015-10-14 11:33:11 -07001681 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001682
kwibergd1fe2812016-04-27 06:47:29 -07001683 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001684 if (config) {
1685 internal_config.reset(new InternalDataChannelInit(*config));
1686 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001687 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001688 InternalCreateDataChannel(label, internal_config.get()));
1689 if (!channel.get()) {
1690 return nullptr;
1691 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001692
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001693 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1694 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001695 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001696 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001697 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001698 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001699 return DataChannelProxy::Create(signaling_thread(), channel.get());
1700}
1701
1702void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001703 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001704 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001705
nisse7ce109a2017-01-31 00:57:56 -08001706 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001707 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001708 return;
1709 }
deadbeefab9b2d12015-10-14 11:33:11 -07001710
Steve Anton8d3444d2017-10-20 15:30:51 -07001711 if (IsClosed()) {
1712 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001713 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001714 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001715 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001716 return;
1717 }
1718
zhihuang1c378ed2017-08-17 14:10:50 -07001719 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001720 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001721 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001722 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001723 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001724 return;
1725 }
1726
Steve Anton22da89f2018-01-25 13:58:07 -08001727 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1728 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1729 if (IsUnifiedPlan()) {
1730 RTCError error = HandleLegacyOfferOptions(options);
1731 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001732 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001733 return;
1734 }
1735 }
1736
zhihuang1c378ed2017-08-17 14:10:50 -07001737 cricket::MediaSessionOptions session_options;
1738 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001739 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001740}
1741
Steve Anton22da89f2018-01-25 13:58:07 -08001742RTCError PeerConnection::HandleLegacyOfferOptions(
1743 const RTCOfferAnswerOptions& options) {
1744 RTC_DCHECK(IsUnifiedPlan());
1745
1746 if (options.offer_to_receive_audio == 0) {
1747 RemoveRecvDirectionFromReceivingTransceiversOfType(
1748 cricket::MEDIA_TYPE_AUDIO);
1749 } else if (options.offer_to_receive_audio == 1) {
1750 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1751 } else if (options.offer_to_receive_audio > 1) {
1752 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1753 "offer_to_receive_audio > 1 is not supported.");
1754 }
1755
1756 if (options.offer_to_receive_video == 0) {
1757 RemoveRecvDirectionFromReceivingTransceiversOfType(
1758 cricket::MEDIA_TYPE_VIDEO);
1759 } else if (options.offer_to_receive_video == 1) {
1760 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1761 } else if (options.offer_to_receive_video > 1) {
1762 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1763 "offer_to_receive_video > 1 is not supported.");
1764 }
1765
1766 return RTCError::OK();
1767}
1768
1769void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1770 cricket::MediaType media_type) {
1771 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001772 RtpTransceiverDirection new_direction =
1773 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1774 if (new_direction != transceiver->direction()) {
1775 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1776 << " transceiver (MID="
1777 << transceiver->mid().value_or("<not set>") << ") from "
1778 << RtpTransceiverDirectionToString(
1779 transceiver->direction())
1780 << " to "
1781 << RtpTransceiverDirectionToString(new_direction)
1782 << " since CreateOffer specified offer_to_receive=0";
1783 transceiver->internal()->set_direction(new_direction);
1784 }
Steve Anton22da89f2018-01-25 13:58:07 -08001785 }
1786}
1787
1788void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1789 cricket::MediaType media_type) {
1790 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001791 RTC_LOG(LS_INFO)
1792 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1793 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001794 RtpTransceiverInit init;
1795 init.direction = RtpTransceiverDirection::kRecvOnly;
1796 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1797 }
1798}
1799
1800std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1801PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1802 std::vector<
1803 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1804 receiving_transceivers;
1805 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001806 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001807 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1808 receiving_transceivers.push_back(transceiver);
1809 }
1810 }
1811 return receiving_transceivers;
1812}
1813
htaa2a49d92016-03-04 02:51:39 -08001814void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1815 const RTCOfferAnswerOptions& options) {
1816 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001817 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001818 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001819 return;
1820 }
1821
Steve Antondffead82018-02-06 10:31:29 -08001822 if (!(signaling_state_ == kHaveRemoteOffer ||
1823 signaling_state_ == kHaveLocalPrAnswer)) {
1824 std::string error =
1825 "PeerConnection cannot create an answer in a state other than "
1826 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001827 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001828 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001829 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001830 return;
1831 }
1832
Steve Antondffead82018-02-06 10:31:29 -08001833 // The remote description should be set if we're in the right state.
1834 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001835
Steve Anton22da89f2018-01-25 13:58:07 -08001836 if (IsUnifiedPlan()) {
1837 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1838 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1839 "supported with Unified Plan semantics. Use the "
1840 "RtpTransceiver API instead.";
1841 }
1842 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1843 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1844 "supported with Unified Plan semantics. Use the "
1845 "RtpTransceiver API instead.";
1846 }
1847 }
1848
htaa2a49d92016-03-04 02:51:39 -08001849 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001850 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001851
Steve Antond25da372017-11-06 14:50:29 -08001852 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001853}
1854
1855void PeerConnection::SetLocalDescription(
1856 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001857 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001858 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001859
Steve Anton80dd7b52018-02-16 17:08:42 -08001860 // The SetLocalDescription contract is that we take ownership of the session
1861 // description regardless of the outcome, so wrap it in a unique_ptr right
1862 // away. Ideally, SetLocalDescription's signature will be changed to take the
1863 // description as a unique_ptr argument to formalize this agreement.
1864 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1865
nisse7ce109a2017-01-31 00:57:56 -08001866 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001867 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001868 return;
1869 }
Steve Anton8a006912017-12-04 15:25:56 -08001870
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001871 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001872 PostSetSessionDescriptionFailure(
1873 observer,
1874 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001875 return;
1876 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001877
Steve Anton80dd7b52018-02-16 17:08:42 -08001878 // If a session error has occurred the PeerConnection is in a possibly
1879 // inconsistent state so fail right away.
1880 if (session_error() != SessionError::kNone) {
1881 std::string error_message = GetSessionErrorMsg();
1882 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001883 PostSetSessionDescriptionFailure(
1884 observer,
1885 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001886 return;
1887 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001888
Steve Anton80dd7b52018-02-16 17:08:42 -08001889 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1890 if (!error.ok()) {
1891 std::string error_message = GetSetDescriptionErrorMessage(
1892 cricket::CS_LOCAL, desc->GetType(), error);
1893 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001894 PostSetSessionDescriptionFailure(
1895 observer,
1896 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001897 return;
1898 }
1899
1900 // Grab the description type before moving ownership to ApplyLocalDescription,
1901 // which may destroy it before returning.
1902 const SdpType type = desc->GetType();
1903
1904 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08001905 // |desc| may be destroyed at this point.
1906
1907 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08001908 // If ApplyLocalDescription fails, the PeerConnection could be in an
1909 // inconsistent state, so act conservatively here and set the session error
1910 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
1911 SetSessionError(SessionError::kContent, error.message());
1912 std::string error_message =
1913 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
1914 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001915 PostSetSessionDescriptionFailure(
1916 observer,
1917 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001918 return;
1919 }
Steve Anton8a006912017-12-04 15:25:56 -08001920 RTC_DCHECK(local_description());
1921
1922 PostSetSessionDescriptionSuccess(observer);
1923
Steve Antonad182762018-09-05 20:22:40 +00001924 // MaybeStartGathering needs to be called after posting
1925 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1926 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08001927 transport_controller_->MaybeStartGathering();
1928
Steve Antona3a92c22017-12-07 10:27:41 -08001929 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001930 // TODO(deadbeef): We already had to hop to the network thread for
1931 // MaybeStartGathering...
1932 network_thread()->Invoke<void>(
1933 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1934 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08001935 // Make UMA notes about what was agreed to.
1936 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08001937 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001938 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08001939}
1940
1941RTCError PeerConnection::ApplyLocalDescription(
1942 std::unique_ptr<SessionDescriptionInterface> desc) {
1943 RTC_DCHECK_RUN_ON(signaling_thread());
1944 RTC_DCHECK(desc);
1945
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946 // Update stats here so that we have the most recent stats for tracks and
1947 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001948 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001949
Steve Antondcc3c022017-12-22 16:02:54 -08001950 // Take a reference to the old local description since it's used below to
1951 // compare against the new local description. When setting the new local
1952 // description, grab ownership of the replaced session description in case it
1953 // is the same as |old_local_description|, to keep it alive for the duration
1954 // of the method.
1955 const SessionDescriptionInterface* old_local_description =
1956 local_description();
1957 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07001958 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08001959 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08001960 replaced_local_description = pending_local_description_
1961 ? std::move(pending_local_description_)
1962 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001963 current_local_description_ = std::move(desc);
1964 pending_local_description_ = nullptr;
1965 current_remote_description_ = std::move(pending_remote_description_);
1966 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08001967 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08001968 pending_local_description_ = std::move(desc);
1969 }
1970 // The session description to apply now must be accessed by
1971 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001972 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001973
Zhi Huange830e682018-03-30 10:48:35 -07001974 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
1975 if (!error.ok()) {
1976 return error;
1977 }
1978
Steve Antondcc3c022017-12-22 16:02:54 -08001979 if (IsUnifiedPlan()) {
1980 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08001981 cricket::CS_LOCAL, *local_description(), old_local_description,
1982 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08001983 if (!error.ok()) {
1984 return error;
1985 }
Steve Anton0f5400a2018-07-17 14:25:36 -07001986 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
1987 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08001988 for (auto transceiver : transceivers_) {
1989 const ContentInfo* content =
1990 FindMediaSectionForTransceiver(transceiver, local_description());
1991 if (!content) {
1992 continue;
1993 }
1994 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07001995 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
1996 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08001997 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07001998 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
1999 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2000 // "recvonly", process the removal of a remote track for the media
2001 // description, given transceiver, removeList, and muteTracks.
2002 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2003 (transceiver->internal()->fired_direction() &&
2004 RtpTransceiverDirectionHasRecv(
2005 *transceiver->internal()->fired_direction()))) {
2006 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2007 &removed_streams);
2008 }
2009 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2010 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002011 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002012 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002013 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002014 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002015 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002016 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002017 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002018 }
2019 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002020 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002021 }
2022 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002023 // Media channels will be created only when offer is set. These may use new
2024 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002025 if (type == SdpType::kOffer) {
2026 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2027 // description is applied. Restore back to old description.
2028 RTCError error = CreateChannels(*local_description()->description());
2029 if (!error.ok()) {
2030 return error;
2031 }
2032 }
Steve Antondcc3c022017-12-22 16:02:54 -08002033 // Remove unused channels if MediaContentDescription is rejected.
2034 RemoveUnusedChannels(local_description()->description());
2035 }
Steve Anton8a006912017-12-04 15:25:56 -08002036
Zhi Huange830e682018-03-30 10:48:35 -07002037 error = UpdateSessionState(type, cricket::CS_LOCAL,
2038 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002039 if (!error.ok()) {
2040 return error;
2041 }
Steve Antondcc3c022017-12-22 16:02:54 -08002042
Steve Anton8a006912017-12-04 15:25:56 -08002043 if (remote_description()) {
2044 // Now that we have a local description, we can push down remote candidates.
2045 UseCandidatesInSessionDescription(remote_description());
2046 }
2047
2048 pending_ice_restarts_.clear();
2049 if (session_error() != SessionError::kNone) {
2050 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2051 }
2052
deadbeefab9b2d12015-10-14 11:33:11 -07002053 // If setting the description decided our SSL role, allocate any necessary
2054 // SCTP sids.
2055 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002056 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002057 AllocateSctpSids(role);
2058 }
2059
Steve Antond3679212018-01-17 17:41:02 -08002060 if (IsUnifiedPlan()) {
2061 for (auto transceiver : transceivers_) {
2062 const ContentInfo* content =
2063 FindMediaSectionForTransceiver(transceiver, local_description());
2064 if (!content) {
2065 continue;
2066 }
Steve Anton74255ff2018-01-24 18:32:57 -08002067 const auto& streams = content->media_description()->streams();
2068 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002069 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002070 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002071 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002072 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002073 } else {
2074 // 0 is a special value meaning "this sender has no associated send
2075 // stream". Need to call this so the sender won't attempt to configure
2076 // a no longer existing stream and run into DCHECKs in the lower
2077 // layers.
2078 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002079 }
2080 }
2081 } else {
2082 // Plan B semantics.
2083
Steve Antondcc3c022017-12-22 16:02:54 -08002084 // Update state and SSRC of local MediaStreams and DataChannels based on the
2085 // local session description.
2086 const cricket::ContentInfo* audio_content =
2087 GetFirstAudioContent(local_description()->description());
2088 if (audio_content) {
2089 if (audio_content->rejected) {
2090 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2091 } else {
2092 const cricket::AudioContentDescription* audio_desc =
2093 audio_content->media_description()->as_audio();
2094 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2095 }
deadbeeffaac4972015-11-12 15:33:07 -08002096 }
deadbeefab9b2d12015-10-14 11:33:11 -07002097
Steve Antondcc3c022017-12-22 16:02:54 -08002098 const cricket::ContentInfo* video_content =
2099 GetFirstVideoContent(local_description()->description());
2100 if (video_content) {
2101 if (video_content->rejected) {
2102 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2103 } else {
2104 const cricket::VideoContentDescription* video_desc =
2105 video_content->media_description()->as_video();
2106 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2107 }
deadbeeffaac4972015-11-12 15:33:07 -08002108 }
deadbeefab9b2d12015-10-14 11:33:11 -07002109 }
2110
2111 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002112 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002113 if (data_content) {
2114 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002115 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002116 if (rtc::starts_with(data_desc->protocol().data(),
2117 cricket::kMediaProtocolRtpPrefix)) {
2118 UpdateLocalRtpDataChannels(data_desc->streams());
2119 }
2120 }
2121
Steve Anton8a006912017-12-04 15:25:56 -08002122 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002123}
2124
2125void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002126 SetSessionDescriptionObserver* observer,
2127 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002128 SetRemoteDescription(
2129 std::unique_ptr<SessionDescriptionInterface>(desc),
2130 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2131 new SetRemoteDescriptionObserverAdapter(this, observer)));
2132}
2133
2134void PeerConnection::SetRemoteDescription(
2135 std::unique_ptr<SessionDescriptionInterface> desc,
2136 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002137 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002138
nisse7ce109a2017-01-31 00:57:56 -08002139 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002140 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002141 return;
2142 }
Steve Anton8a006912017-12-04 15:25:56 -08002143
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002144 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002145 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002146 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002147 return;
2148 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002149
Steve Anton80dd7b52018-02-16 17:08:42 -08002150 // If a session error has occurred the PeerConnection is in a possibly
2151 // inconsistent state so fail right away.
2152 if (session_error() != SessionError::kNone) {
2153 std::string error_message = GetSessionErrorMsg();
2154 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2155 observer->OnSetRemoteDescriptionComplete(
2156 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2157 return;
2158 }
Steve Anton71439a62018-02-15 11:53:06 -08002159
Steve Antonba42e992018-04-09 14:10:01 -07002160 if (desc->GetType() == SdpType::kOffer) {
2161 // Report to UMA the format of the received offer.
2162 ReportSdpFormatReceived(*desc);
2163 }
2164
Steve Anton80dd7b52018-02-16 17:08:42 -08002165 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002166 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002167 std::string error_message = GetSetDescriptionErrorMessage(
2168 cricket::CS_REMOTE, desc->GetType(), error);
2169 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002170 observer->OnSetRemoteDescriptionComplete(
2171 RTCError(error.type(), std::move(error_message)));
2172 return;
2173 }
Steve Anton71439a62018-02-15 11:53:06 -08002174
Steve Anton80dd7b52018-02-16 17:08:42 -08002175 // Grab the description type before moving ownership to
2176 // ApplyRemoteDescription, which may destroy it before returning.
2177 const SdpType type = desc->GetType();
2178
2179 error = ApplyRemoteDescription(std::move(desc));
2180 // |desc| may be destroyed at this point.
2181
2182 if (!error.ok()) {
2183 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2184 // inconsistent state, so act conservatively here and set the session error
2185 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2186 SetSessionError(SessionError::kContent, error.message());
2187 std::string error_message =
2188 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2189 RTC_LOG(LS_ERROR) << error_message;
2190 observer->OnSetRemoteDescriptionComplete(
2191 RTCError(error.type(), std::move(error_message)));
2192 return;
2193 }
2194 RTC_DCHECK(remote_description());
2195
2196 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002197 // TODO(deadbeef): We already had to hop to the network thread for
2198 // MaybeStartGathering...
2199 network_thread()->Invoke<void>(
2200 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2201 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002202 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002203 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002204 }
2205
2206 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002207 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002208}
2209
2210RTCError PeerConnection::ApplyRemoteDescription(
2211 std::unique_ptr<SessionDescriptionInterface> desc) {
2212 RTC_DCHECK_RUN_ON(signaling_thread());
2213 RTC_DCHECK(desc);
2214
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215 // Update stats here so that we have the most recent stats for tracks and
2216 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002217 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002218
Steve Antondcc3c022017-12-22 16:02:54 -08002219 // Take a reference to the old remote description since it's used below to
2220 // compare against the new remote description. When setting the new remote
2221 // description, grab ownership of the replaced session description in case it
2222 // is the same as |old_remote_description|, to keep it alive for the duration
2223 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002224 const SessionDescriptionInterface* old_remote_description =
2225 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002226 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002227 SdpType type = desc->GetType();
2228 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002229 replaced_remote_description = pending_remote_description_
2230 ? std::move(pending_remote_description_)
2231 : std::move(current_remote_description_);
2232 current_remote_description_ = std::move(desc);
2233 pending_remote_description_ = nullptr;
2234 current_local_description_ = std::move(pending_local_description_);
2235 } else {
2236 replaced_remote_description = std::move(pending_remote_description_);
2237 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238 }
Steve Anton8a006912017-12-04 15:25:56 -08002239 // The session description to apply now must be accessed by
2240 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002241 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002242
Zhi Huange830e682018-03-30 10:48:35 -07002243 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2244 if (!error.ok()) {
2245 return error;
2246 }
Steve Anton8a006912017-12-04 15:25:56 -08002247 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002248 if (IsUnifiedPlan()) {
2249 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002250 cricket::CS_REMOTE, *remote_description(), local_description(),
2251 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002252 if (!error.ok()) {
2253 return error;
2254 }
Steve Antondcc3c022017-12-22 16:02:54 -08002255 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002256 // Media channels will be created only when offer is set. These may use new
2257 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002258 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002259 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002260 // description is applied. Restore back to old description.
2261 RTCError error = CreateChannels(*remote_description()->description());
2262 if (!error.ok()) {
2263 return error;
2264 }
2265 }
Steve Antondcc3c022017-12-22 16:02:54 -08002266 // Remove unused channels if MediaContentDescription is rejected.
2267 RemoveUnusedChannels(remote_description()->description());
2268 }
Steve Anton8a006912017-12-04 15:25:56 -08002269
Zhi Huange830e682018-03-30 10:48:35 -07002270 // NOTE: Candidates allocation will be initiated only when
2271 // SetLocalDescription is called.
2272 error = UpdateSessionState(type, cricket::CS_REMOTE,
2273 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002274 if (!error.ok()) {
2275 return error;
2276 }
2277
2278 if (local_description() &&
2279 !UseCandidatesInSessionDescription(remote_description())) {
2280 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2281 }
2282
2283 if (old_remote_description) {
2284 for (const cricket::ContentInfo& content :
2285 old_remote_description->description()->contents()) {
2286 // Check if this new SessionDescription contains new ICE ufrag and
2287 // password that indicates the remote peer requests an ICE restart.
2288 // TODO(deadbeef): When we start storing both the current and pending
2289 // remote description, this should reset pending_ice_restarts and compare
2290 // against the current description.
2291 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2292 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002293 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002294 pending_ice_restarts_.insert(content.name);
2295 }
2296 } else {
2297 // We retain all received candidates only if ICE is not restarted.
2298 // When ICE is restarted, all previous candidates belong to an old
2299 // generation and should not be kept.
2300 // TODO(deadbeef): This goes against the W3C spec which says the remote
2301 // description should only contain candidates from the last set remote
2302 // description plus any candidates added since then. We should remove
2303 // this once we're sure it won't break anything.
2304 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2305 old_remote_description, content.name, mutable_remote_description());
2306 }
2307 }
2308 }
2309
2310 if (session_error() != SessionError::kNone) {
2311 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2312 }
2313
2314 // Set the the ICE connection state to connecting since the connection may
2315 // become writable with peer reflexive candidates before any remote candidate
2316 // is signaled.
2317 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2318 // is to have a new signal the indicates a change in checking state from the
2319 // transport and expose a new checking() member from transport that can be
2320 // read to determine the current checking state. The existing SignalConnecting
2321 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002322 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002323 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002324 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2325 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2326 }
2327
deadbeefab9b2d12015-10-14 11:33:11 -07002328 // If setting the description decided our SSL role, allocate any necessary
2329 // SCTP sids.
2330 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002331 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002332 AllocateSctpSids(role);
2333 }
2334
Steve Antondcc3c022017-12-22 16:02:54 -08002335 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002336 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002337 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002338 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002339 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002340 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002341 for (auto transceiver : transceivers_) {
2342 const ContentInfo* content =
2343 FindMediaSectionForTransceiver(transceiver, remote_description());
2344 if (!content) {
2345 continue;
2346 }
2347 const MediaContentDescription* media_desc = content->media_description();
2348 RtpTransceiverDirection local_direction =
2349 RtpTransceiverDirectionReversed(media_desc->direction());
2350 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2351 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2352 // transceiver's current direction is neither sendrecv nor recvonly,
2353 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002354 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002355 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002356 // The remote description has signaled the stream IDs.
2357 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002358 }
Steve Antondcc3c022017-12-22 16:02:54 -08002359 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002360 (!transceiver->fired_direction() ||
2361 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002362 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002363 << content->name << " (added to "
2364 << GetStreamIdsString(stream_ids) << ").";
2365
2366 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2367 for (const std::string& stream_id : stream_ids) {
2368 rtc::scoped_refptr<MediaStreamInterface> stream =
2369 remote_streams_->find(stream_id);
2370 if (!stream) {
2371 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2372 MediaStream::Create(stream_id));
2373 remote_streams_->AddStream(stream);
2374 added_streams.push_back(stream);
2375 }
2376 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002377 }
Steve Anton3172c032018-05-03 15:30:18 -07002378 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002379 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2380 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002381 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002382 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002383 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002384 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2385 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2386 // removal of a remote track for the media description, given transceiver,
2387 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002388 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002389 (transceiver->fired_direction() &&
2390 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2391 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2392 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002393 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002394 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2395 transceiver->internal()->set_fired_direction(local_direction);
2396 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2397 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002398 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002399 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2400 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002401 transceiver->internal()->set_current_direction(local_direction);
2402 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002403 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2404 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002405 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002406 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2407 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002408 transceiver->Stop();
2409 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002410 if (!content->rejected &&
2411 RtpTransceiverDirectionHasRecv(local_direction)) {
2412 // Set ssrc to 0 in the case of an unsignalled ssrc.
2413 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002414 if (!media_desc->streams().empty() &&
2415 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002416 ssrc = media_desc->streams()[0].first_ssrc();
2417 }
2418 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002419 }
Steve Antondcc3c022017-12-22 16:02:54 -08002420 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002421 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002422 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002423 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002424 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002425 observer->OnTrack(transceiver);
2426 observer->OnAddTrack(transceiver->receiver(),
2427 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002428 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002429 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002430 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002431 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002432 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002433 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002434 }
2435 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002436 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002437 }
Steve Antondcc3c022017-12-22 16:02:54 -08002438 }
2439
Henrik Boströmfdb92012017-11-09 19:55:44 +01002440 const cricket::ContentInfo* audio_content =
2441 GetFirstAudioContent(remote_description()->description());
2442 const cricket::ContentInfo* video_content =
2443 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002444 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002445 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002446 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002447 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002448 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002449 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002450
2451 // Check if the descriptions include streams, just in case the peer supports
2452 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002453 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002454 (audio_desc && !audio_desc->streams().empty()) ||
2455 (video_desc && !video_desc->streams().empty())) {
2456 remote_peer_supports_msid_ = true;
2457 }
deadbeefab9b2d12015-10-14 11:33:11 -07002458
2459 // We wait to signal new streams until we finish processing the description,
2460 // since only at that point will new streams have all their tracks.
2461 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2462
Steve Antondcc3c022017-12-22 16:02:54 -08002463 if (!IsUnifiedPlan()) {
2464 // TODO(steveanton): When removing RTP senders/receivers in response to a
2465 // rejected media section, there is some cleanup logic that expects the
2466 // voice/ video channel to still be set. But in this method the voice/video
2467 // channel would have been destroyed by the SetRemoteDescription caller
2468 // above so the cleanup that relies on them fails to run. The RemoveSenders
2469 // calls should be moved to right before the DestroyChannel calls to fix
2470 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002471
Steve Antondcc3c022017-12-22 16:02:54 -08002472 // Find all audio rtp streams and create corresponding remote AudioTracks
2473 // and MediaStreams.
2474 if (audio_content) {
2475 if (audio_content->rejected) {
2476 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2477 } else {
2478 bool default_audio_track_needed =
2479 !remote_peer_supports_msid_ &&
2480 RtpTransceiverDirectionHasSend(audio_desc->direction());
2481 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2482 default_audio_track_needed, audio_desc->type(),
2483 new_streams);
2484 }
deadbeeffaac4972015-11-12 15:33:07 -08002485 }
deadbeefab9b2d12015-10-14 11:33:11 -07002486
Steve Antondcc3c022017-12-22 16:02:54 -08002487 // Find all video rtp streams and create corresponding remote VideoTracks
2488 // and MediaStreams.
2489 if (video_content) {
2490 if (video_content->rejected) {
2491 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2492 } else {
2493 bool default_video_track_needed =
2494 !remote_peer_supports_msid_ &&
2495 RtpTransceiverDirectionHasSend(video_desc->direction());
2496 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2497 default_video_track_needed, video_desc->type(),
2498 new_streams);
2499 }
deadbeeffaac4972015-11-12 15:33:07 -08002500 }
deadbeefab9b2d12015-10-14 11:33:11 -07002501
Steve Antondcc3c022017-12-22 16:02:54 -08002502 // Update the DataChannels with the information from the remote peer.
2503 if (data_desc) {
2504 if (rtc::starts_with(data_desc->protocol().data(),
2505 cricket::kMediaProtocolRtpPrefix)) {
2506 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2507 }
deadbeefab9b2d12015-10-14 11:33:11 -07002508 }
deadbeefab9b2d12015-10-14 11:33:11 -07002509
Steve Antondcc3c022017-12-22 16:02:54 -08002510 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002511 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002512 for (size_t i = 0; i < new_streams->count(); ++i) {
2513 MediaStreamInterface* new_stream = new_streams->at(i);
2514 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002515 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002516 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2517 }
deadbeefab9b2d12015-10-14 11:33:11 -07002518
Steve Antondcc3c022017-12-22 16:02:54 -08002519 UpdateEndedRemoteMediaStreams();
2520 }
deadbeefab9b2d12015-10-14 11:33:11 -07002521
Steve Anton8a006912017-12-04 15:25:56 -08002522 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002523}
2524
Steve Anton0f5400a2018-07-17 14:25:36 -07002525void PeerConnection::ProcessRemovalOfRemoteTrack(
2526 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2527 transceiver,
2528 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2529 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2530 RTC_DCHECK(transceiver->mid());
2531 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2532 << *transceiver->mid();
2533 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2534 transceiver->internal()->receiver_internal()->streams();
2535 // This will remove the remote track from the streams.
2536 transceiver->internal()->receiver_internal()->set_stream_ids({});
2537 remove_list->push_back(transceiver);
2538 // Remove any streams that no longer have tracks.
2539 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2540 // of streams, see if the stream was removed by checking if this was the
2541 // last receiver with that stream ID.
2542 for (auto stream : media_streams) {
2543 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2544 remote_streams_->RemoveStream(stream);
2545 removed_streams->push_back(stream);
2546 }
2547 }
2548}
2549
Steve Antondcc3c022017-12-22 16:02:54 -08002550RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2551 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002552 const SessionDescriptionInterface& new_session,
2553 const SessionDescriptionInterface* old_local_description,
2554 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002555 RTC_DCHECK(IsUnifiedPlan());
2556
Steve Anton7464fca2018-01-19 11:10:37 -08002557 const cricket::ContentGroup* bundle_group = nullptr;
2558 if (new_session.GetType() == SdpType::kOffer) {
2559 auto bundle_group_or_error =
2560 GetEarlyBundleGroup(*new_session.description());
2561 if (!bundle_group_or_error.ok()) {
2562 return bundle_group_or_error.MoveError();
2563 }
2564 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002565 }
Steve Antondcc3c022017-12-22 16:02:54 -08002566
Steve Antondcc3c022017-12-22 16:02:54 -08002567 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002568 for (size_t i = 0; i < new_contents.size(); ++i) {
2569 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002570 cricket::MediaType media_type = new_content.media_description()->type();
2571 seen_mids_.insert(new_content.name);
2572 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2573 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002574 const cricket::ContentInfo* old_local_content = nullptr;
2575 if (old_local_description &&
2576 i < old_local_description->description()->contents().size()) {
2577 old_local_content =
2578 &old_local_description->description()->contents()[i];
2579 }
2580 const cricket::ContentInfo* old_remote_content = nullptr;
2581 if (old_remote_description &&
2582 i < old_remote_description->description()->contents().size()) {
2583 old_remote_content =
2584 &old_remote_description->description()->contents()[i];
2585 }
Steve Antondcc3c022017-12-22 16:02:54 -08002586 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002587 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2588 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002589 if (!transceiver_or_error.ok()) {
2590 return transceiver_or_error.MoveError();
2591 }
2592 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002593 RTCError error =
2594 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2595 if (!error.ok()) {
2596 return error;
2597 }
2598 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002599 if (GetDataMid() && new_content.name != *GetDataMid()) {
2600 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002601 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2602 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002603 continue;
2604 }
2605 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2606 if (!error.ok()) {
2607 return error;
2608 }
Steve Antondcc3c022017-12-22 16:02:54 -08002609 } else {
2610 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2611 "Unknown section type.");
2612 }
2613 }
2614
2615 return RTCError::OK();
2616}
2617
2618RTCError PeerConnection::UpdateTransceiverChannel(
2619 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2620 transceiver,
2621 const cricket::ContentInfo& content,
2622 const cricket::ContentGroup* bundle_group) {
2623 RTC_DCHECK(IsUnifiedPlan());
2624 RTC_DCHECK(transceiver);
2625 cricket::BaseChannel* channel = transceiver->internal()->channel();
2626 if (content.rejected) {
2627 if (channel) {
2628 transceiver->internal()->SetChannel(nullptr);
2629 DestroyBaseChannel(channel);
2630 }
2631 } else {
2632 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002633 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002634 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002635 } else {
Steve Anton69470252018-02-09 11:43:08 -08002636 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002637 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002638 }
2639 if (!channel) {
2640 LOG_AND_RETURN_ERROR(
2641 RTCErrorType::INTERNAL_ERROR,
2642 "Failed to create channel for mid=" + content.name);
2643 }
2644 transceiver->internal()->SetChannel(channel);
2645 }
2646 }
2647 return RTCError::OK();
2648}
2649
Steve Antonfa2260d2017-12-28 16:38:23 -08002650RTCError PeerConnection::UpdateDataChannel(
2651 cricket::ContentSource source,
2652 const cricket::ContentInfo& content,
2653 const cricket::ContentGroup* bundle_group) {
2654 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002655 // If data channels are disabled, ignore this media section. CreateAnswer
2656 // will take care of rejecting it.
2657 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002658 }
2659 if (content.rejected) {
2660 DestroyDataChannel();
2661 } else {
2662 if (!rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002663 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002664 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2665 "Failed to create data channel.");
2666 }
2667 }
2668 if (source == cricket::CS_REMOTE) {
2669 const MediaContentDescription* data_desc = content.media_description();
2670 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2671 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2672 }
2673 }
2674 }
2675 return RTCError::OK();
2676}
2677
Steve Antondcc3c022017-12-22 16:02:54 -08002678RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2679PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002680 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002681 size_t mline_index,
2682 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002683 const ContentInfo* old_local_content,
2684 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002685 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002686 // If this is an offer then the m= section might be recycled. If the m=
2687 // section is being recycled (defined as: rejected in the current local or
2688 // remote description and not rejected in new description), dissociate the
2689 // currently associated RtpTransceiver by setting its mid property to null,
2690 // and discard the mapping between the transceiver and its m= section index.
2691 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2692 old_remote_content)) {
2693 // We want to dissociate the transceiver that has the rejected mid.
2694 const std::string& old_mid =
2695 (old_local_content && old_local_content->rejected)
2696 ? old_local_content->name
2697 : old_remote_content->name;
2698 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002699 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002700 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2701 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002702 old_transceiver->internal()->set_mid(absl::nullopt);
2703 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002704 }
2705 }
2706 const MediaContentDescription* media_desc = content.media_description();
2707 auto transceiver = GetAssociatedTransceiver(content.name);
2708 if (source == cricket::CS_LOCAL) {
2709 // Find the RtpTransceiver that corresponds to this m= section, using the
2710 // mapping between transceivers and m= section indices established when
2711 // creating the offer.
2712 if (!transceiver) {
2713 transceiver = GetTransceiverByMLineIndex(mline_index);
2714 }
2715 if (!transceiver) {
2716 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2717 "Unknown transceiver");
2718 }
2719 } else {
2720 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2721 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2722 // of the same type...
2723 if (!transceiver &&
2724 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2725 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2726 }
2727 // If no RtpTransceiver was found in the previous step, create one with a
2728 // recvonly direction.
2729 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002730 RTC_LOG(LS_INFO) << "Adding "
2731 << cricket::MediaTypeToString(media_desc->type())
2732 << " transceiver for MID=" << content.name
2733 << " at i=" << mline_index
2734 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002735 std::string sender_id = rtc::CreateRandomUuid();
Steve Anton1bc97162018-06-25 14:04:01 -07002736 auto sender = CreateSender(media_desc->type(), sender_id, nullptr, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002737 std::string receiver_id;
2738 if (!media_desc->streams().empty()) {
2739 receiver_id = media_desc->streams()[0].id;
2740 } else {
2741 receiver_id = rtc::CreateRandomUuid();
2742 }
2743 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002744 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002745 transceiver->internal()->set_direction(
2746 RtpTransceiverDirection::kRecvOnly);
2747 }
2748 }
2749 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002750 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002751 LOG_AND_RETURN_ERROR(
2752 RTCErrorType::INVALID_PARAMETER,
2753 "Transceiver type does not match media description type.");
2754 }
2755 // Associate the found or created RtpTransceiver with the m= section by
2756 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2757 // section, and establish a mapping between the transceiver and the index of
2758 // the m= section.
2759 transceiver->internal()->set_mid(content.name);
2760 transceiver->internal()->set_mline_index(mline_index);
2761 return std::move(transceiver);
2762}
2763
2764rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2765PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2766 RTC_DCHECK(IsUnifiedPlan());
2767 for (auto transceiver : transceivers_) {
2768 if (transceiver->mid() == mid) {
2769 return transceiver;
2770 }
2771 }
2772 return nullptr;
2773}
2774
2775rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2776PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2777 RTC_DCHECK(IsUnifiedPlan());
2778 for (auto transceiver : transceivers_) {
2779 if (transceiver->internal()->mline_index() == mline_index) {
2780 return transceiver;
2781 }
2782 }
2783 return nullptr;
2784}
2785
2786rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2787PeerConnection::FindAvailableTransceiverToReceive(
2788 cricket::MediaType media_type) const {
2789 RTC_DCHECK(IsUnifiedPlan());
2790 // From JSEP section 5.10 (Applying a Remote Description):
2791 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2792 // the same type that were added to the PeerConnection by addTrack and are not
2793 // associated with any m= section and are not stopped, find the first such
2794 // RtpTransceiver.
2795 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002796 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002797 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2798 !transceiver->stopped()) {
2799 return transceiver;
2800 }
2801 }
2802 return nullptr;
2803}
2804
Steve Antoned10bd92017-12-05 10:52:59 -08002805const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2806 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2807 transceiver,
2808 const SessionDescriptionInterface* sdesc) const {
2809 RTC_DCHECK(transceiver);
2810 RTC_DCHECK(sdesc);
2811 if (IsUnifiedPlan()) {
2812 if (!transceiver->internal()->mid()) {
2813 // This transceiver is not associated with a media section yet.
2814 return nullptr;
2815 }
2816 return sdesc->description()->GetContentByName(
2817 *transceiver->internal()->mid());
2818 } else {
2819 // Plan B only allows at most one audio and one video section, so use the
2820 // first media section of that type.
2821 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002822 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002823 }
2824}
2825
deadbeef46c73892016-11-16 19:42:04 -08002826PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2827 return configuration_;
2828}
2829
deadbeef293e9262017-01-11 12:28:30 -08002830bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2831 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002832 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002833 if (IsClosed()) {
2834 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2835 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2836 }
2837
Qingsi Wanga2d60672018-04-11 16:57:45 -07002838 // According to JSEP, after setLocalDescription, changing the candidate pool
2839 // size is not allowed, and changing the set of ICE servers will not result
2840 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002841 if (local_description() && configuration.ice_candidate_pool_size !=
2842 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002843 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2844 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002845 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002846 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002847
deadbeef293e9262017-01-11 12:28:30 -08002848 // The simplest (and most future-compatible) way to tell if the config was
2849 // modified in an invalid way is to copy each property we do support
2850 // modifying, then use operator==. There are far more properties we don't
2851 // support modifying than those we do, and more could be added.
2852 RTCConfiguration modified_config = configuration_;
2853 modified_config.servers = configuration.servers;
2854 modified_config.type = configuration.type;
2855 modified_config.ice_candidate_pool_size =
2856 configuration.ice_candidate_pool_size;
2857 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08002858 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08002859 modified_config.ice_check_interval_strong_connectivity =
2860 configuration.ice_check_interval_strong_connectivity;
2861 modified_config.ice_check_interval_weak_connectivity =
2862 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07002863 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
2864 modified_config.ice_unwritable_min_checks =
2865 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002866 modified_config.stun_candidate_keepalive_interval =
2867 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02002868 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08002869 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07002870 modified_config.active_reset_srtp_params =
2871 configuration.active_reset_srtp_params;
deadbeef293e9262017-01-11 12:28:30 -08002872 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002873 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08002874 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2875 }
2876
Steve Anton038834f2017-07-14 15:59:59 -07002877 // Validate the modified configuration.
2878 RTCError validate_error = ValidateConfiguration(modified_config);
2879 if (!validate_error.ok()) {
2880 return SafeSetError(std::move(validate_error), error);
2881 }
2882
deadbeef293e9262017-01-11 12:28:30 -08002883 // Note that this isn't possible through chromium, since it's an unsigned
2884 // short in WebIDL.
2885 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07002886 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08002887 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
2888 }
2889
2890 // Parse ICE servers before hopping to network thread.
2891 cricket::ServerAddresses stun_servers;
2892 std::vector<cricket::RelayServerConfig> turn_servers;
2893 RTCErrorType parse_error =
2894 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
2895 if (parse_error != RTCErrorType::NONE) {
2896 return SafeSetError(parse_error, error);
2897 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002898 // Note if STUN or TURN servers were supplied.
2899 if (!stun_servers.empty()) {
2900 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
2901 }
2902 if (!turn_servers.empty()) {
2903 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
2904 }
deadbeef293e9262017-01-11 12:28:30 -08002905
2906 // In theory this shouldn't fail.
2907 if (!network_thread()->Invoke<bool>(
2908 RTC_FROM_HERE,
2909 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
2910 stun_servers, turn_servers, modified_config.type,
2911 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02002912 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08002913 modified_config.turn_customizer,
2914 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002915 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08002916 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
2917 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002918
deadbeefd1a38b52016-12-10 13:15:33 -08002919 // As described in JSEP, calling setConfiguration with new ICE servers or
2920 // candidate policy must set a "needs-ice-restart" bit so that the next offer
2921 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08002922 if (modified_config.servers != configuration_.servers ||
2923 modified_config.type != configuration_.type ||
2924 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08002925 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08002926 }
skvladd1f5fda2017-02-03 16:54:05 -08002927
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08002928 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08002929
Zhi Huangb57e1692018-06-12 11:41:11 -07002930 if (configuration_.active_reset_srtp_params !=
2931 modified_config.active_reset_srtp_params) {
2932 transport_controller_->SetActiveResetSrtpParams(
2933 modified_config.active_reset_srtp_params);
2934 }
2935
deadbeef293e9262017-01-11 12:28:30 -08002936 configuration_ = modified_config;
2937 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002938}
2939
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002940bool PeerConnection::AddIceCandidate(
2941 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002942 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07002943 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002944 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002945 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07002946 return false;
2947 }
Steve Antond25da372017-11-06 14:50:29 -08002948
2949 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07002950 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01002951 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002952 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08002953 return false;
2954 }
2955
2956 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07002957 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002958 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08002959 return false;
2960 }
2961
2962 bool valid = false;
2963 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
2964 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002965 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08002966 return false;
2967 }
2968
2969 // Add this candidate to the remote session description.
2970 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07002971 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002972 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08002973 return false;
2974 }
2975
2976 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02002977 bool result = UseCandidate(ice_candidate);
2978 if (result) {
2979 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
2980 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
2981 } else {
2982 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
2983 }
2984 return result;
Steve Antond25da372017-11-06 14:50:29 -08002985 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07002986 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02002987 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08002988 return true;
2989 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002990}
2991
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002992bool PeerConnection::RemoveIceCandidates(
2993 const std::vector<cricket::Candidate>& candidates) {
2994 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07002995 if (IsClosed()) {
2996 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
2997 return false;
2998 }
2999
Steve Antond25da372017-11-06 14:50:29 -08003000 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003001 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3002 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003003 return false;
3004 }
3005
3006 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003007 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003008 return false;
3009 }
3010
3011 size_t number_removed =
3012 mutable_remote_description()->RemoveCandidates(candidates);
3013 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003014 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003015 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003016 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003017 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003018 }
3019
3020 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003021 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3022 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003023 RTC_LOG(LS_ERROR)
3024 << "RemoveIceCandidates: Error when removing remote candidates: "
3025 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003026 }
3027 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003028}
3029
Niels Möller0c4f7be2018-05-07 14:01:37 +02003030RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003031 if (!worker_thread()->IsCurrent()) {
3032 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003033 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003034 }
3035
Niels Möller0c4f7be2018-05-07 14:01:37 +02003036 const bool has_min = bitrate.min_bitrate_bps.has_value();
3037 const bool has_start = bitrate.start_bitrate_bps.has_value();
3038 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003039 if (has_min && *bitrate.min_bitrate_bps < 0) {
3040 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3041 "min_bitrate_bps <= 0");
3042 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003043 if (has_start) {
3044 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003045 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003046 "start_bitrate_bps < min_bitrate_bps");
3047 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003048 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3049 "curent_bitrate_bps < 0");
3050 }
3051 }
3052 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003053 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003054 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003055 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003056 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3057 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3058 "max_bitrate_bps < min_bitrate_bps");
3059 } else if (*bitrate.max_bitrate_bps < 0) {
3060 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3061 "max_bitrate_bps < 0");
3062 }
3063 }
3064
zstein4b979802017-06-02 14:37:37 -07003065 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003066 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003067
3068 return RTCError::OK();
3069}
3070
Alex Narest78609d52017-10-20 10:37:47 +02003071void PeerConnection::SetBitrateAllocationStrategy(
3072 std::unique_ptr<rtc::BitrateAllocationStrategy>
3073 bitrate_allocation_strategy) {
3074 rtc::Thread* worker_thread = factory_->worker_thread();
3075 if (!worker_thread->IsCurrent()) {
3076 rtc::BitrateAllocationStrategy* strategy_raw =
3077 bitrate_allocation_strategy.release();
3078 auto functor = [this, strategy_raw]() {
3079 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003080 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003081 };
3082 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3083 return;
3084 }
3085 RTC_DCHECK(call_.get());
3086 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3087}
3088
henrika5f6bf242017-11-01 11:06:56 +01003089void PeerConnection::SetAudioPlayout(bool playout) {
3090 if (!worker_thread()->IsCurrent()) {
3091 worker_thread()->Invoke<void>(
3092 RTC_FROM_HERE,
3093 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3094 return;
3095 }
3096 auto audio_state =
3097 factory_->channel_manager()->media_engine()->GetAudioState();
3098 audio_state->SetPlayout(playout);
3099}
3100
3101void PeerConnection::SetAudioRecording(bool recording) {
3102 if (!worker_thread()->IsCurrent()) {
3103 worker_thread()->Invoke<void>(
3104 RTC_FROM_HERE,
3105 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3106 return;
3107 }
3108 auto audio_state =
3109 factory_->channel_manager()->media_engine()->GetAudioState();
3110 audio_state->SetRecording(recording);
3111}
3112
Steve Anton8c0f7a72017-10-03 10:03:10 -07003113std::unique_ptr<rtc::SSLCertificate>
3114PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003115 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3116 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003117 return nullptr;
3118 }
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003119 return chain->Get(0).GetUniqueReference();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003120}
3121
Zhi Huang70b820f2018-01-27 14:16:15 -08003122std::unique_ptr<rtc::SSLCertChain>
3123PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003124 auto audio_transceiver = GetFirstAudioTransceiver();
3125 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003126 return nullptr;
3127 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003128 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003129 audio_transceiver->internal()->channel()->transport_name());
3130}
3131
3132rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3133PeerConnection::GetFirstAudioTransceiver() const {
3134 for (auto transceiver : transceivers_) {
3135 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3136 return transceiver;
3137 }
3138 }
3139 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003140}
3141
ivoc14d5dbe2016-07-04 07:06:55 -07003142bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3143 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003144 // TODO(eladalon): It would be better to not allow negative values into PC.
3145 const size_t max_size = (max_size_bytes < 0)
3146 ? RtcEventLog::kUnlimitedOutput
3147 : rtc::saturated_cast<size_t>(max_size_bytes);
3148 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003149 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003150 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003151}
3152
Bjorn Tereliusde939432017-11-20 17:38:14 +01003153bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3154 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003155 // TODO(eladalon): In C++14, this can be done with a lambda.
3156 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003157 bool operator()() {
3158 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3159 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003160 PeerConnection* const pc;
3161 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003162 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003163 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003164 return worker_thread()->Invoke<bool>(
3165 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003166}
3167
3168void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003169 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003170 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3171}
3172
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003173const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003174 return pending_local_description_ ? pending_local_description_.get()
3175 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003176}
3177
3178const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003179 return pending_remote_description_ ? pending_remote_description_.get()
3180 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003181}
3182
deadbeeffe4a8a42016-12-20 17:56:17 -08003183const SessionDescriptionInterface* PeerConnection::current_local_description()
3184 const {
Steve Anton75737c02017-11-06 10:37:17 -08003185 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003186}
3187
3188const SessionDescriptionInterface* PeerConnection::current_remote_description()
3189 const {
Steve Anton75737c02017-11-06 10:37:17 -08003190 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003191}
3192
3193const SessionDescriptionInterface* PeerConnection::pending_local_description()
3194 const {
Steve Anton75737c02017-11-06 10:37:17 -08003195 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003196}
3197
3198const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3199 const {
Steve Anton75737c02017-11-06 10:37:17 -08003200 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003201}
3202
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003203void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003204 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003205 // Update stats here so that we have the most recent stats for tracks and
3206 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003207 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003208
Steve Anton75737c02017-11-06 10:37:17 -08003209 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003210 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003211
Steve Anton8af21862017-12-15 11:20:13 -08003212 for (auto transceiver : transceivers_) {
3213 transceiver->Stop();
3214 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003215
3216 // Ensure that all asynchronous stats requests are completed before destroying
3217 // the transport controller below.
3218 if (stats_collector_) {
3219 stats_collector_->WaitForPendingRequest();
3220 }
3221
3222 // Don't destroy BaseChannels until after stats has been cleaned up so that
3223 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003224 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003225
Qingsi Wang93a84392018-01-30 17:13:09 -08003226 // The event log is used in the transport controller, which must be outlived
3227 // by the former. CreateOffer by the peer connection is implemented
3228 // asynchronously and if the peer connection is closed without resetting the
3229 // WebRTC session description factory, the session description factory would
3230 // call the transport controller.
3231 webrtc_session_desc_factory_.reset();
3232 transport_controller_.reset();
3233
deadbeef42a42632017-03-10 15:18:00 -08003234 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003235 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3236 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003237
Steve Anton978b8762017-09-29 12:15:02 -07003238 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003239 call_.reset();
3240 // The event log must outlive call (and any other object that uses it).
3241 event_log_.reset();
3242 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003243 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003244 // The .h file says that observer can be discarded after close() returns.
3245 // Make sure this is true.
3246 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003247}
3248
Steve Antonad182762018-09-05 20:22:40 +00003249void PeerConnection::OnMessage(rtc::Message* msg) {
3250 switch (msg->message_id) {
3251 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3252 SetSessionDescriptionMsg* param =
3253 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3254 param->observer->OnSuccess();
3255 delete param;
3256 break;
3257 }
3258 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3259 SetSessionDescriptionMsg* param =
3260 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3261 param->observer->OnFailure(std::move(param->error));
3262 delete param;
3263 break;
3264 }
3265 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3266 CreateSessionDescriptionMsg* param =
3267 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3268 param->observer->OnFailure(std::move(param->error));
3269 delete param;
3270 break;
3271 }
3272 case MSG_GETSTATS: {
3273 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3274 StatsReports reports;
3275 stats_->GetStats(param->track, &reports);
3276 param->observer->OnComplete(reports);
3277 delete param;
3278 break;
3279 }
3280 case MSG_FREE_DATACHANNELS: {
3281 sctp_data_channels_to_free_.clear();
3282 break;
3283 }
3284 case MSG_REPORT_USAGE_PATTERN: {
3285 ReportUsagePattern();
3286 break;
3287 }
3288 default:
3289 RTC_NOTREACHED() << "Not implemented";
3290 break;
3291 }
3292}
3293
Steve Antonafb0bb72018-02-20 11:35:37 -08003294cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3295 RTC_DCHECK(!IsUnifiedPlan());
3296 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3297 GetAudioTransceiver()->internal()->channel());
3298 if (voice_channel) {
3299 return voice_channel->media_channel();
3300 } else {
3301 return nullptr;
3302 }
3303}
3304
3305cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3306 RTC_DCHECK(!IsUnifiedPlan());
3307 auto* video_channel = static_cast<cricket::VideoChannel*>(
3308 GetVideoTransceiver()->internal()->channel());
3309 if (video_channel) {
3310 return video_channel->media_channel();
3311 } else {
3312 return nullptr;
3313 }
3314}
3315
Steve Anton4171afb2017-11-20 10:20:22 -08003316void PeerConnection::CreateAudioReceiver(
3317 MediaStreamInterface* stream,
3318 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003319 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3320 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003321 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3322 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003323 auto* audio_receiver = new AudioRtpReceiver(
3324 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003325 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003326 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3327 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3328 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003329 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003330 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003331 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003332}
3333
Steve Anton4171afb2017-11-20 10:20:22 -08003334void PeerConnection::CreateVideoReceiver(
3335 MediaStreamInterface* stream,
3336 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003337 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3338 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003339 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3340 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003341 auto* video_receiver = new VideoRtpReceiver(
3342 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003343 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003344 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3345 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3346 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003347 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003348 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003349 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003350}
3351
deadbeef70ab1a12015-09-28 16:53:55 -07003352// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3353// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003354rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003355 const RtpSenderInfo& remote_sender_info) {
3356 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3357 if (!receiver) {
3358 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3359 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003360 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003361 }
Steve Anton4171afb2017-11-20 10:20:22 -08003362 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3363 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3364 } else {
3365 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3366 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003367 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003368}
3369
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003370void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3371 MediaStreamInterface* stream) {
3372 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003373 RTC_DCHECK(track);
3374 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003375 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003376 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003377 // We already have a sender for this track, so just change the stream_id
3378 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003379 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003380 return;
3381 }
3382
3383 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003384 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
3385 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003386 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003387 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003388 // If the sender has already been configured in SDP, we call SetSsrc,
3389 // which will connect the sender to the underlying transport. This can
3390 // occur if a local session description that contains the ID of the sender
3391 // is set before AddStream is called. It can also occur if the local
3392 // session description is not changed and RemoveStream is called, and
3393 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003394 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003395 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003396 if (sender_info) {
3397 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003398 }
3399}
3400
3401// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3402// indefinitely, when we have unified plan SDP.
3403void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3404 MediaStreamInterface* stream) {
3405 RTC_DCHECK(!IsClosed());
3406 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003407 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003408 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3409 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003410 return;
3411 }
Steve Anton4171afb2017-11-20 10:20:22 -08003412 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003413}
3414
3415void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3416 MediaStreamInterface* stream) {
3417 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003418 RTC_DCHECK(track);
3419 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003420 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003421 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003422 // We already have a sender for this track, so just change the stream_id
3423 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003424 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003425 return;
3426 }
3427
3428 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003429 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
3430 {stream->id()});
Steve Anton57858b32018-02-15 15:19:50 -08003431 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003432 GetVideoTransceiver()->internal()->AddSender(new_sender);
3433 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003434 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003435 if (sender_info) {
3436 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003437 }
3438}
3439
3440void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3441 MediaStreamInterface* stream) {
3442 RTC_DCHECK(!IsClosed());
3443 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003444 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003445 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3446 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003447 return;
3448 }
Steve Anton4171afb2017-11-20 10:20:22 -08003449 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003450}
3451
Steve Antonba818672017-11-06 10:21:57 -08003452void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003453 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003454 if (ice_connection_state_ == new_state) {
3455 return;
3456 }
3457
deadbeefcbecd352015-09-23 11:50:27 -07003458 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003459 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003460 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003461 return;
3462 }
Steve Antonba818672017-11-06 10:21:57 -08003463
Mirko Bonadei675513b2017-11-09 11:09:25 +01003464 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3465 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003466 RTC_DCHECK(ice_connection_state_ !=
3467 PeerConnectionInterface::kIceConnectionClosed);
3468
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003469 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003470 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003471}
3472
3473void PeerConnection::OnIceGatheringChange(
3474 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003475 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003476 if (IsClosed()) {
3477 return;
3478 }
3479 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003480 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003481}
3482
jbauch81bf7b02017-03-25 08:31:12 -07003483void PeerConnection::OnIceCandidate(
3484 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003485 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003486 if (IsClosed()) {
3487 return;
3488 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003489 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003490 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3491 candidate->candidate().address().IsPrivateIP()) {
3492 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3493 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003494 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003495}
3496
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003497void PeerConnection::OnIceCandidatesRemoved(
3498 const std::vector<cricket::Candidate>& candidates) {
3499 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003500 if (IsClosed()) {
3501 return;
3502 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003503 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003504}
3505
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003506void PeerConnection::ChangeSignalingState(
3507 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003508 RTC_DCHECK(signaling_thread()->IsCurrent());
3509 if (signaling_state_ == signaling_state) {
3510 return;
3511 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003512 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3513 << GetSignalingStateString(signaling_state_)
3514 << " New state: "
3515 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003516 signaling_state_ = signaling_state;
3517 if (signaling_state == kClosed) {
3518 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003519 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003520 if (ice_gathering_state_ != kIceGatheringComplete) {
3521 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003522 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003523 }
3524 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003525 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003526}
3527
deadbeefeb459812015-12-15 19:24:43 -08003528void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3529 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003530 if (IsClosed()) {
3531 return;
3532 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003533 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003534 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003535}
3536
deadbeefeb459812015-12-15 19:24:43 -08003537void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3538 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003539 if (IsClosed()) {
3540 return;
3541 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003542 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003543 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003544}
3545
3546void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3547 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003548 if (IsClosed()) {
3549 return;
3550 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003551 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003552 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003553}
3554
3555void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3556 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003557 if (IsClosed()) {
3558 return;
3559 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003560 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003561 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003562}
3563
Henrik Boström31638672017-11-23 17:48:32 +01003564void PeerConnection::PostSetSessionDescriptionSuccess(
3565 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003566 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3567 signaling_thread()->Post(RTC_FROM_HERE, this,
3568 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003569}
3570
deadbeefab9b2d12015-10-14 11:33:11 -07003571void PeerConnection::PostSetSessionDescriptionFailure(
3572 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003573 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003574 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003575 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3576 msg->error = std::move(error);
3577 signaling_thread()->Post(RTC_FROM_HERE, this,
3578 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003579}
3580
3581void PeerConnection::PostCreateSessionDescriptionFailure(
3582 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003583 RTCError error) {
3584 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003585 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3586 msg->error = std::move(error);
3587 signaling_thread()->Post(RTC_FROM_HERE, this,
3588 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003589}
3590
zhihuang1c378ed2017-08-17 14:10:50 -07003591void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003592 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003593 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003594 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003595
Steve Antondcc3c022017-12-22 16:02:54 -08003596 if (IsUnifiedPlan()) {
3597 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3598 } else {
3599 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3600 }
3601
Steve Antonfa2260d2017-12-28 16:38:23 -08003602 // Intentionally unset the data channel type for RTP data channel with the
3603 // second condition. Otherwise the RTP data channels would be successfully
3604 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3605 // when building with chromium. We want to leave RTP data channels broken, so
3606 // people won't try to use them.
3607 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3608 session_options->data_channel_type = data_channel_type();
3609 }
3610
Steve Antondcc3c022017-12-22 16:02:54 -08003611 // Apply ICE restart flag and renomination flag.
3612 for (auto& options : session_options->media_description_options) {
3613 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3614 options.transport_options.enable_ice_renomination =
3615 configuration_.enable_ice_renomination;
3616 }
3617
3618 session_options->rtcp_cname = rtcp_cname_;
3619 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003620 session_options->is_unified_plan = IsUnifiedPlan();
Steve Antondcc3c022017-12-22 16:02:54 -08003621}
3622
3623void PeerConnection::GetOptionsForPlanBOffer(
3624 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3625 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003626 // Figure out transceiver directional preferences.
3627 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3628 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3629
3630 // By default, generate sendrecv/recvonly m= sections.
3631 bool recv_audio = true;
3632 bool recv_video = true;
3633
3634 // By default, only offer a new m= section if we have media to send with it.
3635 bool offer_new_audio_description = send_audio;
3636 bool offer_new_video_description = send_video;
3637 bool offer_new_data_description = HasDataChannels();
3638
3639 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003640 if (offer_answer_options.offer_to_receive_audio !=
3641 RTCOfferAnswerOptions::kUndefined) {
3642 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003643 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003644 offer_new_audio_description ||
3645 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003646 }
Steve Antondcc3c022017-12-22 16:02:54 -08003647 if (offer_answer_options.offer_to_receive_video !=
3648 RTCOfferAnswerOptions::kUndefined) {
3649 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003650 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003651 offer_new_video_description ||
3652 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003653 }
3654
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003655 absl::optional<size_t> audio_index;
3656 absl::optional<size_t> video_index;
3657 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003658 // If a current description exists, generate m= sections in the same order,
3659 // using the first audio/video/data section that appears and rejecting
3660 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003661 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003662 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003663 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003664 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3665 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3666 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003667 }
3668
zhihuang1c378ed2017-08-17 14:10:50 -07003669 // Add audio/video/data m= sections to the end if needed.
3670 if (!audio_index && offer_new_audio_description) {
3671 session_options->media_description_options.push_back(
3672 cricket::MediaDescriptionOptions(
3673 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003674 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3675 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003676 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003677 }
zhihuang1c378ed2017-08-17 14:10:50 -07003678 if (!video_index && offer_new_video_description) {
3679 session_options->media_description_options.push_back(
3680 cricket::MediaDescriptionOptions(
3681 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003682 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3683 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003684 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003685 }
zhihuang1c378ed2017-08-17 14:10:50 -07003686 if (!data_index && offer_new_data_description) {
3687 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003688 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003689 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003690 }
3691
3692 cricket::MediaDescriptionOptions* audio_media_description_options =
3693 !audio_index ? nullptr
3694 : &session_options->media_description_options[*audio_index];
3695 cricket::MediaDescriptionOptions* video_media_description_options =
3696 !video_index ? nullptr
3697 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003698
Steve Anton4171afb2017-11-20 10:20:22 -08003699 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003700 video_media_description_options,
3701 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003702}
3703
3704// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3705// and return a reference to it.
3706// Generated MIDs should be no more than 3 bytes long to take up less space in
3707// the RTP packet.
3708static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3709 RTC_DCHECK(used_mids);
3710 // We're boring: just generate MIDs 0, 1, 2, ...
3711 size_t i = 0;
3712 std::set<std::string>::iterator it;
3713 bool inserted;
3714 do {
3715 std::string mid = rtc::ToString(i++);
3716 auto insert_result = used_mids->insert(mid);
3717 it = insert_result.first;
3718 inserted = insert_result.second;
3719 } while (!inserted);
3720 return *it;
3721}
3722
3723static cricket::MediaDescriptionOptions
3724GetMediaDescriptionOptionsForTransceiver(
3725 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3726 transceiver,
3727 const std::string& mid) {
3728 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003729 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003730 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003731 // This behavior is specified in JSEP. The gist is that:
3732 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3733 // sendrecv.
3734 // 2. If the MSID is included, then it must be included in any subsequent
3735 // offer/answer exactly the same until the RtpTransceiver is stopped.
3736 if (!transceiver->stopped() &&
3737 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3738 transceiver->internal()->has_ever_been_used_to_send())) {
3739 cricket::SenderOptions sender_options;
3740 sender_options.track_id = transceiver->sender()->id();
3741 sender_options.stream_ids = transceiver->sender()->stream_ids();
3742 // TODO(bugs.webrtc.org/7600): Set num_sim_layers to the number of encodings
3743 // set in the RTP parameters when the transceiver was added.
3744 sender_options.num_sim_layers = 1;
3745 media_description_options.sender_options.push_back(sender_options);
3746 }
Steve Antondcc3c022017-12-22 16:02:54 -08003747 return media_description_options;
3748}
3749
3750void PeerConnection::GetOptionsForUnifiedPlanOffer(
3751 const RTCOfferAnswerOptions& offer_answer_options,
3752 cricket::MediaSessionOptions* session_options) {
3753 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3754 // Offers) and 5.2.2 (Subsequent Offers).
3755 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3756 const ContentInfos& local_contents =
3757 (local_description() ? local_description()->description()->contents()
3758 : ContentInfos());
3759 const ContentInfos& remote_contents =
3760 (remote_description() ? remote_description()->description()->contents()
3761 : ContentInfos());
3762 // The mline indices that can be recycled. New transceivers should reuse these
3763 // slots first.
3764 std::queue<size_t> recycleable_mline_indices;
3765 // Track the MIDs used in previous offer/answer exchanges and the current
3766 // offer so that new, unique MIDs are generated.
3767 std::set<std::string> used_mids = seen_mids_;
3768 // First, go through each media section that exists in either the local or
3769 // remote description and generate a media section in this offer for the
3770 // associated transceiver. If a media section can be recycled, generate a
3771 // default, rejected media section here that can be later overwritten.
3772 for (size_t i = 0;
3773 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3774 // Either |local_content| or |remote_content| is non-null.
3775 const ContentInfo* local_content =
3776 (i < local_contents.size() ? &local_contents[i] : nullptr);
3777 const ContentInfo* remote_content =
3778 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3779 bool had_been_rejected = (local_content && local_content->rejected) ||
3780 (remote_content && remote_content->rejected);
3781 const std::string& mid =
3782 (local_content ? local_content->name : remote_content->name);
3783 cricket::MediaType media_type =
3784 (local_content ? local_content->media_description()->type()
3785 : remote_content->media_description()->type());
3786 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3787 media_type == cricket::MEDIA_TYPE_VIDEO) {
3788 auto transceiver = GetAssociatedTransceiver(mid);
3789 RTC_CHECK(transceiver);
3790 // A media section is considered eligible for recycling if it is marked as
3791 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003792 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003793 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003794 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3795 RtpTransceiverDirection::kInactive,
3796 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003797 recycleable_mline_indices.push(i);
3798 } else {
3799 session_options->media_description_options.push_back(
3800 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3801 // CreateOffer shouldn't really cause any state changes in
3802 // PeerConnection, but we need a way to match new transceivers to new
3803 // media sections in SetLocalDescription and JSEP specifies this is done
3804 // by recording the index of the media section generated for the
3805 // transceiver in the offer.
3806 transceiver->internal()->set_mline_index(i);
3807 }
3808 } else {
3809 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08003810 RTC_CHECK(GetDataMid());
3811 if (had_been_rejected || mid != *GetDataMid()) {
3812 session_options->media_description_options.push_back(
3813 GetMediaDescriptionOptionsForRejectedData(mid));
3814 } else {
3815 session_options->media_description_options.push_back(
3816 GetMediaDescriptionOptionsForActiveData(mid));
3817 }
Steve Antondcc3c022017-12-22 16:02:54 -08003818 }
3819 }
3820 // Next, look for transceivers that are newly added (that is, are not stopped
3821 // and not associated). Reuse media sections marked as recyclable first,
3822 // otherwise append to the end of the offer. New media sections should be
3823 // added in the order they were added to the PeerConnection.
3824 for (auto transceiver : transceivers_) {
3825 if (transceiver->mid() || transceiver->stopped()) {
3826 continue;
3827 }
3828 size_t mline_index;
3829 if (!recycleable_mline_indices.empty()) {
3830 mline_index = recycleable_mline_indices.front();
3831 recycleable_mline_indices.pop();
3832 session_options->media_description_options[mline_index] =
3833 GetMediaDescriptionOptionsForTransceiver(transceiver,
3834 AllocateMid(&used_mids));
3835 } else {
3836 mline_index = session_options->media_description_options.size();
3837 session_options->media_description_options.push_back(
3838 GetMediaDescriptionOptionsForTransceiver(transceiver,
3839 AllocateMid(&used_mids)));
3840 }
3841 // See comment above for why CreateOffer changes the transceiver's state.
3842 transceiver->internal()->set_mline_index(mline_index);
3843 }
Steve Antonfa2260d2017-12-28 16:38:23 -08003844 // Lastly, add a m-section if we have local data channels and an m section
3845 // does not already exist.
3846 if (!GetDataMid() && HasDataChannels()) {
3847 session_options->media_description_options.push_back(
3848 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
3849 }
Steve Antondcc3c022017-12-22 16:02:54 -08003850}
3851
3852void PeerConnection::GetOptionsForAnswer(
3853 const RTCOfferAnswerOptions& offer_answer_options,
3854 cricket::MediaSessionOptions* session_options) {
3855 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
3856
3857 if (IsUnifiedPlan()) {
3858 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
3859 } else {
3860 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
3861 }
3862
Steve Antonfa2260d2017-12-28 16:38:23 -08003863 // Intentionally unset the data channel type for RTP data channel. Otherwise
3864 // the RTP data channels would be successfully negotiated by default and the
3865 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
3866 // We want to leave RTP data channels broken, so people won't try to use them.
3867 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3868 session_options->data_channel_type = data_channel_type();
3869 }
3870
Steve Antondcc3c022017-12-22 16:02:54 -08003871 // Apply ICE renomination flag.
3872 for (auto& options : session_options->media_description_options) {
3873 options.transport_options.enable_ice_renomination =
3874 configuration_.enable_ice_renomination;
3875 }
zhihuang8f65cdf2016-05-06 18:40:30 -07003876
3877 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07003878 session_options->crypto_options = factory_->options().crypto_options;
Steve Antone831b8c2018-02-01 12:22:16 -08003879 session_options->is_unified_plan = IsUnifiedPlan();
deadbeefab9b2d12015-10-14 11:33:11 -07003880}
3881
Steve Antondcc3c022017-12-22 16:02:54 -08003882void PeerConnection::GetOptionsForPlanBAnswer(
3883 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003884 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003885 // Figure out transceiver directional preferences.
3886 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3887 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3888
3889 // By default, generate sendrecv/recvonly m= sections. The direction is also
3890 // restricted by the direction in the offer.
3891 bool recv_audio = true;
3892 bool recv_video = true;
3893
3894 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003895 if (offer_answer_options.offer_to_receive_audio !=
3896 RTCOfferAnswerOptions::kUndefined) {
3897 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08003898 }
Steve Antondcc3c022017-12-22 16:02:54 -08003899 if (offer_answer_options.offer_to_receive_video !=
3900 RTCOfferAnswerOptions::kUndefined) {
3901 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003902 }
3903
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003904 absl::optional<size_t> audio_index;
3905 absl::optional<size_t> video_index;
3906 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08003907
3908 // Generate m= sections that match those in the offer.
3909 // Note that mediasession.cc will handle intersection our preferred
3910 // direction with the offered direction.
3911 GenerateMediaDescriptionOptions(
3912 remote_description(),
3913 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3914 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
3915 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003916
3917 cricket::MediaDescriptionOptions* audio_media_description_options =
3918 !audio_index ? nullptr
3919 : &session_options->media_description_options[*audio_index];
3920 cricket::MediaDescriptionOptions* video_media_description_options =
3921 !video_index ? nullptr
3922 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003923
Steve Anton4171afb2017-11-20 10:20:22 -08003924 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003925 video_media_description_options,
3926 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003927}
zhihuangaf388472016-11-02 16:49:48 -07003928
Steve Antondcc3c022017-12-22 16:02:54 -08003929void PeerConnection::GetOptionsForUnifiedPlanAnswer(
3930 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3931 cricket::MediaSessionOptions* session_options) {
3932 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
3933 // Answers) and 5.3.2 (Subsequent Answers).
3934 RTC_DCHECK(remote_description());
3935 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
3936 for (const ContentInfo& content :
3937 remote_description()->description()->contents()) {
3938 cricket::MediaType media_type = content.media_description()->type();
3939 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3940 media_type == cricket::MEDIA_TYPE_VIDEO) {
3941 auto transceiver = GetAssociatedTransceiver(content.name);
3942 RTC_CHECK(transceiver);
3943 session_options->media_description_options.push_back(
3944 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
3945 } else {
3946 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08003947 // Reject all data sections if data channels are disabled.
3948 // Reject a data section if it has already been rejected.
3949 // Reject all data sections except for the first one.
3950 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
3951 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08003952 session_options->media_description_options.push_back(
3953 GetMediaDescriptionOptionsForRejectedData(content.name));
3954 } else {
3955 session_options->media_description_options.push_back(
3956 GetMediaDescriptionOptionsForActiveData(content.name));
3957 }
Steve Antondcc3c022017-12-22 16:02:54 -08003958 }
3959 }
htaa2a49d92016-03-04 02:51:39 -08003960}
3961
zhihuang1c378ed2017-08-17 14:10:50 -07003962void PeerConnection::GenerateMediaDescriptionOptions(
3963 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08003964 RtpTransceiverDirection audio_direction,
3965 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003966 absl::optional<size_t>* audio_index,
3967 absl::optional<size_t>* video_index,
3968 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08003969 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003970 for (const cricket::ContentInfo& content :
3971 session_desc->description()->contents()) {
3972 if (IsAudioContent(&content)) {
3973 // If we already have an audio m= section, reject this extra one.
3974 if (*audio_index) {
3975 session_options->media_description_options.push_back(
3976 cricket::MediaDescriptionOptions(
3977 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003978 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003979 } else {
3980 session_options->media_description_options.push_back(
3981 cricket::MediaDescriptionOptions(
3982 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003983 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003984 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003985 }
3986 } else if (IsVideoContent(&content)) {
3987 // If we already have an video m= section, reject this extra one.
3988 if (*video_index) {
3989 session_options->media_description_options.push_back(
3990 cricket::MediaDescriptionOptions(
3991 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08003992 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07003993 } else {
3994 session_options->media_description_options.push_back(
3995 cricket::MediaDescriptionOptions(
3996 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08003997 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003998 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003999 }
4000 } else {
4001 RTC_DCHECK(IsDataContent(&content));
4002 // If we already have an data m= section, reject this extra one.
4003 if (*data_index) {
4004 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004005 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004006 } else {
4007 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004008 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004009 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004010 }
4011 }
htaa2a49d92016-03-04 02:51:39 -08004012 }
deadbeefab9b2d12015-10-14 11:33:11 -07004013}
4014
Steve Antonfa2260d2017-12-28 16:38:23 -08004015cricket::MediaDescriptionOptions
4016PeerConnection::GetMediaDescriptionOptionsForActiveData(
4017 const std::string& mid) const {
4018 // Direction for data sections is meaningless, but legacy endpoints might
4019 // expect sendrecv.
4020 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4021 RtpTransceiverDirection::kSendRecv,
4022 /*stopped=*/false);
4023 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4024 return options;
4025}
4026
4027cricket::MediaDescriptionOptions
4028PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4029 const std::string& mid) const {
4030 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4031 RtpTransceiverDirection::kInactive,
4032 /*stopped=*/true);
4033 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4034 return options;
4035}
4036
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004037absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004038 switch (data_channel_type_) {
4039 case cricket::DCT_RTP:
4040 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004041 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004042 }
4043 return rtp_data_channel_->content_name();
4044 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004045 return sctp_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004046 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004047 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004048 }
4049}
4050
Steve Anton4171afb2017-11-20 10:20:22 -08004051void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4052 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4053 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004054 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004055}
4056
Steve Anton4171afb2017-11-20 10:20:22 -08004057void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004058 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004059 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004060 cricket::MediaType media_type,
4061 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004062 RTC_DCHECK(!IsUnifiedPlan());
4063
Steve Anton4171afb2017-11-20 10:20:22 -08004064 std::vector<RtpSenderInfo>* current_senders =
4065 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004066
Steve Anton4171afb2017-11-20 10:20:22 -08004067 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004068 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004069 for (auto sender_it = current_senders->begin();
4070 sender_it != current_senders->end();
4071 /* incremented manually */) {
4072 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004073 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004074 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004075 std::string params_stream_id;
4076 if (params) {
4077 params_stream_id =
4078 (!params->first_stream_id().empty() ? params->first_stream_id()
4079 : kDefaultStreamId);
4080 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004081 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004082 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004083 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004084 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004085 sender_exists) {
4086 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004087 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004088 OnRemoteSenderRemoved(info, media_type);
4089 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004090 }
4091 }
4092
Steve Anton4171afb2017-11-20 10:20:22 -08004093 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004094 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004095 if (!params.has_ssrcs()) {
4096 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4097 // sender, this means it is coming from a Unified Plan endpoint,so we just
4098 // create a default.
4099 default_sender_needed = true;
4100 break;
4101 }
4102
Seth Hampson845e8782018-03-02 11:34:10 -08004103 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004104 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004105 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4106 // not supported in Plan B, we just take the first here and create the
4107 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004108 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004109 (!params.first_stream_id().empty() ? params.first_stream_id()
4110 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004111 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004112 uint32_t ssrc = params.first_ssrc();
4113
4114 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004115 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004116 if (!stream) {
4117 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004118 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004119 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004120 remote_streams_->AddStream(stream);
4121 new_streams->AddStream(stream);
4122 }
4123
Steve Anton4171afb2017-11-20 10:20:22 -08004124 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004125 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004126 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004127 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004128 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004129 }
4130 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004131
Steve Anton4171afb2017-11-20 10:20:22 -08004132 // Add default sender if necessary.
4133 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004134 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004135 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004136 if (!default_stream) {
4137 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004138 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004139 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004140 remote_streams_->AddStream(default_stream);
4141 new_streams->AddStream(default_stream);
4142 }
Steve Anton4171afb2017-11-20 10:20:22 -08004143 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4144 ? kDefaultAudioSenderId
4145 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004146 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004147 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004148 if (!default_sender_info) {
4149 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004150 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004151 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004152 }
4153 }
deadbeefab9b2d12015-10-14 11:33:11 -07004154}
4155
Steve Anton4171afb2017-11-20 10:20:22 -08004156void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4157 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004158 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4159 << " receiver for track_id=" << sender_info.sender_id
4160 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004161
Steve Anton3d954a62018-04-02 11:27:23 -07004162 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004163 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004164 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004165 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004166 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004167 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004168 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004169 }
4170}
4171
Steve Anton4171afb2017-11-20 10:20:22 -08004172void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4173 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004174 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4175 << " receiver for track_id=" << sender_info.sender_id
4176 << " and stream_id=" << sender_info.stream_id;
4177
Seth Hampson845e8782018-03-02 11:34:10 -08004178 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004179
Henrik Boström933d8b02017-10-10 10:05:16 -07004180 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004181 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004182 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4183 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004184 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004185 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004186 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004187 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004188 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004189 }
4190 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004191 // Stopping or destroying a VideoRtpReceiver will end the
4192 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004193 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004194 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004195 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004196 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004197 // There's no guarantee the track is still available, e.g. the track may
4198 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004199 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004200 }
4201 } else {
nisseede5da42017-01-12 05:15:36 -08004202 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004203 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004204 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004205 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004206 }
deadbeefab9b2d12015-10-14 11:33:11 -07004207}
4208
4209void PeerConnection::UpdateEndedRemoteMediaStreams() {
4210 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4211 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4212 MediaStreamInterface* stream = remote_streams_->at(i);
4213 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4214 streams_to_remove.push_back(stream);
4215 }
4216 }
4217
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004218 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004219 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004220 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004221 }
4222}
4223
Steve Anton4171afb2017-11-20 10:20:22 -08004224void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004225 const std::vector<cricket::StreamParams>& streams,
4226 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004227 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004228
Seth Hampson845e8782018-03-02 11:34:10 -08004229 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004230 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004231 for (auto sender_it = current_senders->begin();
4232 sender_it != current_senders->end();
4233 /* incremented manually */) {
4234 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004235 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004236 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4237 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004238 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004239 OnLocalSenderRemoved(info, media_type);
4240 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004241 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004242 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004243 }
4244 }
4245
Steve Anton4171afb2017-11-20 10:20:22 -08004246 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004247 for (const cricket::StreamParams& params : streams) {
4248 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004249 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004250 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004251 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004252 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004253 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004254 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004255 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004256 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004257 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004258 }
4259 }
4260}
4261
Steve Anton4171afb2017-11-20 10:20:22 -08004262void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4263 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004264 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004265 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004266 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004267 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4268 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004269 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004270 return;
4271 }
4272
deadbeeffac06552015-11-25 11:26:01 -08004273 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004274 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004275 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004276 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004277 }
deadbeeffac06552015-11-25 11:26:01 -08004278
Seth Hampson5b4f0752018-04-02 16:31:36 -07004279 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004280 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004281}
4282
Steve Anton4171afb2017-11-20 10:20:22 -08004283void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4284 cricket::MediaType media_type) {
4285 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004286 if (!sender) {
4287 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004288 // SessionDescriptions has been renegotiated.
4289 return;
4290 }
deadbeeffac06552015-11-25 11:26:01 -08004291
4292 // A sender has been removed from the SessionDescription but it's still
4293 // associated with the PeerConnection. This only occurs if the SDP doesn't
4294 // match with the calls to CreateSender, AddStream and RemoveStream.
4295 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004296 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004297 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004298 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004299 }
deadbeeffac06552015-11-25 11:26:01 -08004300
Steve Anton4171afb2017-11-20 10:20:22 -08004301 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004302}
4303
4304void PeerConnection::UpdateLocalRtpDataChannels(
4305 const cricket::StreamParamsVec& streams) {
4306 std::vector<std::string> existing_channels;
4307
4308 // Find new and active data channels.
4309 for (const cricket::StreamParams& params : streams) {
4310 // |it->sync_label| is actually the data channel label. The reason is that
4311 // we use the same naming of data channels as we do for
4312 // MediaStreams and Tracks.
4313 // For MediaStreams, the sync_label is the MediaStream label and the
4314 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004315 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004316 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004317 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004318 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004319 continue;
4320 }
4321 // Set the SSRC the data channel should use for sending.
4322 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4323 existing_channels.push_back(data_channel_it->first);
4324 }
4325
4326 UpdateClosingRtpDataChannels(existing_channels, true);
4327}
4328
4329void PeerConnection::UpdateRemoteRtpDataChannels(
4330 const cricket::StreamParamsVec& streams) {
4331 std::vector<std::string> existing_channels;
4332
4333 // Find new and active data channels.
4334 for (const cricket::StreamParams& params : streams) {
4335 // The data channel label is either the mslabel or the SSRC if the mslabel
4336 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004337 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004338 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004339 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004340 auto data_channel_it = rtp_data_channels_.find(label);
4341 if (data_channel_it == rtp_data_channels_.end()) {
4342 // This is a new data channel.
4343 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4344 } else {
4345 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4346 }
4347 existing_channels.push_back(label);
4348 }
4349
4350 UpdateClosingRtpDataChannels(existing_channels, false);
4351}
4352
4353void PeerConnection::UpdateClosingRtpDataChannels(
4354 const std::vector<std::string>& active_channels,
4355 bool is_local_update) {
4356 auto it = rtp_data_channels_.begin();
4357 while (it != rtp_data_channels_.end()) {
4358 DataChannel* data_channel = it->second;
4359 if (std::find(active_channels.begin(), active_channels.end(),
4360 data_channel->label()) != active_channels.end()) {
4361 ++it;
4362 continue;
4363 }
4364
4365 if (is_local_update) {
4366 data_channel->SetSendSsrc(0);
4367 } else {
4368 data_channel->RemotePeerRequestClose();
4369 }
4370
4371 if (data_channel->state() == DataChannel::kClosed) {
4372 rtp_data_channels_.erase(it);
4373 it = rtp_data_channels_.begin();
4374 } else {
4375 ++it;
4376 }
4377 }
4378}
4379
4380void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4381 uint32_t remote_ssrc) {
4382 rtc::scoped_refptr<DataChannel> channel(
4383 InternalCreateDataChannel(label, nullptr));
4384 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004385 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004386 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004387 return;
4388 }
4389 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004390 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4391 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004392 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004393}
4394
4395rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4396 const std::string& label,
4397 const InternalDataChannelInit* config) {
4398 if (IsClosed()) {
4399 return nullptr;
4400 }
Steve Anton75737c02017-11-06 10:37:17 -08004401 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004402 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004403 << "InternalCreateDataChannel: Data is not supported in this call.";
4404 return nullptr;
4405 }
4406 InternalDataChannelInit new_config =
4407 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08004408 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07004409 if (new_config.id < 0) {
4410 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004411 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004412 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004413 RTC_LOG(LS_ERROR)
4414 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004415 return nullptr;
4416 }
4417 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004418 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004419 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004420 return nullptr;
4421 }
4422 }
4423
Steve Anton75737c02017-11-06 10:37:17 -08004424 rtc::scoped_refptr<DataChannel> channel(
4425 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004426 if (!channel) {
4427 sid_allocator_.ReleaseSid(new_config.id);
4428 return nullptr;
4429 }
4430
4431 if (channel->data_channel_type() == cricket::DCT_RTP) {
4432 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004433 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4434 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004435 return nullptr;
4436 }
4437 rtp_data_channels_[channel->label()] = channel;
4438 } else {
4439 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
4440 sctp_data_channels_.push_back(channel);
4441 channel->SignalClosed.connect(this,
4442 &PeerConnection::OnSctpDataChannelClosed);
4443 }
4444
Steve Anton2d8609c2018-01-23 16:38:46 -08004445 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004446 return channel;
4447}
4448
4449bool PeerConnection::HasDataChannels() const {
4450 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4451}
4452
4453void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4454 for (const auto& channel : sctp_data_channels_) {
4455 if (channel->id() < 0) {
4456 int sid;
4457 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004458 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004459 continue;
4460 }
4461 channel->SetSctpSid(sid);
4462 }
4463 }
4464}
4465
4466void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004467 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004468 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4469 ++it) {
4470 if (it->get() == channel) {
4471 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004472 // After the closing procedure is done, it's safe to use this ID for
4473 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004474 sid_allocator_.ReleaseSid(channel->id());
4475 }
deadbeefbd292462015-12-14 18:15:29 -08004476 // Since this method is triggered by a signal from the DataChannel,
4477 // we can't free it directly here; we need to free it asynchronously.
4478 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004479 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004480 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4481 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004482 return;
4483 }
4484 }
4485}
4486
deadbeefab9b2d12015-10-14 11:33:11 -07004487void PeerConnection::OnDataChannelDestroyed() {
4488 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4489 // DataChannel may callback to us and try to modify the list.
4490 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4491 temp_rtp_dcs.swap(rtp_data_channels_);
4492 for (const auto& kv : temp_rtp_dcs) {
4493 kv.second->OnTransportChannelDestroyed();
4494 }
4495
4496 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4497 temp_sctp_dcs.swap(sctp_data_channels_);
4498 for (const auto& channel : temp_sctp_dcs) {
4499 channel->OnTransportChannelDestroyed();
4500 }
4501}
4502
4503void PeerConnection::OnDataChannelOpenMessage(
4504 const std::string& label,
4505 const InternalDataChannelInit& config) {
4506 rtc::scoped_refptr<DataChannel> channel(
4507 InternalCreateDataChannel(label, &config));
4508 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004509 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004510 return;
4511 }
4512
deadbeefa601f5c2016-06-06 14:27:39 -07004513 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4514 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004515 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004516 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004517}
4518
Steve Anton4171afb2017-11-20 10:20:22 -08004519rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4520PeerConnection::GetAudioTransceiver() const {
4521 // This method only works with Plan B SDP, where there is a single
4522 // audio/video transceiver.
4523 RTC_DCHECK(!IsUnifiedPlan());
4524 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004525 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004526 return transceiver;
4527 }
4528 }
4529 RTC_NOTREACHED();
4530 return nullptr;
4531}
4532
4533rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4534PeerConnection::GetVideoTransceiver() const {
4535 // This method only works with Plan B SDP, where there is a single
4536 // audio/video transceiver.
4537 RTC_DCHECK(!IsUnifiedPlan());
4538 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004539 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004540 return transceiver;
4541 }
4542 }
4543 RTC_NOTREACHED();
4544 return nullptr;
4545}
4546
4547// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4548// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004549bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004550 switch (type) {
4551 case cricket::MEDIA_TYPE_AUDIO:
4552 return !GetAudioTransceiver()->internal()->senders().empty();
4553 case cricket::MEDIA_TYPE_VIDEO:
4554 return !GetVideoTransceiver()->internal()->senders().empty();
4555 case cricket::MEDIA_TYPE_DATA:
4556 return false;
4557 }
4558 RTC_NOTREACHED();
4559 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004560}
4561
Steve Anton4171afb2017-11-20 10:20:22 -08004562rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4563PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4564 for (auto transceiver : transceivers_) {
4565 for (auto sender : transceiver->internal()->senders()) {
4566 if (sender->track() == track) {
4567 return sender;
4568 }
4569 }
4570 }
4571 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004572}
4573
Steve Anton4171afb2017-11-20 10:20:22 -08004574rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4575PeerConnection::FindSenderById(const std::string& sender_id) const {
4576 for (auto transceiver : transceivers_) {
4577 for (auto sender : transceiver->internal()->senders()) {
4578 if (sender->id() == sender_id) {
4579 return sender;
4580 }
4581 }
4582 }
4583 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004584}
4585
Steve Anton4171afb2017-11-20 10:20:22 -08004586rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4587PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4588 for (auto transceiver : transceivers_) {
4589 for (auto receiver : transceiver->internal()->receivers()) {
4590 if (receiver->id() == receiver_id) {
4591 return receiver;
4592 }
4593 }
4594 }
4595 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004596}
4597
Steve Anton4171afb2017-11-20 10:20:22 -08004598std::vector<PeerConnection::RtpSenderInfo>*
4599PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4600 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4601 media_type == cricket::MEDIA_TYPE_VIDEO);
4602 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4603 ? &remote_audio_sender_infos_
4604 : &remote_video_sender_infos_;
4605}
4606
4607std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004608 cricket::MediaType media_type) {
4609 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4610 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004611 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4612 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004613}
4614
Steve Anton4171afb2017-11-20 10:20:22 -08004615const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4616 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004617 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004618 const std::string sender_id) const {
4619 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004620 if (sender_info.stream_id == stream_id &&
4621 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004622 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004623 }
4624 }
4625 return nullptr;
4626}
4627
4628DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4629 for (const auto& channel : sctp_data_channels_) {
4630 if (channel->id() == sid) {
4631 return channel;
4632 }
4633 }
4634 return nullptr;
4635}
4636
deadbeef91dd5672016-05-18 16:55:30 -07004637bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004638 const cricket::ServerAddresses& stun_servers,
4639 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004640 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004641 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004642 // To handle both internal and externally created port allocator, we will
4643 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004644 port_allocator_flags_ = port_allocator_->flags();
4645 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4646 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4647 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004648 // If the disable-IPv6 flag was specified, we'll not override it
4649 // by experiment.
4650 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004651 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004652 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4653 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004654 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004655 }
4656
zhihuangb09b3f92017-03-07 14:40:51 -08004657 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004658 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004659 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004660 }
4661
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004662 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004663 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004664 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004665 }
4666
honghaiz60347052016-05-31 18:29:12 -07004667 if (configuration.candidate_network_policy ==
4668 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004669 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004670 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004671 }
4672
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004673 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004674 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004675 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4676 }
4677
Qingsi Wanga2d60672018-04-11 16:57:45 -07004678 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004679 // No step delay is used while allocating ports.
4680 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4681 port_allocator_->set_candidate_filter(
4682 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004683 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004684
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004685 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004686 for (auto& turn_server : turn_servers_copy) {
4687 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004688 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004689 // Call this last since it may create pooled allocator sessions using the
4690 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004691 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004692 stun_servers, std::move(turn_servers_copy),
4693 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4694 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004695 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004696 return true;
4697}
4698
deadbeef91dd5672016-05-18 16:55:30 -07004699bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004700 const cricket::ServerAddresses& stun_servers,
4701 const std::vector<cricket::RelayServerConfig>& turn_servers,
4702 IceTransportsType type,
4703 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004704 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004705 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004706 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004707 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004708 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004709 // According to JSEP, after setLocalDescription, changing the candidate pool
4710 // size is not allowed, and changing the set of ICE servers will not result
4711 // in new candidates being gathered.
4712 if (local_description()) {
4713 port_allocator_->FreezeCandidatePool();
4714 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004715 // Add the custom tls turn servers if they exist.
4716 auto turn_servers_copy = turn_servers;
4717 for (auto& turn_server : turn_servers_copy) {
4718 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4719 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004720 // Call this last since it may create pooled allocator sessions using the
4721 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004722 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004723 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4724 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004725}
4726
Steve Antonba818672017-11-06 10:21:57 -08004727cricket::ChannelManager* PeerConnection::channel_manager() const {
4728 return factory_->channel_manager();
4729}
4730
Elad Alon99c3fe52017-10-13 16:29:40 +02004731bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004732 std::unique_ptr<RtcEventLogOutput> output,
4733 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004734 if (!event_log_) {
4735 return false;
4736 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004737 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004738}
4739
4740void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004741 if (event_log_) {
4742 event_log_->StopLogging();
4743 }
ivoc14d5dbe2016-07-04 07:06:55 -07004744}
nisseeaabdf62017-05-05 02:23:02 -07004745
Steve Anton75737c02017-11-06 10:37:17 -08004746cricket::BaseChannel* PeerConnection::GetChannel(
4747 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004748 for (auto transceiver : transceivers_) {
4749 cricket::BaseChannel* channel = transceiver->internal()->channel();
4750 if (channel && channel->content_name() == content_name) {
4751 return channel;
4752 }
Steve Anton75737c02017-11-06 10:37:17 -08004753 }
4754 if (rtp_data_channel() &&
4755 rtp_data_channel()->content_name() == content_name) {
4756 return rtp_data_channel();
4757 }
4758 return nullptr;
4759}
4760
4761bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
4762 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004763 RTC_LOG(LS_INFO)
4764 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004765 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004766 return false;
4767 }
4768 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004769 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004770 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004771 return false;
4772 }
4773
Zhi Huange830e682018-03-30 10:48:35 -07004774 auto dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4775 if (dtls_role) {
4776 *role = *dtls_role;
4777 return true;
4778 }
4779 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004780}
4781
4782bool PeerConnection::GetSslRole(const std::string& content_name,
4783 rtc::SSLRole* role) {
4784 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004785 RTC_LOG(LS_INFO)
4786 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004787 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08004788 return false;
4789 }
4790
Zhi Huange830e682018-03-30 10:48:35 -07004791 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
4792 if (dtls_role) {
4793 *role = *dtls_role;
4794 return true;
4795 }
4796 return false;
Steve Anton75737c02017-11-06 10:37:17 -08004797}
4798
Steve Antonf8470812017-12-04 10:46:21 -08004799void PeerConnection::SetSessionError(SessionError error,
4800 const std::string& error_desc) {
4801 RTC_DCHECK_RUN_ON(signaling_thread());
4802 if (error != session_error_) {
4803 session_error_ = error;
4804 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08004805 }
4806}
4807
Zhi Huange830e682018-03-30 10:48:35 -07004808RTCError PeerConnection::UpdateSessionState(
4809 SdpType type,
4810 cricket::ContentSource source,
4811 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08004812 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004813
4814 // If there's already a pending error then no state transition should happen.
4815 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08004816 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004817
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004818 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08004819 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08004820 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004821 }
4822
4823 // Update the signaling state according to the specified state machine (see
4824 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08004825 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004826 ChangeSignalingState(source == cricket::CS_LOCAL
4827 ? PeerConnectionInterface::kHaveLocalOffer
4828 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08004829 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004830 ChangeSignalingState(source == cricket::CS_LOCAL
4831 ? PeerConnectionInterface::kHaveLocalPrAnswer
4832 : PeerConnectionInterface::kHaveRemotePrAnswer);
4833 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004834 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004835 ChangeSignalingState(PeerConnectionInterface::kStable);
4836 }
4837
4838 // Update internal objects according to the session description's media
4839 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07004840 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004841 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08004842 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08004843 }
4844
Steve Anton8a006912017-12-04 15:25:56 -08004845 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004846}
4847
Steve Anton8a006912017-12-04 15:25:56 -08004848RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08004849 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08004850 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08004851 const SessionDescriptionInterface* sdesc =
4852 (source == cricket::CS_LOCAL ? local_description()
4853 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08004854 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08004855
4856 // Push down the new SDP media section for each audio/video transceiver.
4857 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08004858 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08004859 FindMediaSectionForTransceiver(transceiver, sdesc);
4860 cricket::BaseChannel* channel = transceiver->internal()->channel();
4861 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08004862 continue;
4863 }
4864 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004865 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004866 if (!content_desc) {
4867 continue;
4868 }
4869 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02004870 bool success = (source == cricket::CS_LOCAL)
4871 ? channel->SetLocalContent(content_desc, type, &error)
4872 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004873 if (!success) {
4874 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
4875 }
4876 }
4877
4878 // If using the RtpDataChannel, push down the new SDP section for it too.
4879 if (rtp_data_channel_) {
4880 const ContentInfo* data_content =
4881 cricket::GetFirstDataContent(sdesc->description());
4882 if (data_content && !data_content->rejected) {
4883 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08004884 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08004885 if (data_desc) {
4886 std::string error;
4887 bool success =
4888 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08004889 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02004890 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08004891 if (!success) {
4892 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4893 std::move(error));
4894 }
Steve Anton75737c02017-11-06 10:37:17 -08004895 }
4896 }
4897 }
Steve Antoned10bd92017-12-05 10:52:59 -08004898
Steve Anton75737c02017-11-06 10:37:17 -08004899 // Need complete offer/answer with an SCTP m= section before starting SCTP,
4900 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
4901 if (sctp_transport_ && local_description() && remote_description() &&
4902 cricket::GetFirstDataContent(local_description()->description()) &&
4903 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004904 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08004905 RTC_FROM_HERE,
4906 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08004907 if (!success) {
4908 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4909 "Failed to push down SCTP parameters.");
4910 }
Steve Anton75737c02017-11-06 10:37:17 -08004911 }
Steve Antoned10bd92017-12-05 10:52:59 -08004912
Steve Anton8a006912017-12-04 15:25:56 -08004913 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004914}
4915
4916bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
4917 RTC_DCHECK(network_thread()->IsCurrent());
4918 RTC_DCHECK(local_description());
4919 RTC_DCHECK(remote_description());
4920 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
4921 // When we support "max-message-size", that would also be pushed down here.
4922 return sctp_transport_->Start(
4923 GetSctpPort(local_description()->description()),
4924 GetSctpPort(remote_description()->description()));
4925}
4926
Steve Anton8a006912017-12-04 15:25:56 -08004927RTCError PeerConnection::PushdownTransportDescription(
4928 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08004929 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08004930 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004931
Zhi Huange830e682018-03-30 10:48:35 -07004932 if (source == cricket::CS_LOCAL) {
4933 const SessionDescriptionInterface* sdesc = local_description();
4934 RTC_DCHECK(sdesc);
4935 return transport_controller_->SetLocalDescription(type,
4936 sdesc->description());
4937 } else {
4938 const SessionDescriptionInterface* sdesc = remote_description();
4939 RTC_DCHECK(sdesc);
4940 return transport_controller_->SetRemoteDescription(type,
4941 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08004942 }
Steve Anton75737c02017-11-06 10:37:17 -08004943}
4944
4945bool PeerConnection::GetTransportDescription(
4946 const SessionDescription* description,
4947 const std::string& content_name,
4948 cricket::TransportDescription* tdesc) {
4949 if (!description || !tdesc) {
4950 return false;
4951 }
4952 const TransportInfo* transport_info =
4953 description->GetTransportInfoByName(content_name);
4954 if (!transport_info) {
4955 return false;
4956 }
4957 *tdesc = transport_info->description;
4958 return true;
4959}
4960
Steve Anton75737c02017-11-06 10:37:17 -08004961cricket::IceConfig PeerConnection::ParseIceConfig(
4962 const PeerConnectionInterface::RTCConfiguration& config) const {
4963 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08004964 switch (config.continual_gathering_policy) {
4965 case PeerConnectionInterface::GATHER_ONCE:
4966 gathering_policy = cricket::GATHER_ONCE;
4967 break;
4968 case PeerConnectionInterface::GATHER_CONTINUALLY:
4969 gathering_policy = cricket::GATHER_CONTINUALLY;
4970 break;
4971 default:
4972 RTC_NOTREACHED();
4973 gathering_policy = cricket::GATHER_ONCE;
4974 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004975
Steve Anton75737c02017-11-06 10:37:17 -08004976 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07004977 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
4978 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08004979 ice_config.prioritize_most_likely_candidate_pairs =
4980 config.prioritize_most_likely_ice_candidate_pairs;
4981 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07004982 RTCConfigurationToIceConfigOptionalInt(
4983 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08004984 ice_config.continual_gathering_policy = gathering_policy;
4985 ice_config.presume_writable_when_fully_relayed =
4986 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08004987 ice_config.ice_check_interval_strong_connectivity =
4988 config.ice_check_interval_strong_connectivity;
4989 ice_config.ice_check_interval_weak_connectivity =
4990 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08004991 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004992 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08004993 ice_config.regather_all_networks_interval_range =
4994 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08004995 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08004996 return ice_config;
4997}
4998
Steve Anton75737c02017-11-06 10:37:17 -08004999bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5000 std::string* track_id) {
5001 if (!local_description()) {
5002 return false;
5003 }
5004 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5005 track_id);
5006}
5007
5008bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5009 std::string* track_id) {
5010 if (!remote_description()) {
5011 return false;
5012 }
5013 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5014 track_id);
5015}
5016
5017bool PeerConnection::SendData(const cricket::SendDataParams& params,
5018 const rtc::CopyOnWriteBuffer& payload,
5019 cricket::SendDataResult* result) {
5020 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005021 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005022 "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005023 return false;
5024 }
5025 return rtp_data_channel_
5026 ? rtp_data_channel_->SendData(params, payload, result)
5027 : network_thread()->Invoke<bool>(
5028 RTC_FROM_HERE,
5029 Bind(&cricket::SctpTransportInternal::SendData,
5030 sctp_transport_.get(), params, payload, result));
5031}
5032
5033bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
5034 if (!rtp_data_channel_ && !sctp_transport_) {
5035 // Don't log an error here, because DataChannels are expected to call
5036 // ConnectDataChannel in this state. It's the only way to initially tell
5037 // whether or not the underlying transport is ready.
5038 return false;
5039 }
5040 if (rtp_data_channel_) {
5041 rtp_data_channel_->SignalReadyToSendData.connect(
5042 webrtc_data_channel, &DataChannel::OnChannelReady);
5043 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5044 &DataChannel::OnDataReceived);
5045 } else {
5046 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5047 &DataChannel::OnChannelReady);
5048 SignalSctpDataReceived.connect(webrtc_data_channel,
5049 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005050 SignalSctpClosingProcedureStartedRemotely.connect(
5051 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5052 SignalSctpClosingProcedureComplete.connect(
5053 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005054 }
5055 return true;
5056}
5057
5058void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
5059 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005060 RTC_LOG(LS_ERROR)
5061 << "DisconnectDataChannel called when rtp_data_channel_ and "
5062 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005063 return;
5064 }
5065 if (rtp_data_channel_) {
5066 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5067 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5068 } else {
5069 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5070 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005071 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5072 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005073 }
5074}
5075
5076void PeerConnection::AddSctpDataStream(int sid) {
5077 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005078 RTC_LOG(LS_ERROR)
5079 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005080 return;
5081 }
5082 network_thread()->Invoke<void>(
5083 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5084 sctp_transport_.get(), sid));
5085}
5086
5087void PeerConnection::RemoveSctpDataStream(int sid) {
5088 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005089 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005090 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005091 return;
5092 }
5093 network_thread()->Invoke<void>(
5094 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5095 sctp_transport_.get(), sid));
5096}
5097
5098bool PeerConnection::ReadyToSendData() const {
5099 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
5100 sctp_ready_to_send_data_;
5101}
5102
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005103absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005104 if (sctp_mid_ && transport_controller_) {
5105 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5106 if (dtls_transport) {
5107 return dtls_transport->transport_name();
5108 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005109 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005110 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005111 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005112}
5113
Qingsi Wang72a43a12018-02-20 16:03:18 -08005114cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5115 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005116 network_thread()->Invoke<void>(
5117 RTC_FROM_HERE,
5118 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5119 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005120 return candidate_states_list;
5121}
5122
Steve Anton5dfde182018-02-06 10:34:40 -08005123std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5124 const {
5125 std::map<std::string, std::string> transport_names_by_mid;
5126 for (auto transceiver : transceivers_) {
5127 cricket::BaseChannel* channel = transceiver->internal()->channel();
5128 if (channel) {
5129 transport_names_by_mid[channel->content_name()] =
5130 channel->transport_name();
5131 }
Steve Anton75737c02017-11-06 10:37:17 -08005132 }
Steve Anton5dfde182018-02-06 10:34:40 -08005133 if (rtp_data_channel_) {
5134 transport_names_by_mid[rtp_data_channel_->content_name()] =
5135 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005136 }
5137 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005138 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005139 RTC_DCHECK(transport_name);
5140 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005141 }
Steve Anton5dfde182018-02-06 10:34:40 -08005142 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005143}
5144
Steve Anton5dfde182018-02-06 10:34:40 -08005145std::map<std::string, cricket::TransportStats>
5146PeerConnection::GetTransportStatsByNames(
5147 const std::set<std::string>& transport_names) {
5148 if (!network_thread()->IsCurrent()) {
5149 return network_thread()
5150 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5151 RTC_FROM_HERE,
5152 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005153 }
Steve Anton5dfde182018-02-06 10:34:40 -08005154 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5155 for (const std::string& transport_name : transport_names) {
5156 cricket::TransportStats transport_stats;
5157 bool success =
5158 transport_controller_->GetStats(transport_name, &transport_stats);
5159 if (success) {
5160 transport_stats_by_name[transport_name] = std::move(transport_stats);
5161 } else {
5162 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5163 << transport_name;
5164 }
5165 }
5166 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005167}
5168
5169bool PeerConnection::GetLocalCertificate(
5170 const std::string& transport_name,
5171 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005172 if (!certificate) {
5173 return false;
5174 }
5175 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5176 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005177}
5178
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005179std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005180 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005181 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005182}
5183
5184cricket::DataChannelType PeerConnection::data_channel_type() const {
5185 return data_channel_type_;
5186}
5187
5188bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5189 return pending_ice_restarts_.find(content_name) !=
5190 pending_ice_restarts_.end();
5191}
5192
Steve Anton75737c02017-11-06 10:37:17 -08005193bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5194 return transport_controller_->NeedsIceRestart(content_name);
5195}
5196
5197void PeerConnection::OnCertificateReady(
5198 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5199 transport_controller_->SetLocalCertificate(certificate);
5200}
5201
5202void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005203 SetSessionError(SessionError::kTransport,
5204 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005205}
5206
5207void PeerConnection::OnTransportControllerConnectionState(
5208 cricket::IceConnectionState state) {
5209 switch (state) {
5210 case cricket::kIceConnectionConnecting:
5211 // If the current state is Connected or Completed, then there were
5212 // writable channels but now there are not, so the next state must
5213 // be Disconnected.
5214 // kIceConnectionConnecting is currently used as the default,
5215 // un-connected state by the TransportController, so its only use is
5216 // detecting disconnections.
5217 if (ice_connection_state_ ==
5218 PeerConnectionInterface::kIceConnectionConnected ||
5219 ice_connection_state_ ==
5220 PeerConnectionInterface::kIceConnectionCompleted) {
5221 SetIceConnectionState(
5222 PeerConnectionInterface::kIceConnectionDisconnected);
5223 }
5224 break;
5225 case cricket::kIceConnectionFailed:
5226 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5227 break;
5228 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005229 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005230 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005231 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005232 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005233 break;
5234 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005235 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005236 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005237 if (ice_connection_state_ !=
5238 PeerConnectionInterface::kIceConnectionConnected) {
5239 // If jumping directly from "checking" to "connected",
5240 // signal "connected" first.
5241 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5242 }
5243 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005244 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005245 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005246 break;
5247 default:
5248 RTC_NOTREACHED();
5249 }
5250}
5251
5252void PeerConnection::OnTransportControllerCandidatesGathered(
5253 const std::string& transport_name,
5254 const cricket::Candidates& candidates) {
5255 RTC_DCHECK(signaling_thread()->IsCurrent());
5256 int sdp_mline_index;
5257 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005258 RTC_LOG(LS_ERROR)
5259 << "OnTransportControllerCandidatesGathered: content name "
5260 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005261 return;
5262 }
5263
5264 for (cricket::Candidates::const_iterator citer = candidates.begin();
5265 citer != candidates.end(); ++citer) {
5266 // Use transport_name as the candidate media id.
5267 std::unique_ptr<JsepIceCandidate> candidate(
5268 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5269 if (local_description()) {
5270 mutable_local_description()->AddCandidate(candidate.get());
5271 }
5272 OnIceCandidate(std::move(candidate));
5273 }
5274}
5275
5276void PeerConnection::OnTransportControllerCandidatesRemoved(
5277 const std::vector<cricket::Candidate>& candidates) {
5278 RTC_DCHECK(signaling_thread()->IsCurrent());
5279 // Sanity check.
5280 for (const cricket::Candidate& candidate : candidates) {
5281 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005282 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005283 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005284 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005285 return;
5286 }
5287 }
5288
5289 if (local_description()) {
5290 mutable_local_description()->RemoveCandidates(candidates);
5291 }
5292 OnIceCandidatesRemoved(candidates);
5293}
5294
5295void PeerConnection::OnTransportControllerDtlsHandshakeError(
5296 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005297 RTC_HISTOGRAM_ENUMERATION(
5298 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5299 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005300}
5301
Steve Antoned10bd92017-12-05 10:52:59 -08005302void PeerConnection::EnableSending() {
5303 for (auto transceiver : transceivers_) {
5304 cricket::BaseChannel* channel = transceiver->internal()->channel();
5305 if (channel && !channel->enabled()) {
5306 channel->Enable(true);
5307 }
Steve Anton75737c02017-11-06 10:37:17 -08005308 }
5309
Steve Anton4171afb2017-11-20 10:20:22 -08005310 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005311 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005312 }
Steve Anton75737c02017-11-06 10:37:17 -08005313}
5314
5315// Returns the media index for a local ice candidate given the content name.
5316bool PeerConnection::GetLocalCandidateMediaIndex(
5317 const std::string& content_name,
5318 int* sdp_mline_index) {
5319 if (!local_description() || !sdp_mline_index) {
5320 return false;
5321 }
5322
5323 bool content_found = false;
5324 const ContentInfos& contents = local_description()->description()->contents();
5325 for (size_t index = 0; index < contents.size(); ++index) {
5326 if (contents[index].name == content_name) {
5327 *sdp_mline_index = static_cast<int>(index);
5328 content_found = true;
5329 break;
5330 }
5331 }
5332 return content_found;
5333}
5334
5335bool PeerConnection::UseCandidatesInSessionDescription(
5336 const SessionDescriptionInterface* remote_desc) {
5337 if (!remote_desc) {
5338 return true;
5339 }
5340 bool ret = true;
5341
5342 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5343 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5344 for (size_t n = 0; n < candidates->count(); ++n) {
5345 const IceCandidateInterface* candidate = candidates->at(n);
5346 bool valid = false;
5347 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5348 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005349 RTC_LOG(LS_INFO)
5350 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005351 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005352 }
5353 continue;
5354 }
5355 ret = UseCandidate(candidate);
5356 if (!ret) {
5357 break;
5358 }
5359 }
5360 }
5361 return ret;
5362}
5363
5364bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5365 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5366 size_t remote_content_size =
5367 remote_description()->description()->contents().size();
5368 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005369 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005370 return false;
5371 }
5372
5373 cricket::ContentInfo content =
5374 remote_description()->description()->contents()[mediacontent_index];
5375 std::vector<cricket::Candidate> candidates;
5376 candidates.push_back(candidate->candidate());
5377 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005378 RTCError error =
5379 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005380 if (error.ok()) {
5381 // Candidates successfully submitted for checking.
5382 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5383 ice_connection_state_ ==
5384 PeerConnectionInterface::kIceConnectionDisconnected) {
5385 // If state is New, then the session has just gotten its first remote ICE
5386 // candidates, so go to Checking.
5387 // If state is Disconnected, the session is re-using old candidates or
5388 // receiving additional ones, so go to Checking.
5389 // If state is Connected, stay Connected.
5390 // TODO(bemasc): If state is Connected, and the new candidates are for a
5391 // newly added transport, then the state actually _should_ move to
5392 // checking. Add a way to distinguish that case.
5393 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5394 }
5395 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005396 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005397 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005398 }
5399 return true;
5400}
5401
5402void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005403 // Destroy video channel first since it may have a pointer to the
5404 // voice channel.
5405 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005406 if (!video_info || video_info->rejected) {
5407 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005408 }
5409
Steve Anton6fec8802017-12-04 10:37:29 -08005410 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5411 if (!audio_info || audio_info->rejected) {
5412 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005413 }
5414
5415 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5416 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005417 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005418 }
5419}
5420
Steve Antondcc3c022017-12-22 16:02:54 -08005421RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5422 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005423 const cricket::ContentGroup* bundle_group = nullptr;
5424 if (configuration_.bundle_policy ==
5425 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005426 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005427 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5429 "max-bundle configured but session description "
5430 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005431 }
5432 }
Steve Antondcc3c022017-12-22 16:02:54 -08005433 return std::move(bundle_group);
5434}
5435
5436RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005437 // Creating the media channels. Transports should already have been created
5438 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005439 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005440 if (voice && !voice->rejected &&
5441 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005442 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005443 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005444 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5445 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005446 }
5447 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5448 }
5449
Steve Antondcc3c022017-12-22 16:02:54 -08005450 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005451 if (video && !video->rejected &&
5452 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005453 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005454 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005455 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5456 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005457 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005458 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005459 }
5460
Steve Antondcc3c022017-12-22 16:02:54 -08005461 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005462 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
5463 !rtp_data_channel_ && !sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005464 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005465 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5466 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005467 }
5468 }
5469
Steve Anton8a006912017-12-04 15:25:56 -08005470 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005471}
5472
Steve Anton4171afb2017-11-20 10:20:22 -08005473// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005474cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005475 const std::string& mid) {
5476 RtpTransportInternal* rtp_transport =
5477 transport_controller_->GetRtpTransport(mid);
5478 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005479 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005480 call_.get(), configuration_.media_config, rtp_transport,
5481 signaling_thread(), mid, SrtpRequired(),
5482 factory_->options().crypto_options, audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005483 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005484 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005485 }
Steve Anton75737c02017-11-06 10:37:17 -08005486 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5487 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005488 voice_channel->SignalSentPacket.connect(this,
5489 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005490 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005491
Steve Antoneda6ccd2017-12-04 10:21:55 -08005492 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005493}
5494
Steve Anton4171afb2017-11-20 10:20:22 -08005495// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005496cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005497 const std::string& mid) {
5498 RtpTransportInternal* rtp_transport =
5499 transport_controller_->GetRtpTransport(mid);
5500 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005501 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005502 call_.get(), configuration_.media_config, rtp_transport,
5503 signaling_thread(), mid, SrtpRequired(),
5504 factory_->options().crypto_options, video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005505 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005506 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005507 }
Steve Anton75737c02017-11-06 10:37:17 -08005508 video_channel->SignalDtlsSrtpSetupFailure.connect(
5509 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005510 video_channel->SignalSentPacket.connect(this,
5511 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005512 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005513
Steve Antoneda6ccd2017-12-04 10:21:55 -08005514 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005515}
5516
Zhi Huange830e682018-03-30 10:48:35 -07005517bool PeerConnection::CreateDataChannel(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005518 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
5519 if (sctp) {
5520 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005521 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08005522 << "Trying to create SCTP transport, but didn't compile with "
5523 "SCTP support (HAVE_SCTP)";
5524 return false;
5525 }
5526 if (!network_thread()->Invoke<bool>(
Zhi Huange830e682018-03-30 10:48:35 -07005527 RTC_FROM_HERE,
5528 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
Steve Anton75737c02017-11-06 10:37:17 -08005529 return false;
5530 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005531 for (const auto& channel : sctp_data_channels_) {
5532 channel->OnTransportChannelCreated();
5533 }
Steve Anton75737c02017-11-06 10:37:17 -08005534 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005535 RtpTransportInternal* rtp_transport =
5536 transport_controller_->GetRtpTransport(mid);
5537 RTC_DCHECK(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005538 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005539 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5540 SrtpRequired(), factory_->options().crypto_options);
Steve Anton75737c02017-11-06 10:37:17 -08005541 if (!rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005542 return false;
5543 }
Steve Anton75737c02017-11-06 10:37:17 -08005544 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5545 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5546 rtp_data_channel_->SignalSentPacket.connect(
5547 this, &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005548 rtp_data_channel_->SetRtpTransport(rtp_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005549 }
5550
Steve Anton75737c02017-11-06 10:37:17 -08005551 return true;
5552}
5553
5554Call::Stats PeerConnection::GetCallStats() {
5555 if (!worker_thread()->IsCurrent()) {
5556 return worker_thread()->Invoke<Call::Stats>(
5557 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5558 }
5559 if (call_) {
5560 return call_->GetStats();
5561 } else {
5562 return Call::Stats();
5563 }
5564}
5565
Zhi Huange830e682018-03-30 10:48:35 -07005566bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005567 RTC_DCHECK(network_thread()->IsCurrent());
5568 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005569 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005570 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005571 RTC_DCHECK(dtls_transport);
5572 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005573 RTC_DCHECK(sctp_transport_);
5574 sctp_invoker_.reset(new rtc::AsyncInvoker());
5575 sctp_transport_->SignalReadyToSendData.connect(
5576 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5577 sctp_transport_->SignalDataReceived.connect(
5578 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005579 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5580 // another thread. Would be nice if there was a helper class similar to
5581 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5582 // code.
5583 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5584 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5585 sctp_transport_->SignalClosingProcedureComplete.connect(
5586 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005587 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005588 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005589 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005590}
5591
5592void PeerConnection::DestroySctpTransport_n() {
5593 RTC_DCHECK(network_thread()->IsCurrent());
5594 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005595 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005596 sctp_invoker_.reset(nullptr);
5597 sctp_ready_to_send_data_ = false;
5598}
5599
5600void PeerConnection::OnSctpTransportReadyToSendData_n() {
5601 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5602 RTC_DCHECK(network_thread()->IsCurrent());
5603 // Note: Cannot use rtc::Bind here because it will grab a reference to
5604 // PeerConnection and potentially cause PeerConnection to live longer than
5605 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5606 // be destroyed before PeerConnection is destroyed, and at that point all
5607 // pending tasks will be cleared.
5608 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5609 OnSctpTransportReadyToSendData_s(true);
5610 });
5611}
5612
5613void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5614 RTC_DCHECK(signaling_thread()->IsCurrent());
5615 sctp_ready_to_send_data_ = ready;
5616 SignalSctpReadyToSendData(ready);
5617}
5618
5619void PeerConnection::OnSctpTransportDataReceived_n(
5620 const cricket::ReceiveDataParams& params,
5621 const rtc::CopyOnWriteBuffer& payload) {
5622 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5623 RTC_DCHECK(network_thread()->IsCurrent());
5624 // Note: Cannot use rtc::Bind here because it will grab a reference to
5625 // PeerConnection and potentially cause PeerConnection to live longer than
5626 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5627 // be destroyed before PeerConnection is destroyed, and at that point all
5628 // pending tasks will be cleared.
5629 sctp_invoker_->AsyncInvoke<void>(
5630 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5631 OnSctpTransportDataReceived_s(params, payload);
5632 });
5633}
5634
5635void PeerConnection::OnSctpTransportDataReceived_s(
5636 const cricket::ReceiveDataParams& params,
5637 const rtc::CopyOnWriteBuffer& payload) {
5638 RTC_DCHECK(signaling_thread()->IsCurrent());
5639 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
5640 // Received OPEN message; parse and signal that a new data channel should
5641 // be created.
5642 std::string label;
5643 InternalDataChannelInit config;
5644 config.id = params.ssrc;
5645 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005646 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
5647 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08005648 return;
5649 }
5650 config.open_handshake_role = InternalDataChannelInit::kAcker;
5651 OnDataChannelOpenMessage(label, config);
5652 } else {
5653 // Otherwise just forward the signal.
5654 SignalSctpDataReceived(params, payload);
5655 }
5656}
5657
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005658void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005659 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5660 RTC_DCHECK(network_thread()->IsCurrent());
5661 sctp_invoker_->AsyncInvoke<void>(
5662 RTC_FROM_HERE, signaling_thread(),
5663 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005664 &SignalSctpClosingProcedureStartedRemotely, sid));
5665}
5666
5667void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5668 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5669 RTC_DCHECK(network_thread()->IsCurrent());
5670 sctp_invoker_->AsyncInvoke<void>(
5671 RTC_FROM_HERE, signaling_thread(),
5672 rtc::Bind(&sigslot::signal1<int>::operator(),
5673 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005674}
5675
5676// Returns false if bundle is enabled and rtcp_mux is disabled.
5677bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
5678 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
5679 if (!bundle_enabled)
5680 return true;
5681
5682 const cricket::ContentGroup* bundle_group =
5683 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
5684 RTC_DCHECK(bundle_group != NULL);
5685
5686 const cricket::ContentInfos& contents = desc->contents();
5687 for (cricket::ContentInfos::const_iterator citer = contents.begin();
5688 citer != contents.end(); ++citer) {
5689 const cricket::ContentInfo* content = (&*citer);
5690 RTC_DCHECK(content != NULL);
5691 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08005692 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08005693 if (!HasRtcpMuxEnabled(content))
5694 return false;
5695 }
5696 }
5697 // RTCP-MUX is enabled in all the contents.
5698 return true;
5699}
5700
5701bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08005702 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08005703}
5704
Steve Anton8a006912017-12-04 15:25:56 -08005705RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08005706 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08005707 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08005708 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08005709 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08005710 }
5711
5712 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08005713 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08005714 }
5715
Steve Anton3828c062017-12-06 10:34:51 -08005716 SdpType type = sdesc->GetType();
5717 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
5718 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08005719 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01005720 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08005721 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08005722 }
5723
5724 // Verify crypto settings.
5725 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08005726 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
5727 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005728 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08005729 if (!crypto_error.ok()) {
5730 return crypto_error;
5731 }
Steve Anton75737c02017-11-06 10:37:17 -08005732 }
5733
5734 // Verify ice-ufrag and ice-pwd.
5735 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005736 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5737 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08005738 }
5739
5740 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005741 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5742 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08005743 }
5744
5745 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
5746 // m-lines that do not rtcp-mux enabled.
5747
5748 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08005749 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005750 // With an answer we want to compare the new answer session description with
5751 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08005752 const cricket::SessionDescription* offer_desc =
5753 (source == cricket::CS_LOCAL) ? remote_description()->description()
5754 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005755 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
5756 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
5757 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005758 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5759 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
5761 } else {
Steve Anton75737c02017-11-06 10:37:17 -08005762 // The re-offers should respect the order of m= sections in current
5763 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005764 // With a re-offer, either the current local or current remote descriptions
5765 // could be the most up to date, so we would like to check against both of
5766 // them if they exist. It could be the case that one of them has a 0 port
5767 // for a media section, but the other does not. This is important to check
5768 // against in the case that we are recycling an m= section.
5769 const cricket::SessionDescription* current_desc = nullptr;
5770 const cricket::SessionDescription* secondary_current_desc = nullptr;
5771 if (local_description()) {
5772 current_desc = local_description()->description();
5773 if (remote_description()) {
5774 secondary_current_desc = remote_description()->description();
5775 }
5776 } else if (remote_description()) {
5777 current_desc = remote_description()->description();
5778 }
Steve Anton75737c02017-11-06 10:37:17 -08005779 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08005780 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
5781 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08005782 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5783 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08005784 }
5785 }
5786
Steve Antonba42e992018-04-09 14:10:01 -07005787 if (IsUnifiedPlan()) {
5788 // Ensure that each audio and video media section has at most one
5789 // "StreamParams". This will return an error if receiving a session
5790 // description from a "Plan B" endpoint which adds multiple tracks of the
5791 // same type. With Unified Plan, there can only be at most one track per
5792 // media section.
5793 for (const ContentInfo& content : sdesc->description()->contents()) {
5794 const MediaContentDescription& desc = *content.description;
5795 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
5796 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
5797 desc.streams().size() > 1u) {
5798 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5799 "Media section has more than one track specified "
5800 "with a=ssrc lines which is not supported with "
5801 "Unified Plan.");
5802 }
5803 }
5804 }
5805
Steve Anton8a006912017-12-04 15:25:56 -08005806 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005807}
5808
Steve Anton3828c062017-12-06 10:34:51 -08005809bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005810 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005811 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005812 return (state == PeerConnectionInterface::kStable) ||
5813 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08005814 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005815 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005816 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
5817 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
5818 }
5819}
5820
Steve Anton3828c062017-12-06 10:34:51 -08005821bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08005822 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08005823 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08005824 return (state == PeerConnectionInterface::kStable) ||
5825 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08005826 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005827 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08005828 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
5829 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
5830 }
5831}
5832
Steve Antonf8470812017-12-04 10:46:21 -08005833const char* PeerConnection::SessionErrorToString(SessionError error) const {
5834 switch (error) {
5835 case SessionError::kNone:
5836 return "ERROR_NONE";
5837 case SessionError::kContent:
5838 return "ERROR_CONTENT";
5839 case SessionError::kTransport:
5840 return "ERROR_TRANSPORT";
5841 }
5842 RTC_NOTREACHED();
5843 return "";
5844}
5845
Steve Anton75737c02017-11-06 10:37:17 -08005846std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02005847 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08005848 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
5849 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08005850 return desc.str();
5851}
5852
Steve Anton8e20f172018-03-06 10:55:04 -08005853void PeerConnection::ReportSdpFormatReceived(
5854 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08005855 int num_audio_mlines = 0;
5856 int num_video_mlines = 0;
5857 int num_audio_tracks = 0;
5858 int num_video_tracks = 0;
5859 for (const ContentInfo& content : remote_offer.description()->contents()) {
5860 cricket::MediaType media_type = content.media_description()->type();
5861 int num_tracks = std::max(
5862 1, static_cast<int>(content.media_description()->streams().size()));
5863 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
5864 num_audio_mlines += 1;
5865 num_audio_tracks += num_tracks;
5866 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
5867 num_video_mlines += 1;
5868 num_video_tracks += num_tracks;
5869 }
5870 }
5871 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
5872 if (num_audio_mlines > 1 || num_video_mlines > 1) {
5873 format = kSdpFormatReceivedComplexUnifiedPlan;
5874 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
5875 format = kSdpFormatReceivedComplexPlanB;
5876 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
5877 format = kSdpFormatReceivedSimple;
5878 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005879 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
5880 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08005881}
5882
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005883void PeerConnection::NoteUsageEvent(UsageEvent event) {
5884 RTC_DCHECK_RUN_ON(signaling_thread());
5885 usage_event_accumulator_ |= static_cast<int>(event);
5886}
5887
5888void PeerConnection::ReportUsagePattern() const {
5889 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005890 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
5891 usage_event_accumulator_,
5892 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005893 const int bad_bits =
5894 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
5895 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
5896 const int good_bits =
5897 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
5898 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
5899 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
5900 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
5901 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02005902 // If called after close(), we can't report, because observer may have
5903 // been deallocated, and therefore pointer is null. Write to log instead.
5904 if (observer_) {
5905 Observer()->OnInterestingUsage(usage_event_accumulator_);
5906 } else {
5907 RTC_LOG(LS_INFO) << "Interesting usage signature "
5908 << usage_event_accumulator_
5909 << " observed after observer shutdown";
5910 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02005911 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005912}
5913
Steve Anton0ffaaa22018-02-23 10:31:30 -08005914void PeerConnection::ReportNegotiatedSdpSemantics(
5915 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005916 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005917 switch (answer.description()->msid_signaling()) {
5918 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005919 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005920 break;
5921 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005922 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005923 break;
5924 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005925 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005926 break;
5927 case cricket::kMsidSignalingMediaSection |
5928 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005929 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08005930 break;
5931 default:
5932 RTC_NOTREACHED();
5933 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005934 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
5935 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08005936}
5937
Steve Anton75737c02017-11-06 10:37:17 -08005938// We need to check the local/remote description for the Transport instead of
5939// the session, because a new Transport added during renegotiation may have
5940// them unset while the session has them set from the previous negotiation.
5941// Not doing so may trigger the auto generation of transport description and
5942// mess up DTLS identity information, ICE credential, etc.
5943bool PeerConnection::ReadyToUseRemoteCandidate(
5944 const IceCandidateInterface* candidate,
5945 const SessionDescriptionInterface* remote_desc,
5946 bool* valid) {
5947 *valid = true;
5948
5949 const SessionDescriptionInterface* current_remote_desc =
5950 remote_desc ? remote_desc : remote_description();
5951
5952 if (!current_remote_desc) {
5953 return false;
5954 }
5955
5956 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5957 size_t remote_content_size =
5958 current_remote_desc->description()->contents().size();
5959 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005960 RTC_LOG(LS_ERROR)
5961 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
5962 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08005963
5964 *valid = false;
5965 return false;
5966 }
5967
5968 cricket::ContentInfo content =
5969 current_remote_desc->description()->contents()[mediacontent_index];
5970
5971 const std::string transport_name = GetTransportName(content.name);
5972 if (transport_name.empty()) {
5973 return false;
5974 }
Zhi Huange830e682018-03-30 10:48:35 -07005975 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005976}
5977
5978bool PeerConnection::SrtpRequired() const {
5979 return dtls_enabled_ ||
5980 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
5981}
5982
5983void PeerConnection::OnTransportControllerGatheringState(
5984 cricket::IceGatheringState state) {
5985 RTC_DCHECK(signaling_thread()->IsCurrent());
5986 if (state == cricket::kIceGatheringGathering) {
5987 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
5988 } else if (state == cricket::kIceGatheringComplete) {
5989 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
5990 }
5991}
5992
5993void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08005994 std::map<std::string, std::set<cricket::MediaType>>
5995 media_types_by_transport_name;
5996 for (auto transceiver : transceivers_) {
5997 if (transceiver->internal()->channel()) {
5998 const std::string& transport_name =
5999 transceiver->internal()->channel()->transport_name();
6000 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006001 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006002 }
Steve Anton75737c02017-11-06 10:37:17 -08006003 }
6004 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006005 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6006 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006007 }
Zhi Huange830e682018-03-30 10:48:35 -07006008
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006009 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006010 if (transport_name) {
6011 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006012 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006013 }
Zhi Huange830e682018-03-30 10:48:35 -07006014
Steve Antonc7b964c2018-02-01 14:39:45 -08006015 for (const auto& entry : media_types_by_transport_name) {
6016 const std::string& transport_name = entry.first;
6017 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006018 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006019 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006020 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006021 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006022 }
6023 }
6024}
6025// Walk through the ConnectionInfos to gather best connection usage
6026// for IPv4 and IPv6.
6027void PeerConnection::ReportBestConnectionState(
6028 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006029 for (const cricket::TransportChannelStats& channel_stats :
6030 stats.channel_stats) {
6031 for (const cricket::ConnectionInfo& connection_info :
6032 channel_stats.connection_infos) {
6033 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006034 continue;
6035 }
6036
Steve Antonc7b964c2018-02-01 14:39:45 -08006037 const cricket::Candidate& local = connection_info.local_candidate;
6038 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006039
6040 // Increment the counter for IceCandidatePairType.
6041 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6042 (local.type() == RELAY_PORT_TYPE &&
6043 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006044 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6045 GetIceCandidatePairCounter(local, remote),
6046 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006047 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006048 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6049 GetIceCandidatePairCounter(local, remote),
6050 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006051 } else {
6052 RTC_CHECK(0);
6053 }
Steve Anton75737c02017-11-06 10:37:17 -08006054
6055 // Increment the counter for IP type.
6056 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006057 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6058 kBestConnections_IPv4,
6059 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006060 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006061 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6062 kBestConnections_IPv6,
6063 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006064 } else {
6065 RTC_CHECK(0);
6066 }
6067
6068 return;
6069 }
6070 }
6071}
6072
6073void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006074 const cricket::TransportStats& stats,
6075 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006076 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6077 return;
6078 }
6079
6080 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6081 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6082 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6083 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6084 return;
6085 }
6086
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006087 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6088 for (cricket::MediaType media_type : media_types) {
6089 switch (media_type) {
6090 case cricket::MEDIA_TYPE_AUDIO:
6091 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6092 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6093 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6094 break;
6095 case cricket::MEDIA_TYPE_VIDEO:
6096 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6097 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6098 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6099 break;
6100 case cricket::MEDIA_TYPE_DATA:
6101 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6102 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6103 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6104 break;
6105 default:
6106 RTC_NOTREACHED();
6107 continue;
6108 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006109 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006110 }
6111
6112 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6113 for (cricket::MediaType media_type : media_types) {
6114 switch (media_type) {
6115 case cricket::MEDIA_TYPE_AUDIO:
6116 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6117 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6118 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6119 break;
6120 case cricket::MEDIA_TYPE_VIDEO:
6121 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6122 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6123 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6124 break;
6125 case cricket::MEDIA_TYPE_DATA:
6126 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6127 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6128 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6129 break;
6130 default:
6131 RTC_NOTREACHED();
6132 continue;
6133 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006134 }
Steve Anton75737c02017-11-06 10:37:17 -08006135 }
6136}
6137
6138void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6139 RTC_DCHECK(worker_thread()->IsCurrent());
6140 RTC_DCHECK(call_);
6141 call_->OnSentPacket(sent_packet);
6142}
6143
6144const std::string PeerConnection::GetTransportName(
6145 const std::string& content_name) {
6146 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006147 if (channel) {
6148 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006149 }
Steve Anton6fec8802017-12-04 10:37:29 -08006150 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006151 RTC_DCHECK(sctp_mid_);
6152 if (content_name == *sctp_mid_) {
6153 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006154 }
6155 }
6156 // Return an empty string if failed to retrieve the transport name.
6157 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006158}
6159
Steve Anton6fec8802017-12-04 10:37:29 -08006160void PeerConnection::DestroyTransceiverChannel(
6161 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6162 transceiver) {
6163 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006164
Steve Anton6fec8802017-12-04 10:37:29 -08006165 cricket::BaseChannel* channel = transceiver->internal()->channel();
6166 if (channel) {
6167 transceiver->internal()->SetChannel(nullptr);
6168 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006169 }
6170}
6171
6172void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006173 if (rtp_data_channel_) {
6174 OnDataChannelDestroyed();
6175 DestroyBaseChannel(rtp_data_channel_);
6176 rtp_data_channel_ = nullptr;
6177 }
6178
6179 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6180 // grab a reference to this PeerConnection. If this is called from the
6181 // PeerConnection destructor, the RefCountedObject vtable will have already
6182 // been destroyed (since it is a subclass of PeerConnection) and using
6183 // rtc::Bind will cause "Pure virtual function called" error to appear.
6184
6185 if (sctp_transport_) {
6186 OnDataChannelDestroyed();
6187 network_thread()->Invoke<void>(RTC_FROM_HERE,
6188 [this] { DestroySctpTransport_n(); });
6189 }
6190}
6191
6192void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6193 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006194 switch (channel->media_type()) {
6195 case cricket::MEDIA_TYPE_AUDIO:
6196 channel_manager()->DestroyVoiceChannel(
6197 static_cast<cricket::VoiceChannel*>(channel));
6198 break;
6199 case cricket::MEDIA_TYPE_VIDEO:
6200 channel_manager()->DestroyVideoChannel(
6201 static_cast<cricket::VideoChannel*>(channel));
6202 break;
6203 case cricket::MEDIA_TYPE_DATA:
6204 channel_manager()->DestroyRtpDataChannel(
6205 static_cast<cricket::RtpDataChannel*>(channel));
6206 break;
6207 default:
6208 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6209 break;
6210 }
Zhi Huange830e682018-03-30 10:48:35 -07006211}
Steve Anton6fec8802017-12-04 10:37:29 -08006212
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006213bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006214 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006215 RtpTransportInternal* rtp_transport,
6216 cricket::DtlsTransportInternal* dtls_transport) {
6217 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006218 auto base_channel = GetChannel(mid);
6219 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006220 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006221 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006222 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006223 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006224 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006225 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006226}
6227
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006228PeerConnectionObserver* PeerConnection::Observer() const {
6229 // In earlier production code, the pointer was not cleared on close,
6230 // which might have led to undefined behavior if the observer was not
6231 // deallocated, or strange crashes if it was.
6232 // We use CHECK in order to catch such behavior if it exists.
6233 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6234 RTC_CHECK(observer_);
6235 return observer_;
6236}
6237
Harald Alvestrand89061872018-01-02 14:08:34 +01006238void PeerConnection::ClearStatsCache() {
6239 if (stats_collector_) {
6240 stats_collector_->ClearCachedStatsReport();
6241 }
6242}
6243
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006244void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006245 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6246 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006247}
6248
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006249} // namespace webrtc