blob: 54ef67740ebffbfbc0eaf12c89278ec4676a9661 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Harald Alvestrand8ebba742018-05-31 14:00:34 +020014#include <limits>
Steve Antondcc3c022017-12-22 16:02:54 -080015#include <queue>
Steve Anton75737c02017-11-06 10:37:17 -080016#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080017#include <utility>
18#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000019
Karl Wiberg918f50c2018-07-05 11:40:33 +020020#include "absl/memory/memory.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020021#include "api/jsepicecandidate.h"
22#include "api/jsepsessiondescription.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020023#include "api/mediastreamproxy.h"
24#include "api/mediastreamtrackproxy.h"
Yves Gerey2e00abc2018-10-05 15:39:24 +020025#include "api/umametrics.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "call/call.h"
Qingsi Wang93a84392018-01-30 17:13:09 -080027#include "logging/rtc_event_log/icelogger.h"
Elad Alon83ccca12017-10-04 13:18:26 +020028#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "logging/rtc_event_log/rtc_event_log.h"
30#include "media/sctp/sctptransport.h"
31#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080032#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "pc/channelmanager.h"
34#include "pc/dtmfsender.h"
35#include "pc/mediastream.h"
36#include "pc/mediastreamobserver.h"
37#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080038#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020039#include "pc/rtpreceiver.h"
40#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080041#include "pc/sctputils.h"
Steve Antona3a92c22017-12-07 10:27:41 -080042#include "pc/sdputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020043#include "pc/streamcollection.h"
44#include "pc/videocapturertracksource.h"
45#include "pc/videotrack.h"
46#include "rtc_base/bind.h"
47#include "rtc_base/checks.h"
48#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010049#include "rtc_base/numerics/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020050#include "rtc_base/stringencode.h"
Jonas Olsson366a50c2018-09-06 13:41:30 +020051#include "rtc_base/strings/string_builder.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020052#include "rtc_base/stringutils.h"
53#include "rtc_base/trace_event.h"
54#include "system_wrappers/include/clock.h"
55#include "system_wrappers/include/field_trial.h"
Qingsi Wang7fc821d2018-07-12 12:54:53 -070056#include "system_wrappers/include/metrics.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000057
Steve Anton75737c02017-11-06 10:37:17 -080058using cricket::ContentInfo;
59using cricket::ContentInfos;
60using cricket::MediaContentDescription;
61using cricket::SessionDescription;
Steve Anton5adfafd2017-12-20 16:34:00 -080062using cricket::MediaProtocolType;
Steve Anton75737c02017-11-06 10:37:17 -080063using cricket::TransportInfo;
64
65using cricket::LOCAL_PORT_TYPE;
66using cricket::STUN_PORT_TYPE;
67using cricket::RELAY_PORT_TYPE;
68using cricket::PRFLX_PORT_TYPE;
69
Steve Antonba818672017-11-06 10:21:57 -080070namespace webrtc {
71
Steve Anton75737c02017-11-06 10:37:17 -080072// Error messages
73const char kBundleWithoutRtcpMux[] =
74 "rtcp-mux must be enabled when BUNDLE "
75 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080076const char kInvalidCandidates[] = "Description contains invalid candidates.";
77const char kInvalidSdp[] = "Invalid session description.";
78const char kMlineMismatchInAnswer[] =
79 "The order of m-lines in answer doesn't match order in offer. Rejecting "
80 "answer.";
81const char kMlineMismatchInSubsequentOffer[] =
82 "The order of m-lines in subsequent offer doesn't match order from "
83 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080084const char kSdpWithoutDtlsFingerprint[] =
85 "Called with SDP without DTLS fingerprint.";
86const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
87const char kSdpWithoutIceUfragPwd[] =
88 "Called with SDP without ice-ufrag and ice-pwd.";
89const char kSessionError[] = "Session error code: ";
90const char kSessionErrorDesc[] = "Session error description: ";
91const char kDtlsSrtpSetupFailureRtp[] =
92 "Couldn't set up DTLS-SRTP on RTP channel.";
93const char kDtlsSrtpSetupFailureRtcp[] =
94 "Couldn't set up DTLS-SRTP on RTCP channel.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000095
Steve Anton75737c02017-11-06 10:37:17 -080096namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097
Seth Hampson845e8782018-03-02 11:34:10 -080098static const char kDefaultStreamId[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080099static const char kDefaultAudioSenderId[] = "defaulta0";
100static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -0700101
zhihuang8f65cdf2016-05-06 18:40:30 -0700102// The length of RTCP CNAMEs.
103static const int kRtcpCnameLength = 16;
104
Steve Antonad182762018-09-05 20:22:40 +0000105enum {
106 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
107 MSG_SET_SESSIONDESCRIPTION_FAILED,
108 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
109 MSG_GETSTATS,
110 MSG_FREE_DATACHANNELS,
111 MSG_REPORT_USAGE_PATTERN,
112};
113
Harald Alvestrand19793842018-06-25 12:03:50 +0200114static const int REPORT_USAGE_PATTERN_DELAY_MS = 60000;
115
Steve Antonad182762018-09-05 20:22:40 +0000116struct SetSessionDescriptionMsg : public rtc::MessageData {
117 explicit SetSessionDescriptionMsg(
118 webrtc::SetSessionDescriptionObserver* observer)
119 : observer(observer) {}
120
121 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
122 RTCError error;
123};
124
125struct CreateSessionDescriptionMsg : public rtc::MessageData {
126 explicit CreateSessionDescriptionMsg(
127 webrtc::CreateSessionDescriptionObserver* observer)
128 : observer(observer) {}
129
130 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
131 RTCError error;
132};
133
134struct GetStatsMsg : public rtc::MessageData {
135 GetStatsMsg(webrtc::StatsObserver* observer,
136 webrtc::MediaStreamTrackInterface* track)
137 : observer(observer), track(track) {}
138 rtc::scoped_refptr<webrtc::StatsObserver> observer;
139 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
140};
141
deadbeefab9b2d12015-10-14 11:33:11 -0700142// Check if we can send |new_stream| on a PeerConnection.
143bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
144 webrtc::MediaStreamInterface* new_stream) {
145 if (!new_stream || !current_streams) {
146 return false;
147 }
Seth Hampson13b8bad2018-03-13 16:05:28 -0700148 if (current_streams->find(new_stream->id()) != nullptr) {
149 RTC_LOG(LS_ERROR) << "MediaStream with ID " << new_stream->id()
Mirko Bonadei675513b2017-11-09 11:09:25 +0100150 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700151 return false;
152 }
153 return true;
154}
155
deadbeef5e97fb52015-10-15 12:49:08 -0700156// If the direction is "recvonly" or "inactive", treat the description
157// as containing no streams.
158// See: https://code.google.com/p/webrtc/issues/detail?id=5054
159std::vector<cricket::StreamParams> GetActiveStreams(
160 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800161 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700162 ? desc->streams()
163 : std::vector<cricket::StreamParams>();
164}
165
deadbeefab9b2d12015-10-14 11:33:11 -0700166bool IsValidOfferToReceiveMedia(int value) {
167 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
168 return (value >= Options::kUndefined) &&
169 (value <= Options::kMaxOfferToReceiveMedia);
170}
171
zhihuang1c378ed2017-08-17 14:10:50 -0700172// Add options to |[audio/video]_media_description_options| from |senders|.
173void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700174 const std::vector<rtc::scoped_refptr<
175 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700176 cricket::MediaDescriptionOptions* audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200177 cricket::MediaDescriptionOptions* video_media_description_options,
178 int num_sim_layers) {
olka3c747662017-08-17 06:50:32 -0700179 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700180 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
181 if (audio_media_description_options) {
182 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700183 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700184 }
185 } else {
186 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
187 if (video_media_description_options) {
188 video_media_description_options->AddVideoSender(
Jonas Orelandfc1acd22018-08-24 10:58:37 +0200189 sender->id(), sender->internal()->stream_ids(),
190 num_sim_layers);
zhihuang1c378ed2017-08-17 14:10:50 -0700191 }
192 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700193 }
zhihuang1c378ed2017-08-17 14:10:50 -0700194}
olka3c747662017-08-17 06:50:32 -0700195
zhihuang1c378ed2017-08-17 14:10:50 -0700196// Add options to |session_options| from |rtp_data_channels|.
197void AddRtpDataChannelOptions(
198 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
199 rtp_data_channels,
200 cricket::MediaDescriptionOptions* data_media_description_options) {
201 if (!data_media_description_options) {
202 return;
203 }
deadbeefab9b2d12015-10-14 11:33:11 -0700204 // Check for data channels.
205 for (const auto& kv : rtp_data_channels) {
206 const DataChannel* channel = kv.second;
207 if (channel->state() == DataChannel::kConnecting ||
208 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700209 // Legacy RTP data channels are signaled with the track/stream ID set to
210 // the data channel's label.
211 data_media_description_options->AddRtpDataChannel(channel->label(),
212 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700213 }
214 }
215}
216
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700217uint32_t ConvertIceTransportTypeToCandidateFilter(
218 PeerConnectionInterface::IceTransportsType type) {
219 switch (type) {
220 case PeerConnectionInterface::kNone:
221 return cricket::CF_NONE;
222 case PeerConnectionInterface::kRelay:
223 return cricket::CF_RELAY;
224 case PeerConnectionInterface::kNoHost:
225 return (cricket::CF_ALL & ~cricket::CF_HOST);
226 case PeerConnectionInterface::kAll:
227 return cricket::CF_ALL;
228 default:
nissec80e7412017-01-11 05:56:46 -0800229 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700230 }
231 return cricket::CF_NONE;
232}
233
deadbeef293e9262017-01-11 12:28:30 -0800234// Helper to set an error and return from a method.
235bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
236 if (error) {
237 error->set_type(type);
238 }
239 return type == webrtc::RTCErrorType::NONE;
240}
241
Steve Anton038834f2017-07-14 15:59:59 -0700242bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
Steve Antonf820a5e2018-08-10 10:22:52 -0700243 bool ok = error.ok();
Steve Anton038834f2017-07-14 15:59:59 -0700244 if (error_out) {
245 *error_out = std::move(error);
246 }
Steve Antonf820a5e2018-08-10 10:22:52 -0700247 return ok;
Steve Anton038834f2017-07-14 15:59:59 -0700248}
249
Steve Antonba818672017-11-06 10:21:57 -0800250std::string GetSignalingStateString(
251 PeerConnectionInterface::SignalingState state) {
252 switch (state) {
253 case PeerConnectionInterface::kStable:
254 return "kStable";
255 case PeerConnectionInterface::kHaveLocalOffer:
256 return "kHaveLocalOffer";
257 case PeerConnectionInterface::kHaveLocalPrAnswer:
258 return "kHavePrAnswer";
259 case PeerConnectionInterface::kHaveRemoteOffer:
260 return "kHaveRemoteOffer";
261 case PeerConnectionInterface::kHaveRemotePrAnswer:
262 return "kHaveRemotePrAnswer";
263 case PeerConnectionInterface::kClosed:
264 return "kClosed";
265 }
266 RTC_NOTREACHED();
267 return "";
268}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700269
Steve Anton75737c02017-11-06 10:37:17 -0800270IceCandidatePairType GetIceCandidatePairCounter(
271 const cricket::Candidate& local,
272 const cricket::Candidate& remote) {
273 const auto& l = local.type();
274 const auto& r = remote.type();
275 const auto& host = LOCAL_PORT_TYPE;
276 const auto& srflx = STUN_PORT_TYPE;
277 const auto& relay = RELAY_PORT_TYPE;
278 const auto& prflx = PRFLX_PORT_TYPE;
279 if (l == host && r == host) {
280 bool local_private = IPIsPrivate(local.address().ipaddr());
281 bool remote_private = IPIsPrivate(remote.address().ipaddr());
282 if (local_private) {
283 if (remote_private) {
284 return kIceCandidatePairHostPrivateHostPrivate;
285 } else {
286 return kIceCandidatePairHostPrivateHostPublic;
287 }
288 } else {
289 if (remote_private) {
290 return kIceCandidatePairHostPublicHostPrivate;
291 } else {
292 return kIceCandidatePairHostPublicHostPublic;
293 }
294 }
295 }
296 if (l == host && r == srflx)
297 return kIceCandidatePairHostSrflx;
298 if (l == host && r == relay)
299 return kIceCandidatePairHostRelay;
300 if (l == host && r == prflx)
301 return kIceCandidatePairHostPrflx;
302 if (l == srflx && r == host)
303 return kIceCandidatePairSrflxHost;
304 if (l == srflx && r == srflx)
305 return kIceCandidatePairSrflxSrflx;
306 if (l == srflx && r == relay)
307 return kIceCandidatePairSrflxRelay;
308 if (l == srflx && r == prflx)
309 return kIceCandidatePairSrflxPrflx;
310 if (l == relay && r == host)
311 return kIceCandidatePairRelayHost;
312 if (l == relay && r == srflx)
313 return kIceCandidatePairRelaySrflx;
314 if (l == relay && r == relay)
315 return kIceCandidatePairRelayRelay;
316 if (l == relay && r == prflx)
317 return kIceCandidatePairRelayPrflx;
318 if (l == prflx && r == host)
319 return kIceCandidatePairPrflxHost;
320 if (l == prflx && r == srflx)
321 return kIceCandidatePairPrflxSrflx;
322 if (l == prflx && r == relay)
323 return kIceCandidatePairPrflxRelay;
324 return kIceCandidatePairMax;
325}
326
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800327// Logic to decide if an m= section can be recycled. This means that the new
328// m= section is not rejected, but the old local or remote m= section is
329// rejected. |old_content_one| and |old_content_two| refer to the m= section
330// of the old remote and old local descriptions in no particular order.
331// We need to check both the old local and remote because either
332// could be the most current from the latest negotation.
333bool IsMediaSectionBeingRecycled(SdpType type,
334 const ContentInfo& content,
335 const ContentInfo* old_content_one,
336 const ContentInfo* old_content_two) {
337 return type == SdpType::kOffer && !content.rejected &&
338 ((old_content_one && old_content_one->rejected) ||
339 (old_content_two && old_content_two->rejected));
340}
341
Steve Anton75737c02017-11-06 10:37:17 -0800342// Verify that the order of media sections in |new_desc| matches
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800343// |current_desc|. The number of m= sections in |new_desc| should be no
344// less than |current_desc|. In the case of checking an answer's
345// |new_desc|, the |current_desc| is the last offer that was set as the
346// local or remote. In the case of checking an offer's |new_desc| we
347// check against the local and remote descriptions stored from the last
348// negotiation, because either of these could be the most up to date for
349// possible rejected m sections. These are the |current_desc| and
350// |secondary_current_desc|.
351bool MediaSectionsInSameOrder(const SessionDescription& current_desc,
352 const SessionDescription* secondary_current_desc,
353 const SessionDescription& new_desc,
354 const SdpType type) {
355 if (current_desc.contents().size() > new_desc.contents().size()) {
Steve Anton75737c02017-11-06 10:37:17 -0800356 return false;
357 }
358
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800359 for (size_t i = 0; i < current_desc.contents().size(); ++i) {
360 const cricket::ContentInfo* secondary_content_info = nullptr;
361 if (secondary_current_desc &&
362 i < secondary_current_desc->contents().size()) {
363 secondary_content_info = &secondary_current_desc->contents()[i];
364 }
365 if (IsMediaSectionBeingRecycled(type, new_desc.contents()[i],
366 &current_desc.contents()[i],
367 secondary_content_info)) {
368 // For new offer descriptions, if the media section can be recycled, it's
369 // valid for the MID and media type to change.
Steve Antondcc3c022017-12-22 16:02:54 -0800370 continue;
371 }
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800372 if (new_desc.contents()[i].name != current_desc.contents()[i].name) {
Steve Anton75737c02017-11-06 10:37:17 -0800373 return false;
374 }
375 const MediaContentDescription* new_desc_mdesc =
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800376 new_desc.contents()[i].media_description();
377 const MediaContentDescription* current_desc_mdesc =
378 current_desc.contents()[i].media_description();
379 if (new_desc_mdesc->type() != current_desc_mdesc->type()) {
Steve Anton75737c02017-11-06 10:37:17 -0800380 return false;
381 }
382 }
383 return true;
384}
385
Seth Hampsonae8a90a2018-02-13 15:33:48 -0800386bool MediaSectionsHaveSameCount(const SessionDescription& desc1,
387 const SessionDescription& desc2) {
388 return desc1.contents().size() == desc2.contents().size();
Steve Anton75737c02017-11-06 10:37:17 -0800389}
390
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700391void NoteKeyProtocolAndMedia(KeyExchangeProtocolType protocol_type,
392 cricket::MediaType media_type) {
Mirko Bonadeiab499822018-09-11 10:43:20 +0200393 // Array of structs needed to map {KeyExchangeProtocolType,
394 // cricket::MediaType} to KeyExchangeProtocolMedia without using std::map in
395 // order to avoid -Wglobal-constructors and -Wexit-time-destructors.
396 static constexpr struct {
397 KeyExchangeProtocolType protocol_type;
398 cricket::MediaType media_type;
399 KeyExchangeProtocolMedia protocol_media;
400 } kEnumCounterKeyProtocolMediaMap[] = {
401 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_AUDIO,
402 kEnumCounterKeyProtocolMediaTypeDtlsAudio},
403 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_VIDEO,
404 kEnumCounterKeyProtocolMediaTypeDtlsVideo},
405 {kEnumCounterKeyProtocolDtls, cricket::MEDIA_TYPE_DATA,
406 kEnumCounterKeyProtocolMediaTypeDtlsData},
407 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_AUDIO,
408 kEnumCounterKeyProtocolMediaTypeSdesAudio},
409 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_VIDEO,
410 kEnumCounterKeyProtocolMediaTypeSdesVideo},
411 {kEnumCounterKeyProtocolSdes, cricket::MEDIA_TYPE_DATA,
412 kEnumCounterKeyProtocolMediaTypeSdesData},
413 };
414
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700415 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocol", protocol_type,
416 kEnumCounterKeyProtocolMax);
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100417
Mirko Bonadeiab499822018-09-11 10:43:20 +0200418 for (const auto& i : kEnumCounterKeyProtocolMediaMap) {
419 if (i.protocol_type == protocol_type && i.media_type == media_type) {
420 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.KeyProtocolByMedia",
421 i.protocol_media,
422 kEnumCounterKeyProtocolMediaTypeMax);
423 }
Harald Alvestrandf9d0f1d2018-03-02 14:15:26 +0100424 }
425}
426
Harald Alvestrand76829d72018-07-18 23:24:36 +0200427void NoteAddIceCandidateResult(int result) {
428 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.AddIceCandidate", result,
429 kAddIceCandidateMax);
430}
431
Steve Anton75737c02017-11-06 10:37:17 -0800432// Checks that each non-rejected content has SDES crypto keys or a DTLS
433// fingerprint, unless it's in a BUNDLE group, in which case only the
434// BUNDLE-tag section (first media section/description in the BUNDLE group)
435// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
436// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
437// by Channel's |srtp_required| check.
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700438RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800439 const cricket::ContentGroup* bundle =
440 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800441 for (const cricket::ContentInfo& content_info : desc->contents()) {
442 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800443 continue;
444 }
Harald Alvestrand2e180612018-03-07 10:56:14 +0100445 // Note what media is used with each crypto protocol, for all sections.
446 NoteKeyProtocolAndMedia(dtls_enabled ? webrtc::kEnumCounterKeyProtocolDtls
447 : webrtc::kEnumCounterKeyProtocolSdes,
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700448 content_info.media_description()->type());
Steve Anton8a006912017-12-04 15:25:56 -0800449 const std::string& mid = content_info.name;
450 if (bundle && bundle->HasContentName(mid) &&
451 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800452 // This isn't the first media section in the BUNDLE group, so it's not
453 // required to have crypto attributes, since only the crypto attributes
454 // from the first section actually get used.
455 continue;
456 }
457
458 // If the content isn't rejected or bundled into another m= section, crypto
459 // must be present.
Steve Antonb1c1de12017-12-21 15:14:30 -0800460 const MediaContentDescription* media = content_info.media_description();
Steve Anton8a006912017-12-04 15:25:56 -0800461 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800462 if (!media || !tinfo) {
463 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800464 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800465 }
466 if (dtls_enabled) {
467 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100468 RTC_LOG(LS_WARNING)
469 << "Session description must have DTLS fingerprint if "
470 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800471 return RTCError(RTCErrorType::INVALID_PARAMETER,
472 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800473 }
474 } else {
475 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100476 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800477 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800478 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800479 }
480 }
481 }
Steve Anton8a006912017-12-04 15:25:56 -0800482 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800483}
484
485// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
486// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
487// media section/description in the BUNDLE group) needs a ufrag and pwd.
488bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
489 const cricket::ContentGroup* bundle =
490 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800491 for (const cricket::ContentInfo& content_info : desc->contents()) {
492 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800493 continue;
494 }
Steve Anton8a006912017-12-04 15:25:56 -0800495 const std::string& mid = content_info.name;
496 if (bundle && bundle->HasContentName(mid) &&
497 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800498 // This isn't the first media section in the BUNDLE group, so it's not
499 // required to have ufrag/password, since only the ufrag/password from
500 // the first section actually get used.
501 continue;
502 }
503
504 // If the content isn't rejected or bundled into another m= section,
505 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800506 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800507 if (!tinfo) {
508 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100509 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800510 return false;
511 }
512 if (tinfo->description.ice_ufrag.empty() ||
513 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100514 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800515 return false;
516 }
517 }
518 return true;
519}
520
521bool GetTrackIdBySsrc(const SessionDescription* session_description,
522 uint32_t ssrc,
523 std::string* track_id) {
524 RTC_DCHECK(track_id != NULL);
525
Steve Antonb1c1de12017-12-21 15:14:30 -0800526 const cricket::AudioContentDescription* audio_desc =
527 cricket::GetFirstAudioContentDescription(session_description);
528 if (audio_desc) {
529 const auto* found = cricket::GetStreamBySsrc(audio_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800530 if (found) {
531 *track_id = found->id;
532 return true;
533 }
534 }
535
Steve Antonb1c1de12017-12-21 15:14:30 -0800536 const cricket::VideoContentDescription* video_desc =
537 cricket::GetFirstVideoContentDescription(session_description);
538 if (video_desc) {
539 const auto* found = cricket::GetStreamBySsrc(video_desc->streams(), ssrc);
Steve Anton75737c02017-11-06 10:37:17 -0800540 if (found) {
541 *track_id = found->id;
542 return true;
543 }
544 }
545 return false;
546}
547
548// Get the SCTP port out of a SessionDescription.
549// Return -1 if not found.
550int GetSctpPort(const SessionDescription* session_description) {
Steve Antonb1c1de12017-12-21 15:14:30 -0800551 const cricket::DataContentDescription* data_desc =
552 GetFirstDataContentDescription(session_description);
553 RTC_DCHECK(data_desc);
554 if (!data_desc) {
Steve Anton75737c02017-11-06 10:37:17 -0800555 return -1;
556 }
Steve Anton75737c02017-11-06 10:37:17 -0800557 std::string value;
558 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
559 cricket::kGoogleSctpDataCodecName);
Steve Antonb1c1de12017-12-21 15:14:30 -0800560 for (const cricket::DataCodec& codec : data_desc->codecs()) {
Steve Anton75737c02017-11-06 10:37:17 -0800561 if (!codec.Matches(match_pattern)) {
562 continue;
563 }
564 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
565 return rtc::FromString<int>(value);
566 }
567 }
568 return -1;
569}
570
Steve Anton75737c02017-11-06 10:37:17 -0800571// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
572bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
573 const SessionDescriptionInterface* new_desc,
574 const std::string& content_name) {
575 if (!old_desc) {
576 return false;
577 }
578 const SessionDescription* new_sd = new_desc->description();
579 const SessionDescription* old_sd = old_desc->description();
580 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
581 if (!cinfo || cinfo->rejected) {
582 return false;
583 }
584 // If the content isn't rejected, check if ufrag and password has changed.
585 const cricket::TransportDescription* new_transport_desc =
586 new_sd->GetTransportDescriptionByName(content_name);
587 const cricket::TransportDescription* old_transport_desc =
588 old_sd->GetTransportDescriptionByName(content_name);
589 if (!new_transport_desc || !old_transport_desc) {
590 // No transport description exists. This is not an ICE restart.
591 return false;
592 }
593 if (cricket::IceCredentialsChanged(
594 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
595 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100596 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
597 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800598 return true;
599 }
600 return false;
601}
602
Steve Anton80dd7b52018-02-16 17:08:42 -0800603// Generates a string error message for SetLocalDescription/SetRemoteDescription
604// from an RTCError.
605std::string GetSetDescriptionErrorMessage(cricket::ContentSource source,
606 SdpType type,
607 const RTCError& error) {
Jonas Olsson366a50c2018-09-06 13:41:30 +0200608 rtc::StringBuilder oss;
Steve Anton80dd7b52018-02-16 17:08:42 -0800609 oss << "Failed to set " << (source == cricket::CS_LOCAL ? "local" : "remote")
610 << " " << SdpTypeToString(type) << " sdp: " << error.message();
Jonas Olsson84df1c72018-09-14 16:59:32 +0200611 return oss.Release();
Steve Anton80dd7b52018-02-16 17:08:42 -0800612}
613
Seth Hampson5b4f0752018-04-02 16:31:36 -0700614std::string GetStreamIdsString(rtc::ArrayView<const std::string> stream_ids) {
615 std::string output = "streams=[";
616 const char* separator = "";
617 for (const auto& stream_id : stream_ids) {
618 output.append(separator).append(stream_id);
619 separator = ", ";
620 }
621 output.append("]");
622 return output;
623}
624
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200625absl::optional<int> RTCConfigurationToIceConfigOptionalInt(
Qingsi Wang866e08d2018-03-22 17:54:23 -0700626 int rtc_configuration_parameter) {
627 if (rtc_configuration_parameter ==
628 webrtc::PeerConnectionInterface::RTCConfiguration::kUndefined) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200629 return absl::nullopt;
Qingsi Wang866e08d2018-03-22 17:54:23 -0700630 }
631 return rtc_configuration_parameter;
632}
633
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800634cricket::DataMessageType ToCricketDataMessageType(DataMessageType type) {
635 switch (type) {
636 case DataMessageType::kText:
637 return cricket::DMT_TEXT;
638 case DataMessageType::kBinary:
639 return cricket::DMT_BINARY;
640 case DataMessageType::kControl:
641 return cricket::DMT_CONTROL;
642 default:
643 return cricket::DMT_NONE;
644 }
645 return cricket::DMT_NONE;
646}
647
648DataMessageType ToWebrtcDataMessageType(cricket::DataMessageType type) {
649 switch (type) {
650 case cricket::DMT_TEXT:
651 return DataMessageType::kText;
652 case cricket::DMT_BINARY:
653 return DataMessageType::kBinary;
654 case cricket::DMT_CONTROL:
655 return DataMessageType::kControl;
656 case cricket::DMT_NONE:
657 default:
658 RTC_NOTREACHED();
659 }
660 return DataMessageType::kControl;
661}
662
Steve Anton75737c02017-11-06 10:37:17 -0800663} // namespace
664
Henrik Boström31638672017-11-23 17:48:32 +0100665// Upon completion, posts a task to execute the callback of the
666// SetSessionDescriptionObserver asynchronously on the same thread. At this
667// point, the state of the peer connection might no longer reflect the effects
668// of the SetRemoteDescription operation, as the peer connection could have been
669// modified during the post.
670// TODO(hbos): Remove this class once we remove the version of
671// PeerConnectionInterface::SetRemoteDescription() that takes a
672// SetSessionDescriptionObserver as an argument.
673class PeerConnection::SetRemoteDescriptionObserverAdapter
674 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
675 public:
676 SetRemoteDescriptionObserverAdapter(
677 rtc::scoped_refptr<PeerConnection> pc,
678 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
679 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
680
681 // SetRemoteDescriptionObserverInterface implementation.
682 void OnSetRemoteDescriptionComplete(RTCError error) override {
683 if (error.ok())
684 pc_->PostSetSessionDescriptionSuccess(wrapper_);
685 else
Harald Alvestrand5081c0c2018-03-09 15:18:03 +0100686 pc_->PostSetSessionDescriptionFailure(wrapper_, std::move(error));
Henrik Boström31638672017-11-23 17:48:32 +0100687 }
688
689 private:
690 rtc::scoped_refptr<PeerConnection> pc_;
691 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
692};
693
deadbeef293e9262017-01-11 12:28:30 -0800694bool PeerConnectionInterface::RTCConfiguration::operator==(
695 const PeerConnectionInterface::RTCConfiguration& o) const {
696 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700697 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800698 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000699 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700700 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800701 BundlePolicy bundle_policy;
702 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700703 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
704 int ice_candidate_pool_size;
705 bool disable_ipv6;
706 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700707 int max_ipv6_networks;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100708 bool disable_link_local_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700709 bool enable_rtp_data_channel;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200710 absl::optional<int> screencast_min_bitrate;
711 absl::optional<bool> combined_audio_video_bwe;
712 absl::optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800713 TcpCandidatePolicy tcp_candidate_policy;
714 CandidateNetworkPolicy candidate_network_policy;
715 int audio_jitter_buffer_max_packets;
716 bool audio_jitter_buffer_fast_accelerate;
717 int ice_connection_receiving_timeout;
718 int ice_backup_candidate_pair_ping_interval;
719 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800720 bool prioritize_most_likely_ice_candidate_pairs;
721 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800722 bool prune_turn_ports;
723 bool presume_writable_when_fully_relayed;
724 bool enable_ice_renomination;
725 bool redetermine_role_on_ice_restart;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200726 absl::optional<int> ice_check_interval_strong_connectivity;
727 absl::optional<int> ice_check_interval_weak_connectivity;
728 absl::optional<int> ice_check_min_interval;
729 absl::optional<int> ice_unwritable_timeout;
730 absl::optional<int> ice_unwritable_min_checks;
731 absl::optional<int> stun_candidate_keepalive_interval;
732 absl::optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200733 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800734 SdpSemantics sdp_semantics;
Danil Chapovalov66cadcc2018-06-19 16:47:43 +0200735 absl::optional<rtc::AdapterType> network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -0700736 bool active_reset_srtp_params;
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700737 bool use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700738 bool use_media_transport_for_data_channels;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700739 absl::optional<CryptoOptions> crypto_options;
deadbeef293e9262017-01-11 12:28:30 -0800740 };
741 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
742 "Did you add something to RTCConfiguration and forget to "
743 "update operator==?");
744 return type == o.type && servers == o.servers &&
745 bundle_policy == o.bundle_policy &&
746 rtcp_mux_policy == o.rtcp_mux_policy &&
747 tcp_candidate_policy == o.tcp_candidate_policy &&
748 candidate_network_policy == o.candidate_network_policy &&
749 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
750 audio_jitter_buffer_fast_accelerate ==
751 o.audio_jitter_buffer_fast_accelerate &&
752 ice_connection_receiving_timeout ==
753 o.ice_connection_receiving_timeout &&
754 ice_backup_candidate_pair_ping_interval ==
755 o.ice_backup_candidate_pair_ping_interval &&
756 continual_gathering_policy == o.continual_gathering_policy &&
757 certificates == o.certificates &&
758 prioritize_most_likely_ice_candidate_pairs ==
759 o.prioritize_most_likely_ice_candidate_pairs &&
760 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800761 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700762 max_ipv6_networks == o.max_ipv6_networks &&
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +0100763 disable_link_local_networks == o.disable_link_local_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800764 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800765 screencast_min_bitrate == o.screencast_min_bitrate &&
766 combined_audio_video_bwe == o.combined_audio_video_bwe &&
767 enable_dtls_srtp == o.enable_dtls_srtp &&
768 ice_candidate_pool_size == o.ice_candidate_pool_size &&
769 prune_turn_ports == o.prune_turn_ports &&
770 presume_writable_when_fully_relayed ==
771 o.presume_writable_when_fully_relayed &&
772 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800773 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Qingsi Wange6826d22018-03-08 14:55:14 -0800774 ice_check_interval_strong_connectivity ==
775 o.ice_check_interval_strong_connectivity &&
776 ice_check_interval_weak_connectivity ==
777 o.ice_check_interval_weak_connectivity &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700778 ice_check_min_interval == o.ice_check_min_interval &&
Qingsi Wang22e623a2018-03-13 10:53:57 -0700779 ice_unwritable_timeout == o.ice_unwritable_timeout &&
780 ice_unwritable_min_checks == o.ice_unwritable_min_checks &&
Qingsi Wangdb53f8e2018-02-20 14:45:49 -0800781 stun_candidate_keepalive_interval ==
782 o.stun_candidate_keepalive_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200783 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800784 turn_customizer == o.turn_customizer &&
Qingsi Wang9a5c6f82018-02-01 10:38:40 -0800785 sdp_semantics == o.sdp_semantics &&
Zhi Huangb57e1692018-06-12 11:41:11 -0700786 network_preference == o.network_preference &&
Piotr (Peter) Slatalae0c2e972018-10-08 09:43:21 -0700787 active_reset_srtp_params == o.active_reset_srtp_params &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700788 use_media_transport == o.use_media_transport &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700789 use_media_transport_for_data_channels ==
790 o.use_media_transport_for_data_channels &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700791 crypto_options == o.crypto_options;
deadbeef293e9262017-01-11 12:28:30 -0800792}
793
794bool PeerConnectionInterface::RTCConfiguration::operator!=(
795 const PeerConnectionInterface::RTCConfiguration& o) const {
796 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800797}
798
zhihuang8f65cdf2016-05-06 18:40:30 -0700799// Generate a RTCP CNAME when a PeerConnection is created.
800std::string GenerateRtcpCname() {
801 std::string cname;
802 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100803 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800804 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700805 }
806 return cname;
807}
808
zhihuang1c378ed2017-08-17 14:10:50 -0700809bool ValidateOfferAnswerOptions(
810 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
811 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
812 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700813}
814
zhihuang1c378ed2017-08-17 14:10:50 -0700815// From |rtc_options|, fill parts of |session_options| shared by all generated
816// m= sections (in other words, nothing that involves a map/array).
817void ExtractSharedMediaSessionOptions(
818 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
819 cricket::MediaSessionOptions* session_options) {
820 session_options->vad_enabled = rtc_options.voice_activity_detection;
821 session_options->bundle_enabled = rtc_options.use_rtp_mux;
822}
zhihuanga77e6bb2017-08-14 18:17:48 -0700823
zhihuang38ede132017-06-15 12:52:32 -0700824PeerConnection::PeerConnection(PeerConnectionFactory* factory,
825 std::unique_ptr<RtcEventLog> event_log,
826 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700828 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700829 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700830 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700831 remote_streams_(StreamCollection::Create()),
832 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000833
834PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100835 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800836 RTC_DCHECK_RUN_ON(signaling_thread());
837
Steve Anton8af21862017-12-15 11:20:13 -0800838 // Need to stop transceivers before destroying the stats collector because
839 // AudioRtpSender has a reference to the StatsCollector it will update when
840 // stopping.
841 for (auto transceiver : transceivers_) {
842 transceiver->Stop();
843 }
Steve Anton4171afb2017-11-20 10:20:22 -0800844
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700845 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800846 if (stats_collector_) {
847 stats_collector_->WaitForPendingRequest();
848 stats_collector_ = nullptr;
849 }
Steve Anton75737c02017-11-06 10:37:17 -0800850
Steve Anton8af21862017-12-15 11:20:13 -0800851 // Don't destroy BaseChannels until after stats has been cleaned up so that
852 // the last stats request can still read from the channels.
853 DestroyAllChannels();
854
Mirko Bonadei675513b2017-11-09 11:09:25 +0100855 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800856
857 webrtc_session_desc_factory_.reset();
858 sctp_invoker_.reset();
859 sctp_factory_.reset();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -0800860 media_transport_invoker_.reset();
Steve Anton75737c02017-11-06 10:37:17 -0800861 transport_controller_.reset();
862
deadbeef91dd5672016-05-18 16:55:30 -0700863 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700864 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700865 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700866 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700867 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700868 call_.reset();
Qingsi Wang93a84392018-01-30 17:13:09 -0800869 // The event log must outlive call (and any other object that uses it).
eladalon248fd4f2017-09-06 05:18:15 -0700870 event_log_.reset();
871 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000872}
873
Steve Anton8af21862017-12-15 11:20:13 -0800874void PeerConnection::DestroyAllChannels() {
Steve Anton3fe1b152017-12-12 10:20:08 -0800875 // Destroy video channels first since they may have a pointer to a voice
876 // channel.
877 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800878 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800879 DestroyTransceiverChannel(transceiver);
880 }
881 }
882 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -0800883 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton3fe1b152017-12-12 10:20:08 -0800884 DestroyTransceiverChannel(transceiver);
885 }
886 }
887 DestroyDataChannel();
888}
889
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000890bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000891 const PeerConnectionInterface::RTCConfiguration& configuration,
Benjamin Wrightcab58882018-05-02 15:12:47 -0700892 PeerConnectionDependencies dependencies) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100893 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700894
895 RTCError config_error = ValidateConfiguration(configuration);
896 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100897 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700898 return false;
899 }
900
Benjamin Wrightcab58882018-05-02 15:12:47 -0700901 if (!dependencies.allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100902 RTC_LOG(LS_ERROR)
903 << "PeerConnection initialized without a PortAllocator? "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100904 "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800905 return false;
906 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200907
Benjamin Wrightcab58882018-05-02 15:12:47 -0700908 if (!dependencies.observer) {
deadbeef293e9262017-01-11 12:28:30 -0800909 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100910 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
Jonas Olsson45cc8902018-02-13 10:37:07 +0100911 "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800912 return false;
913 }
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700914
Benjamin Wrightcab58882018-05-02 15:12:47 -0700915 observer_ = dependencies.observer;
Zach Steine20867f2018-08-02 13:20:15 -0700916 async_resolver_factory_ = std::move(dependencies.async_resolver_factory);
Benjamin Wrightcab58882018-05-02 15:12:47 -0700917 port_allocator_ = std::move(dependencies.allocator);
Benjamin Wrightd6f86e82018-05-08 13:12:25 -0700918 tls_cert_verifier_ = std::move(dependencies.tls_cert_verifier);
deadbeef653b8e02015-11-11 12:55:10 -0800919
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200920 cricket::ServerAddresses stun_servers;
921 std::vector<cricket::RelayServerConfig> turn_servers;
922
923 RTCErrorType parse_error =
924 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
925 if (parse_error != RTCErrorType::NONE) {
926 return false;
927 }
928
deadbeef91dd5672016-05-18 16:55:30 -0700929 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700930 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700931 if (!network_thread()->Invoke<bool>(
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200932 RTC_FROM_HERE,
933 rtc::Bind(&PeerConnection::InitializePortAllocator_n, this,
934 stun_servers, turn_servers, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935 return false;
936 }
Harald Alvestrandb2a74782018-06-28 13:54:07 +0200937 // If initialization was successful, note if STUN or TURN servers
938 // were supplied.
939 if (!stun_servers.empty()) {
940 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
941 }
942 if (!turn_servers.empty()) {
943 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
944 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000945
Qingsi Wang7fc821d2018-07-12 12:54:53 -0700946 // Send information about IPv4/IPv6 status.
947 PeerConnectionAddressFamilyCounter address_family;
948 if (port_allocator_flags_ & cricket::PORTALLOCATOR_ENABLE_IPV6) {
949 address_family = kPeerConnection_IPv6;
950 } else {
951 address_family = kPeerConnection_IPv4;
952 }
953 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics", address_family,
954 kPeerConnectionAddressFamilyCounter_Max);
955
Zhi Huange830e682018-03-30 10:48:35 -0700956 const PeerConnectionFactoryInterface::Options& options = factory_->options();
957
Steve Anton75737c02017-11-06 10:37:17 -0800958 // RFC 3264: The numeric value of the session id and version in the
959 // o line MUST be representable with a "64 bit signed integer".
960 // Due to this constraint session id |session_id_| is max limited to
961 // LLONG_MAX.
962 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
Zhi Huange830e682018-03-30 10:48:35 -0700963 JsepTransportController::Config config;
964 config.redetermine_role_on_ice_restart =
965 configuration.redetermine_role_on_ice_restart;
966 config.ssl_max_version = factory_->options().ssl_max_version;
967 config.disable_encryption = options.disable_encryption;
968 config.bundle_policy = configuration.bundle_policy;
969 config.rtcp_mux_policy = configuration.rtcp_mux_policy;
Benjamin Wright8c27cca2018-10-25 10:16:44 -0700970 // TODO(bugs.webrtc.org/9891) - Remove options.crypto_options then remove this
971 // stub.
972 config.crypto_options = configuration.crypto_options.has_value()
973 ? *configuration.crypto_options
974 : options.crypto_options;
Zhi Huang365381f2018-04-13 16:44:34 -0700975 config.transport_observer = this;
Qingsi Wang7685e862018-06-11 20:15:46 -0700976 config.event_log = event_log_.get();
Zhi Huange830e682018-03-30 10:48:35 -0700977#if defined(ENABLE_EXTERNAL_AUTH)
978 config.enable_external_auth = true;
979#endif
Zhi Huangb57e1692018-06-12 11:41:11 -0700980 config.active_reset_srtp_params = configuration.active_reset_srtp_params;
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700981
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700982 if (configuration.use_media_transport ||
983 configuration.use_media_transport_for_data_channels) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700984 if (!factory_->media_transport_factory()) {
985 RTC_DCHECK(false)
Bjorn Mellema9bbd862018-11-02 09:07:48 -0700986 << "PeerConnecton is initialized with use_media_transport = true or "
987 << "use_media_transport_for_data_channels = true "
988 << "but media transport factory is not set in PeerConnectionFactory";
Anton Sukhanov98a462c2018-10-17 13:15:42 -0700989 return false;
990 }
991
992 config.media_transport_factory = factory_->media_transport_factory();
993 }
994
Zhi Huange830e682018-03-30 10:48:35 -0700995 transport_controller_.reset(new JsepTransportController(
Zach Steine20867f2018-08-02 13:20:15 -0700996 signaling_thread(), network_thread(), port_allocator_.get(),
997 async_resolver_factory_.get(), config));
Zhi Huange830e682018-03-30 10:48:35 -0700998 transport_controller_->SignalIceConnectionState.connect(
Steve Anton75737c02017-11-06 10:37:17 -0800999 this, &PeerConnection::OnTransportControllerConnectionState);
Jonas Olsson635474e2018-10-18 15:58:17 +02001000 transport_controller_->SignalStandardizedIceConnectionState.connect(
1001 this, &PeerConnection::SetStandardizedIceConnectionState);
1002 transport_controller_->SignalConnectionState.connect(
1003 this, &PeerConnection::SetConnectionState);
Zhi Huange830e682018-03-30 10:48:35 -07001004 transport_controller_->SignalIceGatheringState.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001005 this, &PeerConnection::OnTransportControllerGatheringState);
Zhi Huange830e682018-03-30 10:48:35 -07001006 transport_controller_->SignalIceCandidatesGathered.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001007 this, &PeerConnection::OnTransportControllerCandidatesGathered);
Zhi Huange830e682018-03-30 10:48:35 -07001008 transport_controller_->SignalIceCandidatesRemoved.connect(
Steve Anton75737c02017-11-06 10:37:17 -08001009 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
1010 transport_controller_->SignalDtlsHandshakeError.connect(
1011 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
1012
1013 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -07001014
deadbeefab9b2d12015-10-14 11:33:11 -07001015 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -07001016 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001017
Steve Antonba818672017-11-06 10:21:57 -08001018 configuration_ = configuration;
1019
Steve Anton75737c02017-11-06 10:37:17 -08001020 // Obtain a certificate from RTCConfiguration if any were provided (optional).
1021 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
1022 if (!configuration.certificates.empty()) {
1023 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
1024 // just picking the first one. The decision should be made based on the DTLS
1025 // handshake. The DTLS negotiations need to know about all certificates.
1026 certificate = configuration.certificates[0];
1027 }
1028
Steve Antond25da372017-11-06 14:50:29 -08001029 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -08001030
1031 if (options.disable_encryption) {
1032 dtls_enabled_ = false;
1033 } else {
1034 // Enable DTLS by default if we have an identity store or a certificate.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001035 dtls_enabled_ = (dependencies.cert_generator || certificate);
Steve Anton75737c02017-11-06 10:37:17 -08001036 // |configuration| can override the default |dtls_enabled_| value.
1037 if (configuration.enable_dtls_srtp) {
1038 dtls_enabled_ = *(configuration.enable_dtls_srtp);
1039 }
1040 }
1041
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08001042 if (configuration.use_media_transport_for_data_channels) {
1043 if (configuration.enable_rtp_data_channel) {
1044 RTC_LOG(LS_ERROR) << "enable_rtp_data_channel and "
1045 "use_media_transport_for_data_channels are "
1046 "incompatible and cannot both be set to true";
1047 return false;
1048 }
1049 data_channel_type_ = cricket::DCT_MEDIA_TRANSPORT;
1050 } else if (configuration.enable_rtp_data_channel) {
1051 // Enable creation of RTP data channels if the kEnableRtpDataChannels is
1052 // set. It takes precendence over the disable_sctp_data_channels
1053 // PeerConnectionFactoryInterface::Options.
Steve Anton75737c02017-11-06 10:37:17 -08001054 data_channel_type_ = cricket::DCT_RTP;
1055 } else {
1056 // DTLS has to be enabled to use SCTP.
1057 if (!options.disable_sctp_data_channels && dtls_enabled_) {
1058 data_channel_type_ = cricket::DCT_SCTP;
1059 }
1060 }
1061
1062 video_options_.screencast_min_bitrate_kbps =
1063 configuration.screencast_min_bitrate;
1064 audio_options_.combined_audio_video_bwe =
1065 configuration.combined_audio_video_bwe;
1066
1067 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001068 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -08001069
1070 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +01001071 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -08001072
1073 // Whether the certificate generator/certificate is null or not determines
1074 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1075 // the right instructions by clearing the variables if needed.
1076 if (!dtls_enabled_) {
Benjamin Wrightcab58882018-05-02 15:12:47 -07001077 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001078 certificate = nullptr;
1079 } else if (certificate) {
1080 // Favor generated certificate over the certificate generator.
Benjamin Wrightcab58882018-05-02 15:12:47 -07001081 dependencies.cert_generator.reset();
Steve Anton75737c02017-11-06 10:37:17 -08001082 }
1083
1084 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1085 signaling_thread(), channel_manager(), this, session_id(),
Benjamin Wrightcab58882018-05-02 15:12:47 -07001086 std::move(dependencies.cert_generator), certificate));
Steve Anton75737c02017-11-06 10:37:17 -08001087 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1088 this, &PeerConnection::OnCertificateReady);
1089
1090 if (options.disable_encryption) {
1091 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1092 }
1093
1094 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
Benjamin Wright8c27cca2018-10-25 10:16:44 -07001095 GetCryptoOptions().srtp.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001096
Steve Anton4171afb2017-11-20 10:20:22 -08001097 // Add default audio/video transceivers for Plan B SDP.
1098 if (!IsUnifiedPlan()) {
1099 transceivers_.push_back(
1100 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1101 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
1102 transceivers_.push_back(
1103 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1104 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
1105 }
Harald Alvestrand183e09d2018-06-28 12:04:41 +02001106 int delay_ms =
1107 return_histogram_very_quickly_ ? 0 : REPORT_USAGE_PATTERN_DELAY_MS;
Steve Antonad182762018-09-05 20:22:40 +00001108 signaling_thread()->PostDelayed(RTC_FROM_HERE, delay_ms, this,
1109 MSG_REPORT_USAGE_PATTERN, nullptr);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001110 return true;
1111}
1112
Steve Anton038834f2017-07-14 15:59:59 -07001113RTCError PeerConnection::ValidateConfiguration(
1114 const RTCConfiguration& config) const {
1115 if (config.ice_regather_interval_range &&
1116 config.continual_gathering_policy == GATHER_ONCE) {
1117 return RTCError(RTCErrorType::INVALID_PARAMETER,
1118 "ice_regather_interval_range specified but continual "
1119 "gathering policy is GATHER_ONCE");
1120 }
Qingsi Wangdea68892018-03-27 10:55:21 -07001121 auto result =
1122 cricket::P2PTransportChannel::ValidateIceConfig(ParseIceConfig(config));
1123 return result;
Steve Anton038834f2017-07-14 15:59:59 -07001124}
1125
Yves Gerey665174f2018-06-19 15:03:05 +02001126rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::local_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001127 RTC_CHECK(!IsUnifiedPlan()) << "local_streams is not available with Unified "
1128 "Plan SdpSemantics. Please use GetSenders "
1129 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001130 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001131}
1132
Yves Gerey665174f2018-06-19 15:03:05 +02001133rtc::scoped_refptr<StreamCollectionInterface> PeerConnection::remote_streams() {
Steve Antonfc853712018-03-01 13:48:58 -08001134 RTC_CHECK(!IsUnifiedPlan()) << "remote_streams is not available with Unified "
1135 "Plan SdpSemantics. Please use GetReceivers "
1136 "instead.";
deadbeefab9b2d12015-10-14 11:33:11 -07001137 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001138}
1139
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001140bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001141 RTC_CHECK(!IsUnifiedPlan()) << "AddStream is not available with Unified Plan "
1142 "SdpSemantics. Please use AddTrack instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001143 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001144 if (IsClosed()) {
1145 return false;
1146 }
deadbeefab9b2d12015-10-14 11:33:11 -07001147 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001148 return false;
1149 }
deadbeefab9b2d12015-10-14 11:33:11 -07001150
1151 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001152 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1153 observer->SignalAudioTrackAdded.connect(this,
1154 &PeerConnection::OnAudioTrackAdded);
1155 observer->SignalAudioTrackRemoved.connect(
1156 this, &PeerConnection::OnAudioTrackRemoved);
1157 observer->SignalVideoTrackAdded.connect(this,
1158 &PeerConnection::OnVideoTrackAdded);
1159 observer->SignalVideoTrackRemoved.connect(
1160 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001161 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001162
deadbeefab9b2d12015-10-14 11:33:11 -07001163 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001164 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001165 }
1166 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001167 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001168 }
1169
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001170 stats_->AddStream(local_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001171 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001172 return true;
1173}
1174
1175void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Steve Antonfc853712018-03-01 13:48:58 -08001176 RTC_CHECK(!IsUnifiedPlan()) << "RemoveStream is not available with Unified "
1177 "Plan SdpSemantics. Please use RemoveTrack "
1178 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001179 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001180 if (!IsClosed()) {
1181 for (const auto& track : local_stream->GetAudioTracks()) {
1182 RemoveAudioTrack(track.get(), local_stream);
1183 }
1184 for (const auto& track : local_stream->GetVideoTracks()) {
1185 RemoveVideoTrack(track.get(), local_stream);
1186 }
deadbeefab9b2d12015-10-14 11:33:11 -07001187 }
deadbeefab9b2d12015-10-14 11:33:11 -07001188 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001189 stream_observers_.erase(
1190 std::remove_if(
1191 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001192 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
Seth Hampson13b8bad2018-03-13 16:05:28 -07001193 return observer->stream()->id().compare(local_stream->id()) == 0;
deadbeefeb459812015-12-15 19:24:43 -08001194 }),
1195 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 if (IsClosed()) {
1198 return;
1199 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001200 Observer()->OnRenegotiationNeeded();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001201}
1202
Steve Anton2d6c76a2018-01-05 17:10:52 -08001203RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::AddTrack(
Steve Antonf9381f02017-12-14 10:23:57 -08001204 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001205 const std::vector<std::string>& stream_ids) {
Steve Anton2d6c76a2018-01-05 17:10:52 -08001206 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
Steve Antonf9381f02017-12-14 10:23:57 -08001207 if (!track) {
1208 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Track is null.");
1209 }
1210 if (!(track->kind() == MediaStreamTrackInterface::kAudioKind ||
1211 track->kind() == MediaStreamTrackInterface::kVideoKind)) {
1212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1213 "Track has invalid kind: " + track->kind());
1214 }
Steve Antonf9381f02017-12-14 10:23:57 -08001215 if (IsClosed()) {
1216 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1217 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001218 }
Steve Anton4171afb2017-11-20 10:20:22 -08001219 if (FindSenderForTrack(track)) {
Steve Antonf9381f02017-12-14 10:23:57 -08001220 LOG_AND_RETURN_ERROR(
1221 RTCErrorType::INVALID_PARAMETER,
1222 "Sender already exists for track " + track->id() + ".");
deadbeefe1f9d832016-01-14 15:35:42 -08001223 }
Steve Antonf9381f02017-12-14 10:23:57 -08001224 auto sender_or_error =
Seth Hampson5b4f0752018-04-02 16:31:36 -07001225 (IsUnifiedPlan() ? AddTrackUnifiedPlan(track, stream_ids)
1226 : AddTrackPlanB(track, stream_ids));
Steve Antonf9381f02017-12-14 10:23:57 -08001227 if (sender_or_error.ok()) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001228 Observer()->OnRenegotiationNeeded();
Steve Anton43a723a2018-01-04 15:48:17 -08001229 stats_->AddTrack(track);
Steve Antonf9381f02017-12-14 10:23:57 -08001230 }
1231 return sender_or_error;
1232}
deadbeefe1f9d832016-01-14 15:35:42 -08001233
Steve Antonf9381f02017-12-14 10:23:57 -08001234RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1235PeerConnection::AddTrackPlanB(
1236 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001237 const std::vector<std::string>& stream_ids) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07001238 if (stream_ids.size() > 1u) {
1239 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_OPERATION,
1240 "AddTrack with more than one stream is not "
1241 "supported with Plan B semantics.");
1242 }
1243 std::vector<std::string> adjusted_stream_ids = stream_ids;
1244 if (adjusted_stream_ids.empty()) {
1245 adjusted_stream_ids.push_back(rtc::CreateRandomUuid());
1246 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001247 cricket::MediaType media_type =
1248 (track->kind() == MediaStreamTrackInterface::kAudioKind
1249 ? cricket::MEDIA_TYPE_AUDIO
1250 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton111fdfd2018-06-25 13:03:36 -07001251 auto new_sender =
Florent Castelli892acf02018-10-01 22:47:20 +02001252 CreateSender(media_type, track->id(), track, adjusted_stream_ids, {});
deadbeefe1f9d832016-01-14 15:35:42 -08001253 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
Steve Anton57858b32018-02-15 15:19:50 -08001254 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001255 GetAudioTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001256 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001257 FindSenderInfo(local_audio_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001258 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001259 if (sender_info) {
1260 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001261 }
Steve Antonf9381f02017-12-14 10:23:57 -08001262 } else {
1263 RTC_DCHECK_EQ(MediaStreamTrackInterface::kVideoKind, track->kind());
Steve Anton57858b32018-02-15 15:19:50 -08001264 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08001265 GetVideoTransceiver()->internal()->AddSender(new_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001266 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00001267 FindSenderInfo(local_video_sender_infos_,
Seth Hampson5b4f0752018-04-02 16:31:36 -07001268 new_sender->internal()->stream_ids()[0], track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08001269 if (sender_info) {
1270 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001271 }
deadbeefe1f9d832016-01-14 15:35:42 -08001272 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001273 return rtc::scoped_refptr<RtpSenderInterface>(new_sender);
Steve Antonf9381f02017-12-14 10:23:57 -08001274}
deadbeefe1f9d832016-01-14 15:35:42 -08001275
Steve Antonf9381f02017-12-14 10:23:57 -08001276RTCErrorOr<rtc::scoped_refptr<RtpSenderInterface>>
1277PeerConnection::AddTrackUnifiedPlan(
1278 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Seth Hampson845e8782018-03-02 11:34:10 -08001279 const std::vector<std::string>& stream_ids) {
Steve Antonf9381f02017-12-14 10:23:57 -08001280 auto transceiver = FindFirstTransceiverForAddedTrack(track);
1281 if (transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07001282 RTC_LOG(LS_INFO) << "Reusing an existing "
1283 << cricket::MediaTypeToString(transceiver->media_type())
1284 << " transceiver for AddTrack.";
Steve Antonf9381f02017-12-14 10:23:57 -08001285 if (transceiver->direction() == RtpTransceiverDirection::kRecvOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001286 transceiver->internal()->set_direction(
1287 RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001288 } else if (transceiver->direction() == RtpTransceiverDirection::kInactive) {
Steve Anton52d86772018-02-20 15:48:12 -08001289 transceiver->internal()->set_direction(
1290 RtpTransceiverDirection::kSendOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001291 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001292 transceiver->sender()->SetTrack(track);
Seth Hampson845e8782018-03-02 11:34:10 -08001293 transceiver->internal()->sender_internal()->set_stream_ids(stream_ids);
Steve Antonf9381f02017-12-14 10:23:57 -08001294 } else {
1295 cricket::MediaType media_type =
1296 (track->kind() == MediaStreamTrackInterface::kAudioKind
1297 ? cricket::MEDIA_TYPE_AUDIO
1298 : cricket::MEDIA_TYPE_VIDEO);
Steve Anton3d954a62018-04-02 11:27:23 -07001299 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1300 << " transceiver in response to a call to AddTrack.";
Steve Anton07563732018-06-26 11:13:50 -07001301 std::string sender_id = track->id();
1302 // Avoid creating a sender with an existing ID by generating a random ID.
1303 // This can happen if this is the second time AddTrack has created a sender
1304 // for this track.
1305 if (FindSenderById(sender_id)) {
1306 sender_id = rtc::CreateRandomUuid();
1307 }
Florent Castelli892acf02018-10-01 22:47:20 +02001308 auto sender = CreateSender(media_type, sender_id, track, stream_ids, {});
Steve Anton02ee47c2018-01-10 16:26:06 -08001309 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1310 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antonf9381f02017-12-14 10:23:57 -08001311 transceiver->internal()->set_created_by_addtrack(true);
Steve Anton52d86772018-02-20 15:48:12 -08001312 transceiver->internal()->set_direction(RtpTransceiverDirection::kSendRecv);
Steve Antonf9381f02017-12-14 10:23:57 -08001313 }
Steve Antonf9381f02017-12-14 10:23:57 -08001314 return transceiver->sender();
1315}
1316
1317rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1318PeerConnection::FindFirstTransceiverForAddedTrack(
1319 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1320 RTC_DCHECK(track);
1321 for (auto transceiver : transceivers_) {
1322 if (!transceiver->sender()->track() &&
Steve Anton69470252018-02-09 11:43:08 -08001323 cricket::MediaTypeToString(transceiver->media_type()) ==
Steve Antonf9381f02017-12-14 10:23:57 -08001324 track->kind() &&
Seth Hampson2f0d7022018-02-20 11:54:42 -08001325 !transceiver->internal()->has_ever_been_used_to_send() &&
1326 !transceiver->stopped()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001327 return transceiver;
1328 }
1329 }
1330 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001331}
1332
1333bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1334 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
Steve Anton24db5732018-07-23 10:27:33 -07001335 return RemoveTrackNew(sender).ok();
Steve Antonf9381f02017-12-14 10:23:57 -08001336}
1337
Steve Anton24db5732018-07-23 10:27:33 -07001338RTCError PeerConnection::RemoveTrackNew(
Steve Antonf9381f02017-12-14 10:23:57 -08001339 rtc::scoped_refptr<RtpSenderInterface> sender) {
1340 if (!sender) {
1341 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "Sender is null.");
1342 }
deadbeefe1f9d832016-01-14 15:35:42 -08001343 if (IsClosed()) {
Steve Antonf9381f02017-12-14 10:23:57 -08001344 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_STATE,
1345 "PeerConnection is closed.");
deadbeefe1f9d832016-01-14 15:35:42 -08001346 }
Steve Antonf9381f02017-12-14 10:23:57 -08001347 if (IsUnifiedPlan()) {
1348 auto transceiver = FindTransceiverBySender(sender);
1349 if (!transceiver || !sender->track()) {
1350 return RTCError::OK();
1351 }
1352 sender->SetTrack(nullptr);
1353 if (transceiver->direction() == RtpTransceiverDirection::kSendRecv) {
Steve Anton52d86772018-02-20 15:48:12 -08001354 transceiver->internal()->set_direction(
1355 RtpTransceiverDirection::kRecvOnly);
Steve Antonf9381f02017-12-14 10:23:57 -08001356 } else if (transceiver->direction() == RtpTransceiverDirection::kSendOnly) {
Steve Anton52d86772018-02-20 15:48:12 -08001357 transceiver->internal()->set_direction(
1358 RtpTransceiverDirection::kInactive);
Steve Antonf9381f02017-12-14 10:23:57 -08001359 }
Steve Anton4171afb2017-11-20 10:20:22 -08001360 } else {
Steve Antonf9381f02017-12-14 10:23:57 -08001361 bool removed;
1362 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1363 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1364 } else {
1365 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1366 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1367 }
1368 if (!removed) {
1369 LOG_AND_RETURN_ERROR(
1370 RTCErrorType::INVALID_PARAMETER,
1371 "Couldn't find sender " + sender->id() + " to remove.");
1372 }
Steve Anton4171afb2017-11-20 10:20:22 -08001373 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001374 Observer()->OnRenegotiationNeeded();
Steve Antonf9381f02017-12-14 10:23:57 -08001375 return RTCError::OK();
1376}
1377
1378rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1379PeerConnection::FindTransceiverBySender(
1380 rtc::scoped_refptr<RtpSenderInterface> sender) {
1381 for (auto transceiver : transceivers_) {
1382 if (transceiver->sender() == sender) {
1383 return transceiver;
1384 }
1385 }
1386 return nullptr;
deadbeefe1f9d832016-01-14 15:35:42 -08001387}
1388
Steve Anton9158ef62017-11-27 13:01:52 -08001389RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1390PeerConnection::AddTransceiver(
1391 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1392 return AddTransceiver(track, RtpTransceiverInit());
1393}
1394
1395RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1396PeerConnection::AddTransceiver(
1397 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1398 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001399 RTC_CHECK(IsUnifiedPlan())
1400 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001401 if (!track) {
1402 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1403 }
1404 cricket::MediaType media_type;
1405 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1406 media_type = cricket::MEDIA_TYPE_AUDIO;
1407 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1408 media_type = cricket::MEDIA_TYPE_VIDEO;
1409 } else {
1410 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1411 "Track kind is not audio or video");
1412 }
1413 return AddTransceiver(media_type, track, init);
1414}
1415
1416RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1417PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1418 return AddTransceiver(media_type, RtpTransceiverInit());
1419}
1420
1421RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1422PeerConnection::AddTransceiver(cricket::MediaType media_type,
1423 const RtpTransceiverInit& init) {
Steve Antonfc853712018-03-01 13:48:58 -08001424 RTC_CHECK(IsUnifiedPlan())
1425 << "AddTransceiver is only available with Unified Plan SdpSemantics";
Steve Anton9158ef62017-11-27 13:01:52 -08001426 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1427 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1428 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1429 "media type is not audio or video");
1430 }
1431 return AddTransceiver(media_type, nullptr, init);
1432}
1433
1434RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1435PeerConnection::AddTransceiver(
1436 cricket::MediaType media_type,
1437 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Steve Anton22da89f2018-01-25 13:58:07 -08001438 const RtpTransceiverInit& init,
1439 bool fire_callback) {
Steve Anton9158ef62017-11-27 13:01:52 -08001440 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1441 media_type == cricket::MEDIA_TYPE_VIDEO));
1442 if (track) {
1443 RTC_DCHECK_EQ(media_type,
1444 (track->kind() == MediaStreamTrackInterface::kAudioKind
1445 ? cricket::MEDIA_TYPE_AUDIO
1446 : cricket::MEDIA_TYPE_VIDEO));
1447 }
1448
1449 // TODO(bugs.webrtc.org/7600): Verify init.
Florent Castelli892acf02018-10-01 22:47:20 +02001450 if (init.send_encodings.size() > 1) {
1451 LOG_AND_RETURN_ERROR(
1452 RTCErrorType::UNSUPPORTED_PARAMETER,
1453 "Attempted to create an encoder with more than 1 encoding parameter.");
1454 }
1455
1456 for (const auto& encoding : init.send_encodings) {
1457 if (encoding.ssrc.has_value()) {
1458 LOG_AND_RETURN_ERROR(
1459 RTCErrorType::UNSUPPORTED_PARAMETER,
1460 "Attempted to set an unimplemented parameter of RtpParameters.");
1461 }
1462 }
1463
1464 RtpParameters parameters;
1465 parameters.encodings = init.send_encodings;
1466 if (UnimplementedRtpParameterHasValue(parameters)) {
1467 LOG_AND_RETURN_ERROR(
1468 RTCErrorType::UNSUPPORTED_PARAMETER,
1469 "Attempted to set an unimplemented parameter of RtpParameters.");
1470 }
Steve Anton9158ef62017-11-27 13:01:52 -08001471
Steve Anton3d954a62018-04-02 11:27:23 -07001472 RTC_LOG(LS_INFO) << "Adding " << cricket::MediaTypeToString(media_type)
1473 << " transceiver in response to a call to AddTransceiver.";
Steve Anton07563732018-06-26 11:13:50 -07001474 // Set the sender ID equal to the track ID if the track is specified unless
1475 // that sender ID is already in use.
1476 std::string sender_id =
1477 (track && !FindSenderById(track->id()) ? track->id()
1478 : rtc::CreateRandomUuid());
Florent Castelli892acf02018-10-01 22:47:20 +02001479 auto sender = CreateSender(media_type, sender_id, track, init.stream_ids,
1480 init.send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001481 auto receiver = CreateReceiver(media_type, rtc::CreateRandomUuid());
1482 auto transceiver = CreateAndAddTransceiver(sender, receiver);
1483 transceiver->internal()->set_direction(init.direction);
1484
Steve Anton22da89f2018-01-25 13:58:07 -08001485 if (fire_callback) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001486 Observer()->OnRenegotiationNeeded();
Steve Anton22da89f2018-01-25 13:58:07 -08001487 }
Steve Antonf9381f02017-12-14 10:23:57 -08001488
1489 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1490}
1491
Steve Anton02ee47c2018-01-10 16:26:06 -08001492rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
1493PeerConnection::CreateSender(
1494 cricket::MediaType media_type,
Steve Anton111fdfd2018-06-25 13:03:36 -07001495 const std::string& id,
Steve Anton02ee47c2018-01-10 16:26:06 -08001496 rtc::scoped_refptr<MediaStreamTrackInterface> track,
Florent Castelli892acf02018-10-01 22:47:20 +02001497 const std::vector<std::string>& stream_ids,
1498 const std::vector<RtpEncodingParameters>& send_encodings) {
Steve Anton9158ef62017-11-27 13:01:52 -08001499 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
Steve Anton02ee47c2018-01-10 16:26:06 -08001500 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1501 RTC_DCHECK(!track ||
1502 (track->kind() == MediaStreamTrackInterface::kAudioKind));
1503 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1504 signaling_thread(),
Steve Anton111fdfd2018-06-25 13:03:36 -07001505 new AudioRtpSender(worker_thread(), id, stats_.get()));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001506 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001507 } else {
1508 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
1509 RTC_DCHECK(!track ||
1510 (track->kind() == MediaStreamTrackInterface::kVideoKind));
1511 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton111fdfd2018-06-25 13:03:36 -07001512 signaling_thread(), new VideoRtpSender(worker_thread(), id));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001513 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton02ee47c2018-01-10 16:26:06 -08001514 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001515 bool set_track_succeeded = sender->SetTrack(track);
1516 RTC_DCHECK(set_track_succeeded);
1517 sender->internal()->set_stream_ids(stream_ids);
Florent Castelli892acf02018-10-01 22:47:20 +02001518 sender->internal()->set_init_send_encodings(send_encodings);
Steve Anton02ee47c2018-01-10 16:26:06 -08001519 return sender;
1520}
1521
1522rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1523PeerConnection::CreateReceiver(cricket::MediaType media_type,
1524 const std::string& receiver_id) {
Steve Anton9158ef62017-11-27 13:01:52 -08001525 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1526 receiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001527 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton9158ef62017-11-27 13:01:52 -08001528 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001529 signaling_thread(), new AudioRtpReceiver(worker_thread(), receiver_id,
1530 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001531 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001532 } else {
Steve Anton02ee47c2018-01-10 16:26:06 -08001533 RTC_DCHECK_EQ(media_type, cricket::MEDIA_TYPE_VIDEO);
Steve Anton9158ef62017-11-27 13:01:52 -08001534 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Henrik Boström199e27b2018-07-04 20:51:53 +02001535 signaling_thread(), new VideoRtpReceiver(worker_thread(), receiver_id,
1536 std::vector<std::string>({})));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001537 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
Steve Anton9158ef62017-11-27 13:01:52 -08001538 }
Steve Anton02ee47c2018-01-10 16:26:06 -08001539 return receiver;
1540}
1541
1542rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1543PeerConnection::CreateAndAddTransceiver(
1544 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender,
1545 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1546 receiver) {
Steve Anton07563732018-06-26 11:13:50 -07001547 // Ensure that the new sender does not have an ID that is already in use by
1548 // another sender.
1549 // Allow receiver IDs to conflict since those come from remote SDP (which
1550 // could be invalid, but should not cause a crash).
1551 RTC_DCHECK(!FindSenderById(sender->id()));
Steve Anton02ee47c2018-01-10 16:26:06 -08001552 auto transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1553 signaling_thread(), new RtpTransceiver(sender, receiver));
Steve Anton9158ef62017-11-27 13:01:52 -08001554 transceivers_.push_back(transceiver);
Steve Anton52d86772018-02-20 15:48:12 -08001555 transceiver->internal()->SignalNegotiationNeeded.connect(
1556 this, &PeerConnection::OnNegotiationNeeded);
Steve Antonf9381f02017-12-14 10:23:57 -08001557 return transceiver;
Steve Anton9158ef62017-11-27 13:01:52 -08001558}
1559
Steve Anton52d86772018-02-20 15:48:12 -08001560void PeerConnection::OnNegotiationNeeded() {
1561 RTC_DCHECK_RUN_ON(signaling_thread());
1562 RTC_DCHECK(!IsClosed());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001563 Observer()->OnRenegotiationNeeded();
Steve Anton52d86772018-02-20 15:48:12 -08001564}
1565
deadbeeffac06552015-11-25 11:26:01 -08001566rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001567 const std::string& kind,
1568 const std::string& stream_id) {
Steve Antonfc853712018-03-01 13:48:58 -08001569 RTC_CHECK(!IsUnifiedPlan()) << "CreateSender is not available with Unified "
1570 "Plan SdpSemantics. Please use AddTransceiver "
1571 "instead.";
Peter Boström1a9d6152015-12-08 22:15:17 +01001572 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001573 if (IsClosed()) {
1574 return nullptr;
1575 }
Steve Anton4171afb2017-11-20 10:20:22 -08001576
Seth Hampson5b4f0752018-04-02 16:31:36 -07001577 // Internally we need to have one stream with Plan B semantics, so we
1578 // generate a random stream ID if not specified.
Seth Hampson845e8782018-03-02 11:34:10 -08001579 std::vector<std::string> stream_ids;
Seth Hampson5b4f0752018-04-02 16:31:36 -07001580 if (stream_id.empty()) {
1581 stream_ids.push_back(rtc::CreateRandomUuid());
1582 RTC_LOG(LS_INFO)
1583 << "No stream_id specified for sender. Generated stream ID: "
1584 << stream_ids[0];
1585 } else {
Seth Hampson845e8782018-03-02 11:34:10 -08001586 stream_ids.push_back(stream_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08001587 }
1588
Steve Anton4171afb2017-11-20 10:20:22 -08001589 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001590 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001591 if (kind == MediaStreamTrackInterface::kAudioKind) {
Steve Anton111fdfd2018-06-25 13:03:36 -07001592 auto* audio_sender = new AudioRtpSender(
1593 worker_thread(), rtc::CreateRandomUuid(), stats_.get());
Steve Anton57858b32018-02-15 15:19:50 -08001594 audio_sender->SetVoiceMediaChannel(voice_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001595 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001596 signaling_thread(), audio_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001597 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001598 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
Steve Anton47136dd2018-01-12 10:49:35 -08001599 auto* video_sender =
Steve Anton111fdfd2018-06-25 13:03:36 -07001600 new VideoRtpSender(worker_thread(), rtc::CreateRandomUuid());
Steve Anton57858b32018-02-15 15:19:50 -08001601 video_sender->SetVideoMediaChannel(video_media_channel());
deadbeefa601f5c2016-06-06 14:27:39 -07001602 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton02ee47c2018-01-10 16:26:06 -08001603 signaling_thread(), video_sender);
Steve Anton4171afb2017-11-20 10:20:22 -08001604 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001605 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001606 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001607 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001608 }
Steve Anton111fdfd2018-06-25 13:03:36 -07001609 new_sender->internal()->set_stream_ids(stream_ids);
Steve Anton4171afb2017-11-20 10:20:22 -08001610
deadbeefe1f9d832016-01-14 15:35:42 -08001611 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001612}
1613
deadbeef70ab1a12015-09-28 16:53:55 -07001614std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1615 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001616 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001617 for (auto sender : GetSendersInternal()) {
1618 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001619 }
1620 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001621}
1622
Steve Anton4171afb2017-11-20 10:20:22 -08001623std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1624PeerConnection::GetSendersInternal() const {
1625 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1626 all_senders;
1627 for (auto transceiver : transceivers_) {
1628 auto senders = transceiver->internal()->senders();
1629 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1630 }
1631 return all_senders;
1632}
1633
deadbeef70ab1a12015-09-28 16:53:55 -07001634std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1635PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001636 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001637 for (const auto& receiver : GetReceiversInternal()) {
1638 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001639 }
1640 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001641}
1642
Steve Anton4171afb2017-11-20 10:20:22 -08001643std::vector<
1644 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1645PeerConnection::GetReceiversInternal() const {
1646 std::vector<
1647 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1648 all_receivers;
1649 for (auto transceiver : transceivers_) {
1650 auto receivers = transceiver->internal()->receivers();
1651 all_receivers.insert(all_receivers.end(), receivers.begin(),
1652 receivers.end());
1653 }
1654 return all_receivers;
1655}
1656
Steve Anton9158ef62017-11-27 13:01:52 -08001657std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1658PeerConnection::GetTransceivers() const {
Steve Antonfc853712018-03-01 13:48:58 -08001659 RTC_CHECK(IsUnifiedPlan())
1660 << "GetTransceivers is only supported with Unified Plan SdpSemantics.";
Steve Anton9158ef62017-11-27 13:01:52 -08001661 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1662 for (auto transceiver : transceivers_) {
1663 all_transceivers.push_back(transceiver);
1664 }
1665 return all_transceivers;
1666}
1667
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001668bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001669 MediaStreamTrackInterface* track,
1670 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001671 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001672 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001673 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001674 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001675 return false;
1676 }
1677
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001678 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001679 // The StatsCollector is used to tell if a track is valid because it may
1680 // remember tracks that the PeerConnection previously removed.
1681 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001682 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1683 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001684 return false;
1685 }
Steve Antonad182762018-09-05 20:22:40 +00001686 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
1687 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001688 return true;
1689}
1690
hbos74e1a4f2016-09-15 23:33:01 -07001691void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
Henrik Boström1df1bf82018-03-20 13:24:20 +01001692 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
hbos74e1a4f2016-09-15 23:33:01 -07001693 RTC_DCHECK(stats_collector_);
Henrik Boström1df1bf82018-03-20 13:24:20 +01001694 RTC_DCHECK(callback);
hbos74e1a4f2016-09-15 23:33:01 -07001695 stats_collector_->GetStatsReport(callback);
1696}
1697
Henrik Boström1df1bf82018-03-20 13:24:20 +01001698void PeerConnection::GetStats(
1699 rtc::scoped_refptr<RtpSenderInterface> selector,
1700 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1701 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1702 RTC_DCHECK(callback);
1703 RTC_DCHECK(stats_collector_);
1704 rtc::scoped_refptr<RtpSenderInternal> internal_sender;
1705 if (selector) {
1706 for (const auto& proxy_transceiver : transceivers_) {
1707 for (const auto& proxy_sender :
1708 proxy_transceiver->internal()->senders()) {
1709 if (proxy_sender == selector) {
1710 internal_sender = proxy_sender->internal();
1711 break;
1712 }
1713 }
1714 if (internal_sender)
1715 break;
1716 }
1717 }
1718 // If there is no |internal_sender| then |selector| is either null or does not
1719 // belong to the PeerConnection (in Plan B, senders can be removed from the
1720 // PeerConnection). This means that "all the stats objects representing the
1721 // selector" is an empty set. Invoking GetStatsReport() with a null selector
1722 // produces an empty stats report.
1723 stats_collector_->GetStatsReport(internal_sender, callback);
1724}
1725
1726void PeerConnection::GetStats(
1727 rtc::scoped_refptr<RtpReceiverInterface> selector,
1728 rtc::scoped_refptr<RTCStatsCollectorCallback> callback) {
1729 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
1730 RTC_DCHECK(callback);
1731 RTC_DCHECK(stats_collector_);
1732 rtc::scoped_refptr<RtpReceiverInternal> internal_receiver;
1733 if (selector) {
1734 for (const auto& proxy_transceiver : transceivers_) {
1735 for (const auto& proxy_receiver :
1736 proxy_transceiver->internal()->receivers()) {
1737 if (proxy_receiver == selector) {
1738 internal_receiver = proxy_receiver->internal();
1739 break;
1740 }
1741 }
1742 if (internal_receiver)
1743 break;
1744 }
1745 }
1746 // If there is no |internal_receiver| then |selector| is either null or does
1747 // not belong to the PeerConnection (in Plan B, receivers can be removed from
1748 // the PeerConnection). This means that "all the stats objects representing
1749 // the selector" is an empty set. Invoking GetStatsReport() with a null
1750 // selector produces an empty stats report.
1751 stats_collector_->GetStatsReport(internal_receiver, callback);
1752}
1753
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001754PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1755 return signaling_state_;
1756}
1757
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001758PeerConnectionInterface::IceConnectionState
1759PeerConnection::ice_connection_state() {
1760 return ice_connection_state_;
1761}
1762
Jonas Olsson635474e2018-10-18 15:58:17 +02001763PeerConnectionInterface::IceConnectionState
1764PeerConnection::standardized_ice_connection_state() {
1765 return standardized_ice_connection_state_;
1766}
1767
1768PeerConnectionInterface::PeerConnectionState
1769PeerConnection::peer_connection_state() {
1770 return connection_state_;
1771}
1772
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001773PeerConnectionInterface::IceGatheringState
1774PeerConnection::ice_gathering_state() {
1775 return ice_gathering_state_;
1776}
1777
Yves Gerey665174f2018-06-19 15:03:05 +02001778rtc::scoped_refptr<DataChannelInterface> PeerConnection::CreateDataChannel(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001779 const std::string& label,
1780 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001781 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001782
deadbeefab9b2d12015-10-14 11:33:11 -07001783 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001784
kwibergd1fe2812016-04-27 06:47:29 -07001785 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001786 if (config) {
1787 internal_config.reset(new InternalDataChannelInit(*config));
1788 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001789 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001790 InternalCreateDataChannel(label, internal_config.get()));
1791 if (!channel.get()) {
1792 return nullptr;
1793 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001794
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001795 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1796 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001797 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02001798 Observer()->OnRenegotiationNeeded();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001799 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02001800 NoteUsageEvent(UsageEvent::DATA_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001801 return DataChannelProxy::Create(signaling_thread(), channel.get());
1802}
1803
1804void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001805 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001806 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001807
nisse7ce109a2017-01-31 00:57:56 -08001808 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001809 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001810 return;
1811 }
deadbeefab9b2d12015-10-14 11:33:11 -07001812
Steve Anton8d3444d2017-10-20 15:30:51 -07001813 if (IsClosed()) {
1814 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001815 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001816 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001817 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001818 return;
1819 }
1820
zhihuang1c378ed2017-08-17 14:10:50 -07001821 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001822 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001823 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001824 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001825 observer, RTCError(RTCErrorType::INVALID_PARAMETER, std::move(error)));
deadbeefab9b2d12015-10-14 11:33:11 -07001826 return;
1827 }
1828
Steve Anton22da89f2018-01-25 13:58:07 -08001829 // Legacy handling for offer_to_receive_audio and offer_to_receive_video.
1830 // Specified in WebRTC section 4.4.3.2 "Legacy configuration extensions".
1831 if (IsUnifiedPlan()) {
1832 RTCError error = HandleLegacyOfferOptions(options);
1833 if (!error.ok()) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001834 PostCreateSessionDescriptionFailure(observer, std::move(error));
Steve Anton22da89f2018-01-25 13:58:07 -08001835 return;
1836 }
1837 }
1838
zhihuang1c378ed2017-08-17 14:10:50 -07001839 cricket::MediaSessionOptions session_options;
1840 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001841 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001842}
1843
Steve Anton22da89f2018-01-25 13:58:07 -08001844RTCError PeerConnection::HandleLegacyOfferOptions(
1845 const RTCOfferAnswerOptions& options) {
1846 RTC_DCHECK(IsUnifiedPlan());
1847
1848 if (options.offer_to_receive_audio == 0) {
1849 RemoveRecvDirectionFromReceivingTransceiversOfType(
1850 cricket::MEDIA_TYPE_AUDIO);
1851 } else if (options.offer_to_receive_audio == 1) {
1852 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_AUDIO);
1853 } else if (options.offer_to_receive_audio > 1) {
1854 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1855 "offer_to_receive_audio > 1 is not supported.");
1856 }
1857
1858 if (options.offer_to_receive_video == 0) {
1859 RemoveRecvDirectionFromReceivingTransceiversOfType(
1860 cricket::MEDIA_TYPE_VIDEO);
1861 } else if (options.offer_to_receive_video == 1) {
1862 AddUpToOneReceivingTransceiverOfType(cricket::MEDIA_TYPE_VIDEO);
1863 } else if (options.offer_to_receive_video > 1) {
1864 LOG_AND_RETURN_ERROR(RTCErrorType::UNSUPPORTED_PARAMETER,
1865 "offer_to_receive_video > 1 is not supported.");
1866 }
1867
1868 return RTCError::OK();
1869}
1870
1871void PeerConnection::RemoveRecvDirectionFromReceivingTransceiversOfType(
1872 cricket::MediaType media_type) {
1873 for (auto transceiver : GetReceivingTransceiversOfType(media_type)) {
Steve Anton3d954a62018-04-02 11:27:23 -07001874 RtpTransceiverDirection new_direction =
1875 RtpTransceiverDirectionWithRecvSet(transceiver->direction(), false);
1876 if (new_direction != transceiver->direction()) {
1877 RTC_LOG(LS_INFO) << "Changing " << cricket::MediaTypeToString(media_type)
1878 << " transceiver (MID="
1879 << transceiver->mid().value_or("<not set>") << ") from "
1880 << RtpTransceiverDirectionToString(
1881 transceiver->direction())
1882 << " to "
1883 << RtpTransceiverDirectionToString(new_direction)
1884 << " since CreateOffer specified offer_to_receive=0";
1885 transceiver->internal()->set_direction(new_direction);
1886 }
Steve Anton22da89f2018-01-25 13:58:07 -08001887 }
1888}
1889
1890void PeerConnection::AddUpToOneReceivingTransceiverOfType(
1891 cricket::MediaType media_type) {
1892 if (GetReceivingTransceiversOfType(media_type).empty()) {
Steve Anton3d954a62018-04-02 11:27:23 -07001893 RTC_LOG(LS_INFO)
1894 << "Adding one recvonly " << cricket::MediaTypeToString(media_type)
1895 << " transceiver since CreateOffer specified offer_to_receive=1";
Steve Anton22da89f2018-01-25 13:58:07 -08001896 RtpTransceiverInit init;
1897 init.direction = RtpTransceiverDirection::kRecvOnly;
1898 AddTransceiver(media_type, nullptr, init, /*fire_callback=*/false);
1899 }
1900}
1901
1902std::vector<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1903PeerConnection::GetReceivingTransceiversOfType(cricket::MediaType media_type) {
1904 std::vector<
1905 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
1906 receiving_transceivers;
1907 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08001908 if (!transceiver->stopped() && transceiver->media_type() == media_type &&
Steve Anton22da89f2018-01-25 13:58:07 -08001909 RtpTransceiverDirectionHasRecv(transceiver->direction())) {
1910 receiving_transceivers.push_back(transceiver);
1911 }
1912 }
1913 return receiving_transceivers;
1914}
1915
htaa2a49d92016-03-04 02:51:39 -08001916void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1917 const RTCOfferAnswerOptions& options) {
1918 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001919 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001920 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001921 return;
1922 }
1923
Steve Antondffead82018-02-06 10:31:29 -08001924 if (!(signaling_state_ == kHaveRemoteOffer ||
1925 signaling_state_ == kHaveLocalPrAnswer)) {
1926 std::string error =
1927 "PeerConnection cannot create an answer in a state other than "
1928 "have-remote-offer or have-local-pranswer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001929 RTC_LOG(LS_ERROR) << error;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001930 PostCreateSessionDescriptionFailure(
Harald Alvestrand3725d542018-04-13 15:02:10 +02001931 observer, RTCError(RTCErrorType::INVALID_STATE, std::move(error)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001932 return;
1933 }
1934
Steve Antondffead82018-02-06 10:31:29 -08001935 // The remote description should be set if we're in the right state.
1936 RTC_DCHECK(remote_description());
Steve Anton8d3444d2017-10-20 15:30:51 -07001937
Steve Anton22da89f2018-01-25 13:58:07 -08001938 if (IsUnifiedPlan()) {
1939 if (options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1940 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_audio is not "
1941 "supported with Unified Plan semantics. Use the "
1942 "RtpTransceiver API instead.";
1943 }
1944 if (options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1945 RTC_LOG(LS_WARNING) << "CreateAnswer: offer_to_receive_video is not "
1946 "supported with Unified Plan semantics. Use the "
1947 "RtpTransceiver API instead.";
1948 }
1949 }
1950
htaa2a49d92016-03-04 02:51:39 -08001951 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001952 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001953
Steve Antond25da372017-11-06 14:50:29 -08001954 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955}
1956
1957void PeerConnection::SetLocalDescription(
1958 SetSessionDescriptionObserver* observer,
Steve Anton80dd7b52018-02-16 17:08:42 -08001959 SessionDescriptionInterface* desc_ptr) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001960 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001961
Steve Anton80dd7b52018-02-16 17:08:42 -08001962 // The SetLocalDescription contract is that we take ownership of the session
1963 // description regardless of the outcome, so wrap it in a unique_ptr right
1964 // away. Ideally, SetLocalDescription's signature will be changed to take the
1965 // description as a unique_ptr argument to formalize this agreement.
1966 std::unique_ptr<SessionDescriptionInterface> desc(desc_ptr);
1967
nisse7ce109a2017-01-31 00:57:56 -08001968 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001969 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001970 return;
1971 }
Steve Anton8a006912017-12-04 15:25:56 -08001972
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001973 if (!desc) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001974 PostSetSessionDescriptionFailure(
1975 observer,
1976 RTCError(RTCErrorType::INTERNAL_ERROR, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 return;
1978 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001979
Steve Anton80dd7b52018-02-16 17:08:42 -08001980 // If a session error has occurred the PeerConnection is in a possibly
1981 // inconsistent state so fail right away.
1982 if (session_error() != SessionError::kNone) {
1983 std::string error_message = GetSessionErrorMsg();
1984 RTC_LOG(LS_ERROR) << "SetLocalDescription: " << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001985 PostSetSessionDescriptionFailure(
1986 observer,
1987 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001988 return;
1989 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001990
Steve Anton80dd7b52018-02-16 17:08:42 -08001991 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1992 if (!error.ok()) {
1993 std::string error_message = GetSetDescriptionErrorMessage(
1994 cricket::CS_LOCAL, desc->GetType(), error);
1995 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01001996 PostSetSessionDescriptionFailure(
1997 observer,
1998 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton80dd7b52018-02-16 17:08:42 -08001999 return;
2000 }
2001
2002 // Grab the description type before moving ownership to ApplyLocalDescription,
2003 // which may destroy it before returning.
2004 const SdpType type = desc->GetType();
2005
2006 error = ApplyLocalDescription(std::move(desc));
Steve Anton8a006912017-12-04 15:25:56 -08002007 // |desc| may be destroyed at this point.
2008
2009 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002010 // If ApplyLocalDescription fails, the PeerConnection could be in an
2011 // inconsistent state, so act conservatively here and set the session error
2012 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2013 SetSessionError(SessionError::kContent, error.message());
2014 std::string error_message =
2015 GetSetDescriptionErrorMessage(cricket::CS_LOCAL, type, error);
2016 RTC_LOG(LS_ERROR) << error_message;
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01002017 PostSetSessionDescriptionFailure(
2018 observer,
2019 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07002020 return;
2021 }
Steve Anton8a006912017-12-04 15:25:56 -08002022 RTC_DCHECK(local_description());
2023
2024 PostSetSessionDescriptionSuccess(observer);
2025
Steve Antonad182762018-09-05 20:22:40 +00002026 // MaybeStartGathering needs to be called after posting
2027 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
2028 // before signaling that SetLocalDescription completed.
Steve Anton8a006912017-12-04 15:25:56 -08002029 transport_controller_->MaybeStartGathering();
2030
Steve Antona3a92c22017-12-07 10:27:41 -08002031 if (local_description()->GetType() == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002032 // TODO(deadbeef): We already had to hop to the network thread for
2033 // MaybeStartGathering...
2034 network_thread()->Invoke<void>(
2035 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2036 port_allocator_.get()));
Steve Anton0ffaaa22018-02-23 10:31:30 -08002037 // Make UMA notes about what was agreed to.
2038 ReportNegotiatedSdpSemantics(*local_description());
Steve Anton8a006912017-12-04 15:25:56 -08002039 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002040 NoteUsageEvent(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002041}
2042
2043RTCError PeerConnection::ApplyLocalDescription(
2044 std::unique_ptr<SessionDescriptionInterface> desc) {
2045 RTC_DCHECK_RUN_ON(signaling_thread());
2046 RTC_DCHECK(desc);
2047
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048 // Update stats here so that we have the most recent stats for tracks and
2049 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002050 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002051
Steve Antondcc3c022017-12-22 16:02:54 -08002052 // Take a reference to the old local description since it's used below to
2053 // compare against the new local description. When setting the new local
2054 // description, grab ownership of the replaced session description in case it
2055 // is the same as |old_local_description|, to keep it alive for the duration
2056 // of the method.
2057 const SessionDescriptionInterface* old_local_description =
2058 local_description();
2059 std::unique_ptr<SessionDescriptionInterface> replaced_local_description;
Zhi Huange830e682018-03-30 10:48:35 -07002060 SdpType type = desc->GetType();
Steve Anton3828c062017-12-06 10:34:51 -08002061 if (type == SdpType::kAnswer) {
Steve Antondcc3c022017-12-22 16:02:54 -08002062 replaced_local_description = pending_local_description_
2063 ? std::move(pending_local_description_)
2064 : std::move(current_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002065 current_local_description_ = std::move(desc);
2066 pending_local_description_ = nullptr;
2067 current_remote_description_ = std::move(pending_remote_description_);
2068 } else {
Steve Antondcc3c022017-12-22 16:02:54 -08002069 replaced_local_description = std::move(pending_local_description_);
Steve Anton8a006912017-12-04 15:25:56 -08002070 pending_local_description_ = std::move(desc);
2071 }
2072 // The session description to apply now must be accessed by
2073 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002074 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07002075
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002076 if (!is_caller_) {
2077 if (remote_description()) {
2078 // Remote description was applied first, so this PC is the callee.
2079 is_caller_ = false;
2080 } else {
2081 // Local description is applied first, so this PC is the caller.
2082 is_caller_ = true;
2083 }
2084 }
2085
Zhi Huange830e682018-03-30 10:48:35 -07002086 RTCError error = PushdownTransportDescription(cricket::CS_LOCAL, type);
2087 if (!error.ok()) {
2088 return error;
2089 }
2090
Steve Antondcc3c022017-12-22 16:02:54 -08002091 if (IsUnifiedPlan()) {
2092 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002093 cricket::CS_LOCAL, *local_description(), old_local_description,
2094 remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002095 if (!error.ok()) {
2096 return error;
2097 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002098 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
2099 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002100 for (auto transceiver : transceivers_) {
2101 const ContentInfo* content =
2102 FindMediaSectionForTransceiver(transceiver, local_description());
2103 if (!content) {
2104 continue;
2105 }
2106 const MediaContentDescription* media_desc = content->media_description();
Steve Anton0f5400a2018-07-17 14:25:36 -07002107 // 2.2.7.1.6: If description is of type "answer" or "pranswer", then run
2108 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002109 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002110 // 2.2.7.1.6.1: If direction is "sendonly" or "inactive", and
2111 // transceiver's [[FiredDirection]] slot is either "sendrecv" or
2112 // "recvonly", process the removal of a remote track for the media
2113 // description, given transceiver, removeList, and muteTracks.
2114 if (!RtpTransceiverDirectionHasRecv(media_desc->direction()) &&
2115 (transceiver->internal()->fired_direction() &&
2116 RtpTransceiverDirectionHasRecv(
2117 *transceiver->internal()->fired_direction()))) {
2118 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2119 &removed_streams);
2120 }
2121 // 2.2.7.1.6.2: Set transceiver's [[CurrentDirection]] and
2122 // [[FiredDirection]] slots to direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002123 transceiver->internal()->set_current_direction(media_desc->direction());
Steve Anton0f5400a2018-07-17 14:25:36 -07002124 transceiver->internal()->set_fired_direction(media_desc->direction());
Steve Antondcc3c022017-12-22 16:02:54 -08002125 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002126 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002127 auto observer = Observer();
Steve Anton0f5400a2018-07-17 14:25:36 -07002128 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002129 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton0f5400a2018-07-17 14:25:36 -07002130 }
2131 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002132 observer->OnRemoveStream(stream);
Steve Antondcc3c022017-12-22 16:02:54 -08002133 }
2134 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002135 // Media channels will be created only when offer is set. These may use new
2136 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002137 if (type == SdpType::kOffer) {
2138 // TODO(bugs.webrtc.org/4676) - Handle CreateChannel failure, as new local
2139 // description is applied. Restore back to old description.
2140 RTCError error = CreateChannels(*local_description()->description());
2141 if (!error.ok()) {
2142 return error;
2143 }
2144 }
Steve Antondcc3c022017-12-22 16:02:54 -08002145 // Remove unused channels if MediaContentDescription is rejected.
2146 RemoveUnusedChannels(local_description()->description());
2147 }
Steve Anton8a006912017-12-04 15:25:56 -08002148
Zhi Huange830e682018-03-30 10:48:35 -07002149 error = UpdateSessionState(type, cricket::CS_LOCAL,
2150 local_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002151 if (!error.ok()) {
2152 return error;
2153 }
Steve Antondcc3c022017-12-22 16:02:54 -08002154
Steve Anton8a006912017-12-04 15:25:56 -08002155 if (remote_description()) {
2156 // Now that we have a local description, we can push down remote candidates.
2157 UseCandidatesInSessionDescription(remote_description());
2158 }
2159
2160 pending_ice_restarts_.clear();
2161 if (session_error() != SessionError::kNone) {
2162 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2163 }
2164
deadbeefab9b2d12015-10-14 11:33:11 -07002165 // If setting the description decided our SSL role, allocate any necessary
2166 // SCTP sids.
2167 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002168 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002169 AllocateSctpSids(role);
2170 }
2171
Steve Antond3679212018-01-17 17:41:02 -08002172 if (IsUnifiedPlan()) {
2173 for (auto transceiver : transceivers_) {
2174 const ContentInfo* content =
2175 FindMediaSectionForTransceiver(transceiver, local_description());
2176 if (!content) {
2177 continue;
2178 }
Steve Anton74255ff2018-01-24 18:32:57 -08002179 const auto& streams = content->media_description()->streams();
2180 if (!content->rejected && !streams.empty()) {
Steve Antond3679212018-01-17 17:41:02 -08002181 transceiver->internal()->sender_internal()->set_stream_ids(
Seth Hampson845e8782018-03-02 11:34:10 -08002182 streams[0].stream_ids());
Steve Antond3679212018-01-17 17:41:02 -08002183 transceiver->internal()->sender_internal()->SetSsrc(
Steve Anton74255ff2018-01-24 18:32:57 -08002184 streams[0].first_ssrc());
Steve Anton60b6c1d2018-06-13 11:32:27 -07002185 } else {
2186 // 0 is a special value meaning "this sender has no associated send
2187 // stream". Need to call this so the sender won't attempt to configure
2188 // a no longer existing stream and run into DCHECKs in the lower
2189 // layers.
2190 transceiver->internal()->sender_internal()->SetSsrc(0);
Steve Antond3679212018-01-17 17:41:02 -08002191 }
2192 }
2193 } else {
2194 // Plan B semantics.
2195
Steve Antondcc3c022017-12-22 16:02:54 -08002196 // Update state and SSRC of local MediaStreams and DataChannels based on the
2197 // local session description.
2198 const cricket::ContentInfo* audio_content =
2199 GetFirstAudioContent(local_description()->description());
2200 if (audio_content) {
2201 if (audio_content->rejected) {
2202 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2203 } else {
2204 const cricket::AudioContentDescription* audio_desc =
2205 audio_content->media_description()->as_audio();
2206 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
2207 }
deadbeeffaac4972015-11-12 15:33:07 -08002208 }
deadbeefab9b2d12015-10-14 11:33:11 -07002209
Steve Antondcc3c022017-12-22 16:02:54 -08002210 const cricket::ContentInfo* video_content =
2211 GetFirstVideoContent(local_description()->description());
2212 if (video_content) {
2213 if (video_content->rejected) {
2214 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2215 } else {
2216 const cricket::VideoContentDescription* video_desc =
2217 video_content->media_description()->as_video();
2218 UpdateLocalSenders(video_desc->streams(), video_desc->type());
2219 }
deadbeeffaac4972015-11-12 15:33:07 -08002220 }
deadbeefab9b2d12015-10-14 11:33:11 -07002221 }
2222
2223 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002224 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07002225 if (data_content) {
2226 const cricket::DataContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08002227 data_content->media_description()->as_data();
deadbeefab9b2d12015-10-14 11:33:11 -07002228 if (rtc::starts_with(data_desc->protocol().data(),
2229 cricket::kMediaProtocolRtpPrefix)) {
2230 UpdateLocalRtpDataChannels(data_desc->streams());
2231 }
2232 }
2233
Steve Anton8a006912017-12-04 15:25:56 -08002234 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002235}
2236
2237void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00002238 SetSessionDescriptionObserver* observer,
2239 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002240 SetRemoteDescription(
2241 std::unique_ptr<SessionDescriptionInterface>(desc),
2242 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
2243 new SetRemoteDescriptionObserverAdapter(this, observer)));
2244}
2245
2246void PeerConnection::SetRemoteDescription(
2247 std::unique_ptr<SessionDescriptionInterface> desc,
2248 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002249 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08002250
nisse7ce109a2017-01-31 00:57:56 -08002251 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002252 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002253 return;
2254 }
Steve Anton8a006912017-12-04 15:25:56 -08002255
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002256 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01002257 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08002258 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 return;
2260 }
Steve Anton8d3444d2017-10-20 15:30:51 -07002261
Steve Anton80dd7b52018-02-16 17:08:42 -08002262 // If a session error has occurred the PeerConnection is in a possibly
2263 // inconsistent state so fail right away.
2264 if (session_error() != SessionError::kNone) {
2265 std::string error_message = GetSessionErrorMsg();
2266 RTC_LOG(LS_ERROR) << "SetRemoteDescription: " << error_message;
2267 observer->OnSetRemoteDescriptionComplete(
2268 RTCError(RTCErrorType::INTERNAL_ERROR, std::move(error_message)));
2269 return;
2270 }
Steve Anton71439a62018-02-15 11:53:06 -08002271
Steve Antonba42e992018-04-09 14:10:01 -07002272 if (desc->GetType() == SdpType::kOffer) {
2273 // Report to UMA the format of the received offer.
2274 ReportSdpFormatReceived(*desc);
2275 }
2276
Steve Anton80dd7b52018-02-16 17:08:42 -08002277 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
Steve Anton71439a62018-02-15 11:53:06 -08002278 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08002279 std::string error_message = GetSetDescriptionErrorMessage(
2280 cricket::CS_REMOTE, desc->GetType(), error);
2281 RTC_LOG(LS_ERROR) << error_message;
Steve Anton71439a62018-02-15 11:53:06 -08002282 observer->OnSetRemoteDescriptionComplete(
2283 RTCError(error.type(), std::move(error_message)));
2284 return;
2285 }
Steve Anton71439a62018-02-15 11:53:06 -08002286
Steve Anton80dd7b52018-02-16 17:08:42 -08002287 // Grab the description type before moving ownership to
2288 // ApplyRemoteDescription, which may destroy it before returning.
2289 const SdpType type = desc->GetType();
2290
2291 error = ApplyRemoteDescription(std::move(desc));
2292 // |desc| may be destroyed at this point.
2293
2294 if (!error.ok()) {
2295 // If ApplyRemoteDescription fails, the PeerConnection could be in an
2296 // inconsistent state, so act conservatively here and set the session error
2297 // so that future calls to SetLocalDescription/SetRemoteDescription fail.
2298 SetSessionError(SessionError::kContent, error.message());
2299 std::string error_message =
2300 GetSetDescriptionErrorMessage(cricket::CS_REMOTE, type, error);
2301 RTC_LOG(LS_ERROR) << error_message;
2302 observer->OnSetRemoteDescriptionComplete(
2303 RTCError(error.type(), std::move(error_message)));
2304 return;
2305 }
2306 RTC_DCHECK(remote_description());
2307
2308 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002309 // TODO(deadbeef): We already had to hop to the network thread for
2310 // MaybeStartGathering...
2311 network_thread()->Invoke<void>(
2312 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2313 port_allocator_.get()));
Harald Alvestrand5dbb5862018-02-13 23:48:00 +01002314 // Make UMA notes about what was agreed to.
Steve Anton0ffaaa22018-02-23 10:31:30 -08002315 ReportNegotiatedSdpSemantics(*remote_description());
Steve Anton8a006912017-12-04 15:25:56 -08002316 }
2317
2318 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
Harald Alvestrand8ebba742018-05-31 14:00:34 +02002319 NoteUsageEvent(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED);
Steve Anton8a006912017-12-04 15:25:56 -08002320}
2321
2322RTCError PeerConnection::ApplyRemoteDescription(
2323 std::unique_ptr<SessionDescriptionInterface> desc) {
2324 RTC_DCHECK_RUN_ON(signaling_thread());
2325 RTC_DCHECK(desc);
2326
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002327 // Update stats here so that we have the most recent stats for tracks and
2328 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002329 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08002330
Steve Antondcc3c022017-12-22 16:02:54 -08002331 // Take a reference to the old remote description since it's used below to
2332 // compare against the new remote description. When setting the new remote
2333 // description, grab ownership of the replaced session description in case it
2334 // is the same as |old_remote_description|, to keep it alive for the duration
2335 // of the method.
Steve Anton8a006912017-12-04 15:25:56 -08002336 const SessionDescriptionInterface* old_remote_description =
2337 remote_description();
Steve Anton8a006912017-12-04 15:25:56 -08002338 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08002339 SdpType type = desc->GetType();
2340 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08002341 replaced_remote_description = pending_remote_description_
2342 ? std::move(pending_remote_description_)
2343 : std::move(current_remote_description_);
2344 current_remote_description_ = std::move(desc);
2345 pending_remote_description_ = nullptr;
2346 current_local_description_ = std::move(pending_local_description_);
2347 } else {
2348 replaced_remote_description = std::move(pending_remote_description_);
2349 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002350 }
Steve Anton8a006912017-12-04 15:25:56 -08002351 // The session description to apply now must be accessed by
2352 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01002353 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002354
Zhi Huange830e682018-03-30 10:48:35 -07002355 RTCError error = PushdownTransportDescription(cricket::CS_REMOTE, type);
2356 if (!error.ok()) {
2357 return error;
2358 }
Steve Anton8a006912017-12-04 15:25:56 -08002359 // Transport and Media channels will be created only when offer is set.
Steve Antondcc3c022017-12-22 16:02:54 -08002360 if (IsUnifiedPlan()) {
2361 RTCError error = UpdateTransceiversAndDataChannels(
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002362 cricket::CS_REMOTE, *remote_description(), local_description(),
2363 old_remote_description);
Steve Anton8a006912017-12-04 15:25:56 -08002364 if (!error.ok()) {
2365 return error;
2366 }
Steve Antondcc3c022017-12-22 16:02:54 -08002367 } else {
Zhi Huange830e682018-03-30 10:48:35 -07002368 // Media channels will be created only when offer is set. These may use new
2369 // transports just created by PushdownTransportDescription.
Steve Antondcc3c022017-12-22 16:02:54 -08002370 if (type == SdpType::kOffer) {
Zhi Huange830e682018-03-30 10:48:35 -07002371 // TODO(mallinath) - Handle CreateChannel failure, as new local
Steve Antondcc3c022017-12-22 16:02:54 -08002372 // description is applied. Restore back to old description.
2373 RTCError error = CreateChannels(*remote_description()->description());
2374 if (!error.ok()) {
2375 return error;
2376 }
2377 }
Steve Antondcc3c022017-12-22 16:02:54 -08002378 // Remove unused channels if MediaContentDescription is rejected.
2379 RemoveUnusedChannels(remote_description()->description());
2380 }
Steve Anton8a006912017-12-04 15:25:56 -08002381
Zhi Huange830e682018-03-30 10:48:35 -07002382 // NOTE: Candidates allocation will be initiated only when
2383 // SetLocalDescription is called.
2384 error = UpdateSessionState(type, cricket::CS_REMOTE,
2385 remote_description()->description());
Steve Anton8a006912017-12-04 15:25:56 -08002386 if (!error.ok()) {
2387 return error;
2388 }
2389
2390 if (local_description() &&
2391 !UseCandidatesInSessionDescription(remote_description())) {
2392 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
2393 }
2394
2395 if (old_remote_description) {
2396 for (const cricket::ContentInfo& content :
2397 old_remote_description->description()->contents()) {
2398 // Check if this new SessionDescription contains new ICE ufrag and
2399 // password that indicates the remote peer requests an ICE restart.
2400 // TODO(deadbeef): When we start storing both the current and pending
2401 // remote description, this should reset pending_ice_restarts and compare
2402 // against the current description.
2403 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
2404 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08002405 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08002406 pending_ice_restarts_.insert(content.name);
2407 }
2408 } else {
2409 // We retain all received candidates only if ICE is not restarted.
2410 // When ICE is restarted, all previous candidates belong to an old
2411 // generation and should not be kept.
2412 // TODO(deadbeef): This goes against the W3C spec which says the remote
2413 // description should only contain candidates from the last set remote
2414 // description plus any candidates added since then. We should remove
2415 // this once we're sure it won't break anything.
2416 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
2417 old_remote_description, content.name, mutable_remote_description());
2418 }
2419 }
2420 }
2421
2422 if (session_error() != SessionError::kNone) {
2423 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
2424 }
2425
2426 // Set the the ICE connection state to connecting since the connection may
2427 // become writable with peer reflexive candidates before any remote candidate
2428 // is signaled.
2429 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
2430 // is to have a new signal the indicates a change in checking state from the
2431 // transport and expose a new checking() member from transport that can be
2432 // read to determine the current checking state. The existing SignalConnecting
2433 // actually means "gathering candidates", so cannot be be used here.
Steve Antona3a92c22017-12-07 10:27:41 -08002434 if (remote_description()->GetType() != SdpType::kOffer &&
Steve Antonf764cf42018-05-01 14:32:17 -07002435 remote_description()->number_of_mediasections() > 0u &&
Steve Anton8a006912017-12-04 15:25:56 -08002436 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
2437 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
2438 }
2439
deadbeefab9b2d12015-10-14 11:33:11 -07002440 // If setting the description decided our SSL role, allocate any necessary
2441 // SCTP sids.
2442 rtc::SSLRole role;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002443 if (DataChannel::IsSctpLike(data_channel_type_) && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07002444 AllocateSctpSids(role);
2445 }
2446
Steve Antondcc3c022017-12-22 16:02:54 -08002447 if (IsUnifiedPlan()) {
Steve Anton8b815cd2018-02-16 16:14:42 -08002448 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
Steve Anton3172c032018-05-03 15:30:18 -07002449 now_receiving_transceivers;
Steve Anton0f5400a2018-07-17 14:25:36 -07002450 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> remove_list;
Steve Antonc49bcd92018-02-14 14:28:13 -08002451 std::vector<rtc::scoped_refptr<MediaStreamInterface>> added_streams;
Steve Anton3172c032018-05-03 15:30:18 -07002452 std::vector<rtc::scoped_refptr<MediaStreamInterface>> removed_streams;
Steve Antondcc3c022017-12-22 16:02:54 -08002453 for (auto transceiver : transceivers_) {
2454 const ContentInfo* content =
2455 FindMediaSectionForTransceiver(transceiver, remote_description());
2456 if (!content) {
2457 continue;
2458 }
2459 const MediaContentDescription* media_desc = content->media_description();
2460 RtpTransceiverDirection local_direction =
2461 RtpTransceiverDirectionReversed(media_desc->direction());
2462 // From the WebRTC specification, steps 2.2.8.5/6 of section 4.4.1.6 "Set
2463 // the RTCSessionDescription: If direction is sendrecv or recvonly, and
2464 // transceiver's current direction is neither sendrecv nor recvonly,
2465 // process the addition of a remote track for the media description.
Seth Hampson5b4f0752018-04-02 16:31:36 -07002466 std::vector<std::string> stream_ids;
Seth Hampson2f0d7022018-02-20 11:54:42 -08002467 if (!media_desc->streams().empty()) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07002468 // The remote description has signaled the stream IDs.
2469 stream_ids = media_desc->streams()[0].stream_ids();
Seth Hampson2f0d7022018-02-20 11:54:42 -08002470 }
Steve Antondcc3c022017-12-22 16:02:54 -08002471 if (RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002472 (!transceiver->fired_direction() ||
2473 !RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
Steve Anton3d954a62018-04-02 11:27:23 -07002474 RTC_LOG(LS_INFO) << "Processing the addition of a new track for MID="
Seth Hampson5b4f0752018-04-02 16:31:36 -07002475 << content->name << " (added to "
2476 << GetStreamIdsString(stream_ids) << ").";
2477
2478 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams;
2479 for (const std::string& stream_id : stream_ids) {
2480 rtc::scoped_refptr<MediaStreamInterface> stream =
2481 remote_streams_->find(stream_id);
2482 if (!stream) {
2483 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2484 MediaStream::Create(stream_id));
2485 remote_streams_->AddStream(stream);
2486 added_streams.push_back(stream);
2487 }
2488 media_streams.push_back(stream);
Steve Antonef65ef12018-01-10 17:15:20 -08002489 }
Steve Anton3172c032018-05-03 15:30:18 -07002490 // This will add the remote track to the streams.
Henrik Boström199e27b2018-07-04 20:51:53 +02002491 // TODO(hbos): When we remove remote_streams(), use set_stream_ids()
2492 // instead. https://crbug.com/webrtc/9480
Seth Hampson5b4f0752018-04-02 16:31:36 -07002493 transceiver->internal()->receiver_internal()->SetStreams(media_streams);
Steve Anton3172c032018-05-03 15:30:18 -07002494 now_receiving_transceivers.push_back(transceiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002495 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002496 // 2.2.8.1.7: If direction is "sendonly" or "inactive", and transceiver's
2497 // [[FiredDirection]] slot is either "sendrecv" or "recvonly", process the
2498 // removal of a remote track for the media description, given transceiver,
2499 // removeList, and muteTracks.
Steve Antondcc3c022017-12-22 16:02:54 -08002500 if (!RtpTransceiverDirectionHasRecv(local_direction) &&
Steve Anton0f5400a2018-07-17 14:25:36 -07002501 (transceiver->fired_direction() &&
2502 RtpTransceiverDirectionHasRecv(*transceiver->fired_direction()))) {
2503 ProcessRemovalOfRemoteTrack(transceiver, &remove_list,
2504 &removed_streams);
Steve Antondcc3c022017-12-22 16:02:54 -08002505 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002506 // 2.2.8.1.8: Set transceiver's [[FiredDirection]] slot to direction.
2507 transceiver->internal()->set_fired_direction(local_direction);
2508 // 2.2.8.1.9: If description is of type "answer" or "pranswer", then run
2509 // the following steps:
Steve Antondcc3c022017-12-22 16:02:54 -08002510 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton0f5400a2018-07-17 14:25:36 -07002511 // 2.2.8.1.9.1: Set transceiver's [[CurrentDirection]] slot to
2512 // direction.
Steve Antondcc3c022017-12-22 16:02:54 -08002513 transceiver->internal()->set_current_direction(local_direction);
2514 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002515 // 2.2.8.1.10: If the media description is rejected, and transceiver is
2516 // not already stopped, stop the RTCRtpTransceiver transceiver.
Steve Antondcc3c022017-12-22 16:02:54 -08002517 if (content->rejected && !transceiver->stopped()) {
Steve Anton3d954a62018-04-02 11:27:23 -07002518 RTC_LOG(LS_INFO) << "Stopping transceiver for MID=" << content->name
2519 << " since the media section was rejected.";
Steve Antondcc3c022017-12-22 16:02:54 -08002520 transceiver->Stop();
2521 }
Seth Hampson2f0d7022018-02-20 11:54:42 -08002522 if (!content->rejected &&
2523 RtpTransceiverDirectionHasRecv(local_direction)) {
2524 // Set ssrc to 0 in the case of an unsignalled ssrc.
2525 uint32_t ssrc = 0;
Seth Hampson5897a6e2018-04-03 11:16:33 -07002526 if (!media_desc->streams().empty() &&
2527 media_desc->streams()[0].has_ssrcs()) {
Seth Hampson2f0d7022018-02-20 11:54:42 -08002528 ssrc = media_desc->streams()[0].first_ssrc();
2529 }
2530 transceiver->internal()->receiver_internal()->SetupMediaChannel(ssrc);
Steve Antond3679212018-01-17 17:41:02 -08002531 }
Steve Antondcc3c022017-12-22 16:02:54 -08002532 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002533 // Once all processing has finished, fire off callbacks.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002534 auto observer = Observer();
Steve Anton3172c032018-05-03 15:30:18 -07002535 for (auto transceiver : now_receiving_transceivers) {
Steve Anton6e221372018-02-20 12:59:16 -08002536 stats_->AddTrack(transceiver->receiver()->track());
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002537 observer->OnTrack(transceiver);
2538 observer->OnAddTrack(transceiver->receiver(),
2539 transceiver->receiver()->streams());
Steve Antonef65ef12018-01-10 17:15:20 -08002540 }
Steve Antonc49bcd92018-02-14 14:28:13 -08002541 for (auto stream : added_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002542 observer->OnAddStream(stream);
Steve Antonc49bcd92018-02-14 14:28:13 -08002543 }
Steve Anton0f5400a2018-07-17 14:25:36 -07002544 for (auto transceiver : remove_list) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002545 observer->OnRemoveTrack(transceiver->receiver());
Steve Anton3172c032018-05-03 15:30:18 -07002546 }
2547 for (auto stream : removed_streams) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002548 observer->OnRemoveStream(stream);
Steve Anton3172c032018-05-03 15:30:18 -07002549 }
Steve Antondcc3c022017-12-22 16:02:54 -08002550 }
2551
Henrik Boströmfdb92012017-11-09 19:55:44 +01002552 const cricket::ContentInfo* audio_content =
2553 GetFirstAudioContent(remote_description()->description());
2554 const cricket::ContentInfo* video_content =
2555 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002556 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002557 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002558 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002559 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002560 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01002561 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08002562
2563 // Check if the descriptions include streams, just in case the peer supports
2564 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01002565 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08002566 (audio_desc && !audio_desc->streams().empty()) ||
2567 (video_desc && !video_desc->streams().empty())) {
2568 remote_peer_supports_msid_ = true;
2569 }
deadbeefab9b2d12015-10-14 11:33:11 -07002570
2571 // We wait to signal new streams until we finish processing the description,
2572 // since only at that point will new streams have all their tracks.
2573 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
2574
Steve Antondcc3c022017-12-22 16:02:54 -08002575 if (!IsUnifiedPlan()) {
2576 // TODO(steveanton): When removing RTP senders/receivers in response to a
2577 // rejected media section, there is some cleanup logic that expects the
2578 // voice/ video channel to still be set. But in this method the voice/video
2579 // channel would have been destroyed by the SetRemoteDescription caller
2580 // above so the cleanup that relies on them fails to run. The RemoveSenders
2581 // calls should be moved to right before the DestroyChannel calls to fix
2582 // this.
Steve Anton8d3444d2017-10-20 15:30:51 -07002583
Steve Antondcc3c022017-12-22 16:02:54 -08002584 // Find all audio rtp streams and create corresponding remote AudioTracks
2585 // and MediaStreams.
2586 if (audio_content) {
2587 if (audio_content->rejected) {
2588 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
2589 } else {
2590 bool default_audio_track_needed =
2591 !remote_peer_supports_msid_ &&
2592 RtpTransceiverDirectionHasSend(audio_desc->direction());
2593 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
2594 default_audio_track_needed, audio_desc->type(),
2595 new_streams);
2596 }
deadbeeffaac4972015-11-12 15:33:07 -08002597 }
deadbeefab9b2d12015-10-14 11:33:11 -07002598
Steve Antondcc3c022017-12-22 16:02:54 -08002599 // Find all video rtp streams and create corresponding remote VideoTracks
2600 // and MediaStreams.
2601 if (video_content) {
2602 if (video_content->rejected) {
2603 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
2604 } else {
2605 bool default_video_track_needed =
2606 !remote_peer_supports_msid_ &&
2607 RtpTransceiverDirectionHasSend(video_desc->direction());
2608 UpdateRemoteSendersList(GetActiveStreams(video_desc),
2609 default_video_track_needed, video_desc->type(),
2610 new_streams);
2611 }
deadbeeffaac4972015-11-12 15:33:07 -08002612 }
deadbeefab9b2d12015-10-14 11:33:11 -07002613
Steve Antondcc3c022017-12-22 16:02:54 -08002614 // Update the DataChannels with the information from the remote peer.
2615 if (data_desc) {
2616 if (rtc::starts_with(data_desc->protocol().data(),
2617 cricket::kMediaProtocolRtpPrefix)) {
2618 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2619 }
deadbeefab9b2d12015-10-14 11:33:11 -07002620 }
deadbeefab9b2d12015-10-14 11:33:11 -07002621
Steve Antondcc3c022017-12-22 16:02:54 -08002622 // Iterate new_streams and notify the observer about new MediaStreams.
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002623 auto observer = Observer();
Steve Antondcc3c022017-12-22 16:02:54 -08002624 for (size_t i = 0; i < new_streams->count(); ++i) {
2625 MediaStreamInterface* new_stream = new_streams->at(i);
2626 stats_->AddStream(new_stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02002627 observer->OnAddStream(
Steve Antondcc3c022017-12-22 16:02:54 -08002628 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
2629 }
deadbeefab9b2d12015-10-14 11:33:11 -07002630
Steve Antondcc3c022017-12-22 16:02:54 -08002631 UpdateEndedRemoteMediaStreams();
2632 }
deadbeefab9b2d12015-10-14 11:33:11 -07002633
Steve Anton8a006912017-12-04 15:25:56 -08002634 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07002635}
2636
Steve Anton0f5400a2018-07-17 14:25:36 -07002637void PeerConnection::ProcessRemovalOfRemoteTrack(
2638 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2639 transceiver,
2640 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>* remove_list,
2641 std::vector<rtc::scoped_refptr<MediaStreamInterface>>* removed_streams) {
2642 RTC_DCHECK(transceiver->mid());
2643 RTC_LOG(LS_INFO) << "Processing the removal of a track for MID="
2644 << *transceiver->mid();
2645 std::vector<rtc::scoped_refptr<MediaStreamInterface>> media_streams =
2646 transceiver->internal()->receiver_internal()->streams();
2647 // This will remove the remote track from the streams.
2648 transceiver->internal()->receiver_internal()->set_stream_ids({});
2649 remove_list->push_back(transceiver);
2650 // Remove any streams that no longer have tracks.
2651 // TODO(https://crbug.com/webrtc/9480): When we use stream IDs instead
2652 // of streams, see if the stream was removed by checking if this was the
2653 // last receiver with that stream ID.
2654 for (auto stream : media_streams) {
2655 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2656 remote_streams_->RemoveStream(stream);
2657 removed_streams->push_back(stream);
2658 }
2659 }
2660}
2661
Steve Antondcc3c022017-12-22 16:02:54 -08002662RTCError PeerConnection::UpdateTransceiversAndDataChannels(
2663 cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002664 const SessionDescriptionInterface& new_session,
2665 const SessionDescriptionInterface* old_local_description,
2666 const SessionDescriptionInterface* old_remote_description) {
Steve Antondcc3c022017-12-22 16:02:54 -08002667 RTC_DCHECK(IsUnifiedPlan());
2668
Steve Anton7464fca2018-01-19 11:10:37 -08002669 const cricket::ContentGroup* bundle_group = nullptr;
2670 if (new_session.GetType() == SdpType::kOffer) {
2671 auto bundle_group_or_error =
2672 GetEarlyBundleGroup(*new_session.description());
2673 if (!bundle_group_or_error.ok()) {
2674 return bundle_group_or_error.MoveError();
2675 }
2676 bundle_group = bundle_group_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002677 }
Steve Antondcc3c022017-12-22 16:02:54 -08002678
Steve Antondcc3c022017-12-22 16:02:54 -08002679 const ContentInfos& new_contents = new_session.description()->contents();
Steve Antondcc3c022017-12-22 16:02:54 -08002680 for (size_t i = 0; i < new_contents.size(); ++i) {
2681 const cricket::ContentInfo& new_content = new_contents[i];
Steve Antondcc3c022017-12-22 16:02:54 -08002682 cricket::MediaType media_type = new_content.media_description()->type();
2683 seen_mids_.insert(new_content.name);
2684 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
2685 media_type == cricket::MEDIA_TYPE_VIDEO) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002686 const cricket::ContentInfo* old_local_content = nullptr;
2687 if (old_local_description &&
2688 i < old_local_description->description()->contents().size()) {
2689 old_local_content =
2690 &old_local_description->description()->contents()[i];
2691 }
2692 const cricket::ContentInfo* old_remote_content = nullptr;
2693 if (old_remote_description &&
2694 i < old_remote_description->description()->contents().size()) {
2695 old_remote_content =
2696 &old_remote_description->description()->contents()[i];
2697 }
Steve Antondcc3c022017-12-22 16:02:54 -08002698 auto transceiver_or_error =
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002699 AssociateTransceiver(source, new_session.GetType(), i, new_content,
2700 old_local_content, old_remote_content);
Steve Antondcc3c022017-12-22 16:02:54 -08002701 if (!transceiver_or_error.ok()) {
2702 return transceiver_or_error.MoveError();
2703 }
2704 auto transceiver = transceiver_or_error.MoveValue();
Steve Antondcc3c022017-12-22 16:02:54 -08002705 RTCError error =
2706 UpdateTransceiverChannel(transceiver, new_content, bundle_group);
2707 if (!error.ok()) {
2708 return error;
2709 }
2710 } else if (media_type == cricket::MEDIA_TYPE_DATA) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002711 if (GetDataMid() && new_content.name != *GetDataMid()) {
2712 // Ignore all but the first data section.
Steve Anton3d954a62018-04-02 11:27:23 -07002713 RTC_LOG(LS_INFO) << "Ignoring data media section with MID="
2714 << new_content.name;
Steve Antonfa2260d2017-12-28 16:38:23 -08002715 continue;
2716 }
2717 RTCError error = UpdateDataChannel(source, new_content, bundle_group);
2718 if (!error.ok()) {
2719 return error;
2720 }
Steve Antondcc3c022017-12-22 16:02:54 -08002721 } else {
2722 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2723 "Unknown section type.");
2724 }
2725 }
2726
2727 return RTCError::OK();
2728}
2729
2730RTCError PeerConnection::UpdateTransceiverChannel(
2731 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2732 transceiver,
2733 const cricket::ContentInfo& content,
2734 const cricket::ContentGroup* bundle_group) {
2735 RTC_DCHECK(IsUnifiedPlan());
2736 RTC_DCHECK(transceiver);
2737 cricket::BaseChannel* channel = transceiver->internal()->channel();
2738 if (content.rejected) {
2739 if (channel) {
2740 transceiver->internal()->SetChannel(nullptr);
2741 DestroyBaseChannel(channel);
2742 }
2743 } else {
2744 if (!channel) {
Steve Anton69470252018-02-09 11:43:08 -08002745 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Zhi Huange830e682018-03-30 10:48:35 -07002746 channel = CreateVoiceChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002747 } else {
Steve Anton69470252018-02-09 11:43:08 -08002748 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, transceiver->media_type());
Zhi Huange830e682018-03-30 10:48:35 -07002749 channel = CreateVideoChannel(content.name);
Steve Antondcc3c022017-12-22 16:02:54 -08002750 }
2751 if (!channel) {
2752 LOG_AND_RETURN_ERROR(
2753 RTCErrorType::INTERNAL_ERROR,
2754 "Failed to create channel for mid=" + content.name);
2755 }
2756 transceiver->internal()->SetChannel(channel);
2757 }
2758 }
2759 return RTCError::OK();
2760}
2761
Steve Antonfa2260d2017-12-28 16:38:23 -08002762RTCError PeerConnection::UpdateDataChannel(
2763 cricket::ContentSource source,
2764 const cricket::ContentInfo& content,
2765 const cricket::ContentGroup* bundle_group) {
2766 if (data_channel_type_ == cricket::DCT_NONE) {
Steve Antondbf9d032018-01-19 15:23:40 -08002767 // If data channels are disabled, ignore this media section. CreateAnswer
2768 // will take care of rejecting it.
2769 return RTCError::OK();
Steve Antonfa2260d2017-12-28 16:38:23 -08002770 }
2771 if (content.rejected) {
2772 DestroyDataChannel();
2773 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08002774 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07002775 if (!CreateDataChannel(content.name)) {
Steve Antonfa2260d2017-12-28 16:38:23 -08002776 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
2777 "Failed to create data channel.");
2778 }
2779 }
2780 if (source == cricket::CS_REMOTE) {
2781 const MediaContentDescription* data_desc = content.media_description();
2782 if (data_desc && cricket::IsRtpProtocol(data_desc->protocol())) {
2783 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
2784 }
2785 }
2786 }
2787 return RTCError::OK();
2788}
2789
Steve Antondcc3c022017-12-22 16:02:54 -08002790RTCErrorOr<rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>>
2791PeerConnection::AssociateTransceiver(cricket::ContentSource source,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002792 SdpType type,
Steve Antondcc3c022017-12-22 16:02:54 -08002793 size_t mline_index,
2794 const ContentInfo& content,
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002795 const ContentInfo* old_local_content,
2796 const ContentInfo* old_remote_content) {
Steve Antondcc3c022017-12-22 16:02:54 -08002797 RTC_DCHECK(IsUnifiedPlan());
Seth Hampsonae8a90a2018-02-13 15:33:48 -08002798 // If this is an offer then the m= section might be recycled. If the m=
2799 // section is being recycled (defined as: rejected in the current local or
2800 // remote description and not rejected in new description), dissociate the
2801 // currently associated RtpTransceiver by setting its mid property to null,
2802 // and discard the mapping between the transceiver and its m= section index.
2803 if (IsMediaSectionBeingRecycled(type, content, old_local_content,
2804 old_remote_content)) {
2805 // We want to dissociate the transceiver that has the rejected mid.
2806 const std::string& old_mid =
2807 (old_local_content && old_local_content->rejected)
2808 ? old_local_content->name
2809 : old_remote_content->name;
2810 auto old_transceiver = GetAssociatedTransceiver(old_mid);
Steve Antondcc3c022017-12-22 16:02:54 -08002811 if (old_transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002812 RTC_LOG(LS_INFO) << "Dissociating transceiver for MID=" << old_mid
2813 << " since the media section is being recycled.";
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02002814 old_transceiver->internal()->set_mid(absl::nullopt);
2815 old_transceiver->internal()->set_mline_index(absl::nullopt);
Steve Antondcc3c022017-12-22 16:02:54 -08002816 }
2817 }
2818 const MediaContentDescription* media_desc = content.media_description();
2819 auto transceiver = GetAssociatedTransceiver(content.name);
2820 if (source == cricket::CS_LOCAL) {
2821 // Find the RtpTransceiver that corresponds to this m= section, using the
2822 // mapping between transceivers and m= section indices established when
2823 // creating the offer.
2824 if (!transceiver) {
2825 transceiver = GetTransceiverByMLineIndex(mline_index);
2826 }
2827 if (!transceiver) {
2828 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2829 "Unknown transceiver");
2830 }
2831 } else {
2832 RTC_DCHECK_EQ(source, cricket::CS_REMOTE);
2833 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers
2834 // of the same type...
2835 if (!transceiver &&
2836 RtpTransceiverDirectionHasRecv(media_desc->direction())) {
2837 transceiver = FindAvailableTransceiverToReceive(media_desc->type());
2838 }
2839 // If no RtpTransceiver was found in the previous step, create one with a
2840 // recvonly direction.
2841 if (!transceiver) {
Steve Anton3d954a62018-04-02 11:27:23 -07002842 RTC_LOG(LS_INFO) << "Adding "
2843 << cricket::MediaTypeToString(media_desc->type())
2844 << " transceiver for MID=" << content.name
2845 << " at i=" << mline_index
2846 << " in response to the remote description.";
Steve Anton111fdfd2018-06-25 13:03:36 -07002847 std::string sender_id = rtc::CreateRandomUuid();
Florent Castelli892acf02018-10-01 22:47:20 +02002848 auto sender =
2849 CreateSender(media_desc->type(), sender_id, nullptr, {}, {});
Steve Anton5f94aa22018-02-01 10:58:30 -08002850 std::string receiver_id;
2851 if (!media_desc->streams().empty()) {
2852 receiver_id = media_desc->streams()[0].id;
2853 } else {
2854 receiver_id = rtc::CreateRandomUuid();
2855 }
2856 auto receiver = CreateReceiver(media_desc->type(), receiver_id);
Steve Anton02ee47c2018-01-10 16:26:06 -08002857 transceiver = CreateAndAddTransceiver(sender, receiver);
Steve Antondcc3c022017-12-22 16:02:54 -08002858 transceiver->internal()->set_direction(
2859 RtpTransceiverDirection::kRecvOnly);
2860 }
2861 }
2862 RTC_DCHECK(transceiver);
Steve Anton69470252018-02-09 11:43:08 -08002863 if (transceiver->media_type() != media_desc->type()) {
Steve Antondcc3c022017-12-22 16:02:54 -08002864 LOG_AND_RETURN_ERROR(
2865 RTCErrorType::INVALID_PARAMETER,
2866 "Transceiver type does not match media description type.");
2867 }
2868 // Associate the found or created RtpTransceiver with the m= section by
2869 // setting the value of the RtpTransceiver's mid property to the MID of the m=
2870 // section, and establish a mapping between the transceiver and the index of
2871 // the m= section.
2872 transceiver->internal()->set_mid(content.name);
2873 transceiver->internal()->set_mline_index(mline_index);
2874 return std::move(transceiver);
2875}
2876
2877rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2878PeerConnection::GetAssociatedTransceiver(const std::string& mid) const {
2879 RTC_DCHECK(IsUnifiedPlan());
2880 for (auto transceiver : transceivers_) {
2881 if (transceiver->mid() == mid) {
2882 return transceiver;
2883 }
2884 }
2885 return nullptr;
2886}
2887
2888rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2889PeerConnection::GetTransceiverByMLineIndex(size_t mline_index) const {
2890 RTC_DCHECK(IsUnifiedPlan());
2891 for (auto transceiver : transceivers_) {
2892 if (transceiver->internal()->mline_index() == mline_index) {
2893 return transceiver;
2894 }
2895 }
2896 return nullptr;
2897}
2898
2899rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2900PeerConnection::FindAvailableTransceiverToReceive(
2901 cricket::MediaType media_type) const {
2902 RTC_DCHECK(IsUnifiedPlan());
2903 // From JSEP section 5.10 (Applying a Remote Description):
2904 // If the m= section is sendrecv or recvonly, and there are RtpTransceivers of
2905 // the same type that were added to the PeerConnection by addTrack and are not
2906 // associated with any m= section and are not stopped, find the first such
2907 // RtpTransceiver.
2908 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08002909 if (transceiver->media_type() == media_type &&
Steve Antondcc3c022017-12-22 16:02:54 -08002910 transceiver->internal()->created_by_addtrack() && !transceiver->mid() &&
2911 !transceiver->stopped()) {
2912 return transceiver;
2913 }
2914 }
2915 return nullptr;
2916}
2917
Steve Antoned10bd92017-12-05 10:52:59 -08002918const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
2919 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
2920 transceiver,
2921 const SessionDescriptionInterface* sdesc) const {
2922 RTC_DCHECK(transceiver);
2923 RTC_DCHECK(sdesc);
2924 if (IsUnifiedPlan()) {
2925 if (!transceiver->internal()->mid()) {
2926 // This transceiver is not associated with a media section yet.
2927 return nullptr;
2928 }
2929 return sdesc->description()->GetContentByName(
2930 *transceiver->internal()->mid());
2931 } else {
2932 // Plan B only allows at most one audio and one video section, so use the
2933 // first media section of that type.
2934 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
Steve Anton69470252018-02-09 11:43:08 -08002935 transceiver->media_type());
Steve Antoned10bd92017-12-05 10:52:59 -08002936 }
2937}
2938
deadbeef46c73892016-11-16 19:42:04 -08002939PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
2940 return configuration_;
2941}
2942
deadbeef293e9262017-01-11 12:28:30 -08002943bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
2944 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002945 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
Steve Antonc79268f2018-04-24 09:54:10 -07002946 if (IsClosed()) {
2947 RTC_LOG(LS_ERROR) << "SetConfiguration: PeerConnection is closed.";
2948 return SafeSetError(RTCErrorType::INVALID_STATE, error);
2949 }
2950
Qingsi Wanga2d60672018-04-11 16:57:45 -07002951 // According to JSEP, after setLocalDescription, changing the candidate pool
2952 // size is not allowed, and changing the set of ICE servers will not result
2953 // in new candidates being gathered.
Steve Anton75737c02017-11-06 10:37:17 -08002954 if (local_description() && configuration.ice_candidate_pool_size !=
2955 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002956 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
2957 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08002958 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00002959 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002960
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07002961 if (local_description() &&
2962 configuration.use_media_transport != configuration_.use_media_transport) {
2963 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2964 "SetLocalDescription.";
2965 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2966 }
2967
2968 if (remote_description() &&
2969 configuration.use_media_transport != configuration_.use_media_transport) {
2970 RTC_LOG(LS_ERROR) << "Can't change media_transport after calling "
2971 "SetRemoteDescription.";
2972 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2973 }
2974
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002975 if (local_description() &&
Bjorn Mellema9bbd862018-11-02 09:07:48 -07002976 configuration.use_media_transport_for_data_channels !=
2977 configuration_.use_media_transport_for_data_channels) {
2978 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2979 "after calling SetLocalDescription.";
2980 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2981 }
2982
2983 if (remote_description() &&
2984 configuration.use_media_transport_for_data_channels !=
2985 configuration_.use_media_transport_for_data_channels) {
2986 RTC_LOG(LS_ERROR) << "Can't change media_transport_for_data_channels "
2987 "after calling SetRemoteDescription.";
2988 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2989 }
2990
2991 if (local_description() &&
Benjamin Wright8c27cca2018-10-25 10:16:44 -07002992 configuration.crypto_options != configuration_.crypto_options) {
2993 RTC_LOG(LS_ERROR) << "Can't change crypto_options after calling "
2994 "SetLocalDescription.";
2995 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
2996 }
2997
deadbeef293e9262017-01-11 12:28:30 -08002998 // The simplest (and most future-compatible) way to tell if the config was
2999 // modified in an invalid way is to copy each property we do support
3000 // modifying, then use operator==. There are far more properties we don't
3001 // support modifying than those we do, and more could be added.
3002 RTCConfiguration modified_config = configuration_;
3003 modified_config.servers = configuration.servers;
3004 modified_config.type = configuration.type;
3005 modified_config.ice_candidate_pool_size =
3006 configuration.ice_candidate_pool_size;
3007 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08003008 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Qingsi Wange6826d22018-03-08 14:55:14 -08003009 modified_config.ice_check_interval_strong_connectivity =
3010 configuration.ice_check_interval_strong_connectivity;
3011 modified_config.ice_check_interval_weak_connectivity =
3012 configuration.ice_check_interval_weak_connectivity;
Qingsi Wang22e623a2018-03-13 10:53:57 -07003013 modified_config.ice_unwritable_timeout = configuration.ice_unwritable_timeout;
3014 modified_config.ice_unwritable_min_checks =
3015 configuration.ice_unwritable_min_checks;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003016 modified_config.stun_candidate_keepalive_interval =
3017 configuration.stun_candidate_keepalive_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02003018 modified_config.turn_customizer = configuration.turn_customizer;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08003019 modified_config.network_preference = configuration.network_preference;
Zhi Huangb57e1692018-06-12 11:41:11 -07003020 modified_config.active_reset_srtp_params =
3021 configuration.active_reset_srtp_params;
Piotr (Peter) Slatalaaa1e7c22018-10-16 10:04:45 -07003022 modified_config.use_media_transport = configuration.use_media_transport;
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003023 modified_config.use_media_transport_for_data_channels =
3024 configuration.use_media_transport_for_data_channels;
deadbeef293e9262017-01-11 12:28:30 -08003025 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003026 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08003027 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
3028 }
3029
Steve Anton038834f2017-07-14 15:59:59 -07003030 // Validate the modified configuration.
3031 RTCError validate_error = ValidateConfiguration(modified_config);
3032 if (!validate_error.ok()) {
3033 return SafeSetError(std::move(validate_error), error);
3034 }
3035
deadbeef293e9262017-01-11 12:28:30 -08003036 // Note that this isn't possible through chromium, since it's an unsigned
3037 // short in WebIDL.
3038 if (configuration.ice_candidate_pool_size < 0 ||
Wez939eb802018-05-03 03:34:17 -07003039 configuration.ice_candidate_pool_size > static_cast<int>(UINT16_MAX)) {
deadbeef293e9262017-01-11 12:28:30 -08003040 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
3041 }
3042
3043 // Parse ICE servers before hopping to network thread.
3044 cricket::ServerAddresses stun_servers;
3045 std::vector<cricket::RelayServerConfig> turn_servers;
3046 RTCErrorType parse_error =
3047 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
3048 if (parse_error != RTCErrorType::NONE) {
3049 return SafeSetError(parse_error, error);
3050 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003051 // Note if STUN or TURN servers were supplied.
3052 if (!stun_servers.empty()) {
3053 NoteUsageEvent(UsageEvent::STUN_SERVER_ADDED);
3054 }
3055 if (!turn_servers.empty()) {
3056 NoteUsageEvent(UsageEvent::TURN_SERVER_ADDED);
3057 }
deadbeef293e9262017-01-11 12:28:30 -08003058
3059 // In theory this shouldn't fail.
3060 if (!network_thread()->Invoke<bool>(
3061 RTC_FROM_HERE,
3062 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
3063 stun_servers, turn_servers, modified_config.type,
3064 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003065 modified_config.prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08003066 modified_config.turn_customizer,
3067 modified_config.stun_candidate_keepalive_interval))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003068 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08003069 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
3070 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07003071
deadbeefd1a38b52016-12-10 13:15:33 -08003072 // As described in JSEP, calling setConfiguration with new ICE servers or
3073 // candidate policy must set a "needs-ice-restart" bit so that the next offer
3074 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08003075 if (modified_config.servers != configuration_.servers ||
3076 modified_config.type != configuration_.type ||
3077 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08003078 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08003079 }
skvladd1f5fda2017-02-03 16:54:05 -08003080
Qingsi Wang9c98f0c2018-02-15 15:10:59 -08003081 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
Piotr (Peter) Slatala97fc11f2018-10-18 12:57:59 -07003082 transport_controller_->SetMediaTransportFactory(
Bjorn Mellema9bbd862018-11-02 09:07:48 -07003083 modified_config.use_media_transport ||
3084 modified_config.use_media_transport_for_data_channels
3085 ? factory_->media_transport_factory()
3086 : nullptr);
skvladd1f5fda2017-02-03 16:54:05 -08003087
Zhi Huangb57e1692018-06-12 11:41:11 -07003088 if (configuration_.active_reset_srtp_params !=
3089 modified_config.active_reset_srtp_params) {
3090 transport_controller_->SetActiveResetSrtpParams(
3091 modified_config.active_reset_srtp_params);
3092 }
3093
deadbeef293e9262017-01-11 12:28:30 -08003094 configuration_ = modified_config;
3095 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00003096}
3097
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003098bool PeerConnection::AddIceCandidate(
3099 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01003100 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07003101 if (IsClosed()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003102 RTC_LOG(LS_ERROR) << "AddIceCandidate: PeerConnection is closed.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003103 NoteAddIceCandidateResult(kAddIceCandidateFailClosed);
zhihuang29ff8442016-07-27 11:07:25 -07003104 return false;
3105 }
Steve Antond25da372017-11-06 14:50:29 -08003106
3107 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003108 RTC_LOG(LS_ERROR) << "AddIceCandidate: ICE candidates can't be added "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003109 "without any remote session description.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003110 NoteAddIceCandidateResult(kAddIceCandidateFailNoRemoteDescription);
Steve Antond25da372017-11-06 14:50:29 -08003111 return false;
3112 }
3113
3114 if (!ice_candidate) {
Steve Antonc79268f2018-04-24 09:54:10 -07003115 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate is null.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003116 NoteAddIceCandidateResult(kAddIceCandidateFailNullCandidate);
Steve Antond25da372017-11-06 14:50:29 -08003117 return false;
3118 }
3119
3120 bool valid = false;
3121 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
3122 if (!valid) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003123 NoteAddIceCandidateResult(kAddIceCandidateFailNotValid);
Steve Antond25da372017-11-06 14:50:29 -08003124 return false;
3125 }
3126
3127 // Add this candidate to the remote session description.
3128 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Steve Antonc79268f2018-04-24 09:54:10 -07003129 RTC_LOG(LS_ERROR) << "AddIceCandidate: Candidate cannot be used.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003130 NoteAddIceCandidateResult(kAddIceCandidateFailInAddition);
Steve Antond25da372017-11-06 14:50:29 -08003131 return false;
3132 }
3133
3134 if (ready) {
Harald Alvestrand76829d72018-07-18 23:24:36 +02003135 bool result = UseCandidate(ice_candidate);
3136 if (result) {
3137 NoteUsageEvent(UsageEvent::REMOTE_CANDIDATE_ADDED);
3138 NoteAddIceCandidateResult(kAddIceCandidateSuccess);
3139 } else {
3140 NoteAddIceCandidateResult(kAddIceCandidateFailNotUsable);
3141 }
3142 return result;
Steve Antond25da372017-11-06 14:50:29 -08003143 } else {
Steve Antonc79268f2018-04-24 09:54:10 -07003144 RTC_LOG(LS_INFO) << "AddIceCandidate: Not ready to use candidate.";
Harald Alvestrand76829d72018-07-18 23:24:36 +02003145 NoteAddIceCandidateResult(kAddIceCandidateFailNotReady);
Steve Antond25da372017-11-06 14:50:29 -08003146 return true;
3147 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003148}
3149
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003150bool PeerConnection::RemoveIceCandidates(
3151 const std::vector<cricket::Candidate>& candidates) {
3152 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antonc79268f2018-04-24 09:54:10 -07003153 if (IsClosed()) {
3154 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: PeerConnection is closed.";
3155 return false;
3156 }
3157
Steve Antond25da372017-11-06 14:50:29 -08003158 if (!remote_description()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003159 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: ICE candidates can't be removed "
3160 "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08003161 return false;
3162 }
3163
3164 if (candidates.empty()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003165 RTC_LOG(LS_ERROR) << "RemoveIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08003166 return false;
3167 }
3168
3169 size_t number_removed =
3170 mutable_remote_description()->RemoveCandidates(candidates);
3171 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003172 RTC_LOG(LS_ERROR)
Steve Antonc79268f2018-04-24 09:54:10 -07003173 << "RemoveIceCandidates: Failed to remove candidates. Requested "
Jonas Olsson45cc8902018-02-13 10:37:07 +01003174 << candidates.size() << " but only " << number_removed
Mirko Bonadei675513b2017-11-09 11:09:25 +01003175 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08003176 }
3177
3178 // Remove the candidates from the transport controller.
Zhi Huange830e682018-03-30 10:48:35 -07003179 RTCError error = transport_controller_->RemoveRemoteCandidates(candidates);
3180 if (!error.ok()) {
Steve Antonc79268f2018-04-24 09:54:10 -07003181 RTC_LOG(LS_ERROR)
3182 << "RemoveIceCandidates: Error when removing remote candidates: "
3183 << error.message();
Steve Antond25da372017-11-06 14:50:29 -08003184 }
3185 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003186}
3187
Niels Möller0c4f7be2018-05-07 14:01:37 +02003188RTCError PeerConnection::SetBitrate(const BitrateSettings& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07003189 if (!worker_thread()->IsCurrent()) {
3190 return worker_thread()->Invoke<RTCError>(
Yves Gerey665174f2018-06-19 15:03:05 +02003191 RTC_FROM_HERE, [&]() { return SetBitrate(bitrate); });
zstein4b979802017-06-02 14:37:37 -07003192 }
3193
Niels Möller0c4f7be2018-05-07 14:01:37 +02003194 const bool has_min = bitrate.min_bitrate_bps.has_value();
3195 const bool has_start = bitrate.start_bitrate_bps.has_value();
3196 const bool has_max = bitrate.max_bitrate_bps.has_value();
zstein4b979802017-06-02 14:37:37 -07003197 if (has_min && *bitrate.min_bitrate_bps < 0) {
3198 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3199 "min_bitrate_bps <= 0");
3200 }
Niels Möller0c4f7be2018-05-07 14:01:37 +02003201 if (has_start) {
3202 if (has_min && *bitrate.start_bitrate_bps < *bitrate.min_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003203 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003204 "start_bitrate_bps < min_bitrate_bps");
3205 } else if (*bitrate.start_bitrate_bps < 0) {
zstein4b979802017-06-02 14:37:37 -07003206 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3207 "curent_bitrate_bps < 0");
3208 }
3209 }
3210 if (has_max) {
Yves Gerey665174f2018-06-19 15:03:05 +02003211 if (has_start && *bitrate.max_bitrate_bps < *bitrate.start_bitrate_bps) {
zstein4b979802017-06-02 14:37:37 -07003212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
Niels Möller0c4f7be2018-05-07 14:01:37 +02003213 "max_bitrate_bps < start_bitrate_bps");
zstein4b979802017-06-02 14:37:37 -07003214 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
3215 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3216 "max_bitrate_bps < min_bitrate_bps");
3217 } else if (*bitrate.max_bitrate_bps < 0) {
3218 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3219 "max_bitrate_bps < 0");
3220 }
3221 }
3222
zstein4b979802017-06-02 14:37:37 -07003223 RTC_DCHECK(call_.get());
Niels Möller0c4f7be2018-05-07 14:01:37 +02003224 call_->GetTransportControllerSend()->SetClientBitratePreferences(bitrate);
zstein4b979802017-06-02 14:37:37 -07003225
3226 return RTCError::OK();
3227}
3228
Alex Narest78609d52017-10-20 10:37:47 +02003229void PeerConnection::SetBitrateAllocationStrategy(
3230 std::unique_ptr<rtc::BitrateAllocationStrategy>
3231 bitrate_allocation_strategy) {
3232 rtc::Thread* worker_thread = factory_->worker_thread();
3233 if (!worker_thread->IsCurrent()) {
3234 rtc::BitrateAllocationStrategy* strategy_raw =
3235 bitrate_allocation_strategy.release();
3236 auto functor = [this, strategy_raw]() {
3237 call_->SetBitrateAllocationStrategy(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003238 absl::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
Alex Narest78609d52017-10-20 10:37:47 +02003239 };
3240 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
3241 return;
3242 }
3243 RTC_DCHECK(call_.get());
3244 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
3245}
3246
henrika5f6bf242017-11-01 11:06:56 +01003247void PeerConnection::SetAudioPlayout(bool playout) {
3248 if (!worker_thread()->IsCurrent()) {
3249 worker_thread()->Invoke<void>(
3250 RTC_FROM_HERE,
3251 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
3252 return;
3253 }
3254 auto audio_state =
3255 factory_->channel_manager()->media_engine()->GetAudioState();
3256 audio_state->SetPlayout(playout);
3257}
3258
3259void PeerConnection::SetAudioRecording(bool recording) {
3260 if (!worker_thread()->IsCurrent()) {
3261 worker_thread()->Invoke<void>(
3262 RTC_FROM_HERE,
3263 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
3264 return;
3265 }
3266 auto audio_state =
3267 factory_->channel_manager()->media_engine()->GetAudioState();
3268 audio_state->SetRecording(recording);
3269}
3270
Steve Anton8c0f7a72017-10-03 10:03:10 -07003271std::unique_ptr<rtc::SSLCertificate>
3272PeerConnection::GetRemoteAudioSSLCertificate() {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08003273 std::unique_ptr<rtc::SSLCertChain> chain = GetRemoteAudioSSLCertChain();
3274 if (!chain || !chain->GetSize()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07003275 return nullptr;
3276 }
Steve Antonf25303e2018-10-16 15:23:31 -07003277 return chain->Get(0).Clone();
Steve Anton8c0f7a72017-10-03 10:03:10 -07003278}
3279
Zhi Huang70b820f2018-01-27 14:16:15 -08003280std::unique_ptr<rtc::SSLCertChain>
3281PeerConnection::GetRemoteAudioSSLCertChain() {
Steve Antonafb0bb72018-02-20 11:35:37 -08003282 auto audio_transceiver = GetFirstAudioTransceiver();
3283 if (!audio_transceiver || !audio_transceiver->internal()->channel()) {
Zhi Huang70b820f2018-01-27 14:16:15 -08003284 return nullptr;
3285 }
Zhi Huang70b820f2018-01-27 14:16:15 -08003286 return transport_controller_->GetRemoteSSLCertChain(
Steve Antonafb0bb72018-02-20 11:35:37 -08003287 audio_transceiver->internal()->channel()->transport_name());
3288}
3289
3290rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3291PeerConnection::GetFirstAudioTransceiver() const {
3292 for (auto transceiver : transceivers_) {
3293 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3294 return transceiver;
3295 }
3296 }
3297 return nullptr;
Zhi Huang70b820f2018-01-27 14:16:15 -08003298}
3299
ivoc14d5dbe2016-07-04 07:06:55 -07003300bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
3301 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02003302 // TODO(eladalon): It would be better to not allow negative values into PC.
3303 const size_t max_size = (max_size_bytes < 0)
3304 ? RtcEventLog::kUnlimitedOutput
3305 : rtc::saturated_cast<size_t>(max_size_bytes);
3306 return StartRtcEventLog(
Karl Wiberg918f50c2018-07-05 11:40:33 +02003307 absl::make_unique<RtcEventLogOutputFile>(file, max_size),
Bjorn Tereliusde939432017-11-20 17:38:14 +01003308 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02003309}
3310
Bjorn Tereliusde939432017-11-20 17:38:14 +01003311bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
3312 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02003313 // TODO(eladalon): In C++14, this can be done with a lambda.
3314 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01003315 bool operator()() {
3316 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
3317 }
Karl Wibergd6b48192017-10-16 23:01:06 +02003318 PeerConnection* const pc;
3319 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01003320 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02003321 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01003322 return worker_thread()->Invoke<bool>(
3323 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07003324}
3325
3326void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07003327 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07003328 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
3329}
3330
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003331const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003332 return pending_local_description_ ? pending_local_description_.get()
3333 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003334}
3335
3336const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08003337 return pending_remote_description_ ? pending_remote_description_.get()
3338 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003339}
3340
deadbeeffe4a8a42016-12-20 17:56:17 -08003341const SessionDescriptionInterface* PeerConnection::current_local_description()
3342 const {
Steve Anton75737c02017-11-06 10:37:17 -08003343 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003344}
3345
3346const SessionDescriptionInterface* PeerConnection::current_remote_description()
3347 const {
Steve Anton75737c02017-11-06 10:37:17 -08003348 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003349}
3350
3351const SessionDescriptionInterface* PeerConnection::pending_local_description()
3352 const {
Steve Anton75737c02017-11-06 10:37:17 -08003353 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003354}
3355
3356const SessionDescriptionInterface* PeerConnection::pending_remote_description()
3357 const {
Steve Anton75737c02017-11-06 10:37:17 -08003358 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08003359}
3360
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003361void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01003362 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003363 // Update stats here so that we have the most recent stats for tracks and
3364 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00003365 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003366
Steve Anton75737c02017-11-06 10:37:17 -08003367 ChangeSignalingState(PeerConnectionInterface::kClosed);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003368 NoteUsageEvent(UsageEvent::CLOSE_CALLED);
Steve Anton3fe1b152017-12-12 10:20:08 -08003369
Steve Anton8af21862017-12-15 11:20:13 -08003370 for (auto transceiver : transceivers_) {
3371 transceiver->Stop();
3372 }
Steve Anton25cfeb92018-04-26 11:44:00 -07003373
3374 // Ensure that all asynchronous stats requests are completed before destroying
3375 // the transport controller below.
3376 if (stats_collector_) {
3377 stats_collector_->WaitForPendingRequest();
3378 }
3379
3380 // Don't destroy BaseChannels until after stats has been cleaned up so that
3381 // the last stats request can still read from the channels.
Steve Anton8af21862017-12-15 11:20:13 -08003382 DestroyAllChannels();
Steve Anton75737c02017-11-06 10:37:17 -08003383
Qingsi Wang93a84392018-01-30 17:13:09 -08003384 // The event log is used in the transport controller, which must be outlived
3385 // by the former. CreateOffer by the peer connection is implemented
3386 // asynchronously and if the peer connection is closed without resetting the
3387 // WebRTC session description factory, the session description factory would
3388 // call the transport controller.
3389 webrtc_session_desc_factory_.reset();
3390 transport_controller_.reset();
3391
deadbeef42a42632017-03-10 15:18:00 -08003392 network_thread()->Invoke<void>(
Yves Gerey665174f2018-06-19 15:03:05 +02003393 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
3394 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07003395
Steve Anton978b8762017-09-29 12:15:02 -07003396 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07003397 call_.reset();
3398 // The event log must outlive call (and any other object that uses it).
3399 event_log_.reset();
3400 });
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003401 ReportUsagePattern();
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003402 // The .h file says that observer can be discarded after close() returns.
3403 // Make sure this is true.
3404 observer_ = nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003405}
3406
Steve Antonad182762018-09-05 20:22:40 +00003407void PeerConnection::OnMessage(rtc::Message* msg) {
3408 switch (msg->message_id) {
3409 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
3410 SetSessionDescriptionMsg* param =
3411 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3412 param->observer->OnSuccess();
3413 delete param;
3414 break;
3415 }
3416 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
3417 SetSessionDescriptionMsg* param =
3418 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
3419 param->observer->OnFailure(std::move(param->error));
3420 delete param;
3421 break;
3422 }
3423 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
3424 CreateSessionDescriptionMsg* param =
3425 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
3426 param->observer->OnFailure(std::move(param->error));
3427 delete param;
3428 break;
3429 }
3430 case MSG_GETSTATS: {
3431 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
3432 StatsReports reports;
3433 stats_->GetStats(param->track, &reports);
3434 param->observer->OnComplete(reports);
3435 delete param;
3436 break;
3437 }
3438 case MSG_FREE_DATACHANNELS: {
3439 sctp_data_channels_to_free_.clear();
3440 break;
3441 }
3442 case MSG_REPORT_USAGE_PATTERN: {
3443 ReportUsagePattern();
3444 break;
3445 }
3446 default:
3447 RTC_NOTREACHED() << "Not implemented";
3448 break;
3449 }
3450}
3451
Steve Antonafb0bb72018-02-20 11:35:37 -08003452cricket::VoiceMediaChannel* PeerConnection::voice_media_channel() const {
3453 RTC_DCHECK(!IsUnifiedPlan());
3454 auto* voice_channel = static_cast<cricket::VoiceChannel*>(
3455 GetAudioTransceiver()->internal()->channel());
3456 if (voice_channel) {
3457 return voice_channel->media_channel();
3458 } else {
3459 return nullptr;
3460 }
3461}
3462
3463cricket::VideoMediaChannel* PeerConnection::video_media_channel() const {
3464 RTC_DCHECK(!IsUnifiedPlan());
3465 auto* video_channel = static_cast<cricket::VideoChannel*>(
3466 GetVideoTransceiver()->internal()->channel());
3467 if (video_channel) {
3468 return video_channel->media_channel();
3469 } else {
3470 return nullptr;
3471 }
3472}
3473
Steve Anton4171afb2017-11-20 10:20:22 -08003474void PeerConnection::CreateAudioReceiver(
3475 MediaStreamInterface* stream,
3476 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003477 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3478 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003479 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3480 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003481 auto* audio_receiver = new AudioRtpReceiver(
3482 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003483 audio_receiver->SetVoiceMediaChannel(voice_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003484 audio_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3485 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3486 signaling_thread(), audio_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003487 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003488 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003489 NoteUsageEvent(UsageEvent::AUDIO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003490}
3491
Steve Anton4171afb2017-11-20 10:20:22 -08003492void PeerConnection::CreateVideoReceiver(
3493 MediaStreamInterface* stream,
3494 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01003495 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
3496 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
Henrik Boström199e27b2018-07-04 20:51:53 +02003497 // TODO(https://crbug.com/webrtc/9480): When we remove remote_streams(), use
3498 // the constructor taking stream IDs instead.
Steve Antond3679212018-01-17 17:41:02 -08003499 auto* video_receiver = new VideoRtpReceiver(
3500 worker_thread(), remote_sender_info.sender_id, streams);
Steve Anton57858b32018-02-15 15:19:50 -08003501 video_receiver->SetVideoMediaChannel(video_media_channel());
Steve Antond3679212018-01-17 17:41:02 -08003502 video_receiver->SetupMediaChannel(remote_sender_info.first_ssrc);
3503 auto receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
3504 signaling_thread(), video_receiver);
Steve Anton4171afb2017-11-20 10:20:22 -08003505 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003506 Observer()->OnAddTrack(receiver, std::move(streams));
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003507 NoteUsageEvent(UsageEvent::VIDEO_ADDED);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003508}
3509
deadbeef70ab1a12015-09-28 16:53:55 -07003510// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
3511// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07003512rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08003513 const RtpSenderInfo& remote_sender_info) {
3514 auto receiver = FindReceiverById(remote_sender_info.sender_id);
3515 if (!receiver) {
3516 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
3517 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07003518 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003519 }
Steve Anton4171afb2017-11-20 10:20:22 -08003520 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3521 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
3522 } else {
3523 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
3524 }
Henrik Boström933d8b02017-10-10 10:05:16 -07003525 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003526}
3527
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003528void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
3529 MediaStreamInterface* stream) {
3530 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003531 RTC_DCHECK(track);
3532 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003533 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003534 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003535 // We already have a sender for this track, so just change the stream_id
3536 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003537 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003538 return;
3539 }
3540
3541 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003542 auto new_sender = CreateSender(cricket::MEDIA_TYPE_AUDIO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003543 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003544 new_sender->internal()->SetVoiceMediaChannel(voice_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003545 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003546 // If the sender has already been configured in SDP, we call SetSsrc,
3547 // which will connect the sender to the underlying transport. This can
3548 // occur if a local session description that contains the ID of the sender
3549 // is set before AddStream is called. It can also occur if the local
3550 // session description is not changed and RemoveStream is called, and
3551 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08003552 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003553 FindSenderInfo(local_audio_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003554 if (sender_info) {
3555 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003556 }
3557}
3558
3559// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
3560// indefinitely, when we have unified plan SDP.
3561void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
3562 MediaStreamInterface* stream) {
3563 RTC_DCHECK(!IsClosed());
3564 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003565 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003566 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3567 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003568 return;
3569 }
Steve Anton4171afb2017-11-20 10:20:22 -08003570 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003571}
3572
3573void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
3574 MediaStreamInterface* stream) {
3575 RTC_DCHECK(!IsClosed());
Steve Anton111fdfd2018-06-25 13:03:36 -07003576 RTC_DCHECK(track);
3577 RTC_DCHECK(stream);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003578 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003579 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003580 // We already have a sender for this track, so just change the stream_id
3581 // so that it's correct in the next call to CreateOffer.
Seth Hampson5b4f0752018-04-02 16:31:36 -07003582 sender->internal()->set_stream_ids({stream->id()});
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003583 return;
3584 }
3585
3586 // Normal case; we've never seen this track before.
Steve Anton111fdfd2018-06-25 13:03:36 -07003587 auto new_sender = CreateSender(cricket::MEDIA_TYPE_VIDEO, track->id(), track,
Florent Castelli892acf02018-10-01 22:47:20 +02003588 {stream->id()}, {});
Steve Anton57858b32018-02-15 15:19:50 -08003589 new_sender->internal()->SetVideoMediaChannel(video_media_channel());
Steve Anton4171afb2017-11-20 10:20:22 -08003590 GetVideoTransceiver()->internal()->AddSender(new_sender);
3591 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00003592 FindSenderInfo(local_video_sender_infos_, stream->id(), track->id());
Steve Anton4171afb2017-11-20 10:20:22 -08003593 if (sender_info) {
3594 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003595 }
3596}
3597
3598void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
3599 MediaStreamInterface* stream) {
3600 RTC_DCHECK(!IsClosed());
3601 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08003602 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003603 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
3604 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003605 return;
3606 }
Steve Anton4171afb2017-11-20 10:20:22 -08003607 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003608}
3609
Steve Antonba818672017-11-06 10:21:57 -08003610void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003611 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08003612 if (ice_connection_state_ == new_state) {
3613 return;
3614 }
3615
deadbeefcbecd352015-09-23 11:50:27 -07003616 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08003617 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07003618 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07003619 return;
3620 }
Steve Antonba818672017-11-06 10:21:57 -08003621
Mirko Bonadei675513b2017-11-09 11:09:25 +01003622 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
3623 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08003624 RTC_DCHECK(ice_connection_state_ !=
3625 PeerConnectionInterface::kIceConnectionClosed);
3626
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003627 ice_connection_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003628 Observer()->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003629}
3630
Jonas Olsson635474e2018-10-18 15:58:17 +02003631void PeerConnection::SetStandardizedIceConnectionState(
3632 PeerConnectionInterface::IceConnectionState new_state) {
3633 RTC_DCHECK(signaling_thread()->IsCurrent());
3634 if (standardized_ice_connection_state_ == new_state)
3635 return;
3636 if (IsClosed())
3637 return;
3638 standardized_ice_connection_state_ = new_state;
3639 // TODO(jonasolsson): Pass this value on to OnIceConnectionChange instead of
3640 // the old one once disconnects are handled properly.
3641}
3642
3643void PeerConnection::SetConnectionState(
3644 PeerConnectionInterface::PeerConnectionState new_state) {
3645 RTC_DCHECK(signaling_thread()->IsCurrent());
3646 if (connection_state_ == new_state)
3647 return;
3648 if (IsClosed())
3649 return;
3650 connection_state_ = new_state;
3651 Observer()->OnConnectionChange(new_state);
3652}
3653
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003654void PeerConnection::OnIceGatheringChange(
3655 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003656 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003657 if (IsClosed()) {
3658 return;
3659 }
3660 ice_gathering_state_ = new_state;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003661 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003662}
3663
jbauch81bf7b02017-03-25 08:31:12 -07003664void PeerConnection::OnIceCandidate(
3665 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07003666 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003667 if (IsClosed()) {
3668 return;
3669 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02003670 NoteUsageEvent(UsageEvent::CANDIDATE_COLLECTED);
Harald Alvestrand056d8112018-07-16 19:18:58 +02003671 if (candidate->candidate().type() == LOCAL_PORT_TYPE &&
3672 candidate->candidate().address().IsPrivateIP()) {
3673 NoteUsageEvent(UsageEvent::PRIVATE_CANDIDATE_COLLECTED);
3674 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003675 Observer()->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003676}
3677
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003678void PeerConnection::OnIceCandidatesRemoved(
3679 const std::vector<cricket::Candidate>& candidates) {
3680 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07003681 if (IsClosed()) {
3682 return;
3683 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003684 Observer()->OnIceCandidatesRemoved(candidates);
Honghai Zhang7fb69db2016-03-14 11:59:18 -07003685}
3686
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003687void PeerConnection::ChangeSignalingState(
3688 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08003689 RTC_DCHECK(signaling_thread()->IsCurrent());
3690 if (signaling_state_ == signaling_state) {
3691 return;
3692 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01003693 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
3694 << GetSignalingStateString(signaling_state_)
3695 << " New state: "
3696 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003697 signaling_state_ = signaling_state;
3698 if (signaling_state == kClosed) {
3699 ice_connection_state_ = kIceConnectionClosed;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003700 Observer()->OnIceConnectionChange(ice_connection_state_);
Jonas Olsson635474e2018-10-18 15:58:17 +02003701 standardized_ice_connection_state_ =
3702 PeerConnectionInterface::IceConnectionState::kIceConnectionClosed;
3703 connection_state_ = PeerConnectionInterface::PeerConnectionState::kClosed;
3704 Observer()->OnConnectionChange(connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003705 if (ice_gathering_state_ != kIceGatheringComplete) {
3706 ice_gathering_state_ = kIceGatheringComplete;
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003707 Observer()->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003708 }
3709 }
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003710 Observer()->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003711}
3712
deadbeefeb459812015-12-15 19:24:43 -08003713void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
3714 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003715 if (IsClosed()) {
3716 return;
3717 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003718 AddAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003719 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003720}
3721
deadbeefeb459812015-12-15 19:24:43 -08003722void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
3723 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003724 if (IsClosed()) {
3725 return;
3726 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003727 RemoveAudioTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003728 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003729}
3730
3731void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
3732 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003733 if (IsClosed()) {
3734 return;
3735 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003736 AddVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003737 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003738}
3739
3740void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
3741 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07003742 if (IsClosed()) {
3743 return;
3744 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07003745 RemoveVideoTrack(track, stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02003746 Observer()->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08003747}
3748
Henrik Boström31638672017-11-23 17:48:32 +01003749void PeerConnection::PostSetSessionDescriptionSuccess(
3750 SetSessionDescriptionObserver* observer) {
Steve Antonad182762018-09-05 20:22:40 +00003751 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3752 signaling_thread()->Post(RTC_FROM_HERE, this,
3753 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
Henrik Boström31638672017-11-23 17:48:32 +01003754}
3755
deadbeefab9b2d12015-10-14 11:33:11 -07003756void PeerConnection::PostSetSessionDescriptionFailure(
3757 SetSessionDescriptionObserver* observer,
Steve Antonad182762018-09-05 20:22:40 +00003758 RTCError&& error) {
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003759 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003760 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
3761 msg->error = std::move(error);
3762 signaling_thread()->Post(RTC_FROM_HERE, this,
3763 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003764}
3765
3766void PeerConnection::PostCreateSessionDescriptionFailure(
3767 CreateSessionDescriptionObserver* observer,
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01003768 RTCError error) {
3769 RTC_DCHECK(!error.ok());
Steve Antonad182762018-09-05 20:22:40 +00003770 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
3771 msg->error = std::move(error);
3772 signaling_thread()->Post(RTC_FROM_HERE, this,
3773 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07003774}
3775
zhihuang1c378ed2017-08-17 14:10:50 -07003776void PeerConnection::GetOptionsForOffer(
Steve Antondcc3c022017-12-22 16:02:54 -08003777 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
deadbeefab9b2d12015-10-14 11:33:11 -07003778 cricket::MediaSessionOptions* session_options) {
Steve Antondcc3c022017-12-22 16:02:54 -08003779 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07003780
Steve Antondcc3c022017-12-22 16:02:54 -08003781 if (IsUnifiedPlan()) {
3782 GetOptionsForUnifiedPlanOffer(offer_answer_options, session_options);
3783 } else {
3784 GetOptionsForPlanBOffer(offer_answer_options, session_options);
3785 }
3786
Steve Antonfa2260d2017-12-28 16:38:23 -08003787 // Intentionally unset the data channel type for RTP data channel with the
3788 // second condition. Otherwise the RTP data channels would be successfully
3789 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
3790 // when building with chromium. We want to leave RTP data channels broken, so
3791 // people won't try to use them.
3792 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
3793 session_options->data_channel_type = data_channel_type();
3794 }
3795
Steve Antondcc3c022017-12-22 16:02:54 -08003796 // Apply ICE restart flag and renomination flag.
3797 for (auto& options : session_options->media_description_options) {
3798 options.transport_options.ice_restart = offer_answer_options.ice_restart;
3799 options.transport_options.enable_ice_renomination =
3800 configuration_.enable_ice_renomination;
3801 }
3802
3803 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07003804 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08003805 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02003806 session_options->pooled_ice_credentials =
3807 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
3808 RTC_FROM_HERE,
3809 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
3810 port_allocator_.get()));
Steve Antondcc3c022017-12-22 16:02:54 -08003811}
3812
3813void PeerConnection::GetOptionsForPlanBOffer(
3814 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
3815 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07003816 // Figure out transceiver directional preferences.
3817 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
3818 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
3819
3820 // By default, generate sendrecv/recvonly m= sections.
3821 bool recv_audio = true;
3822 bool recv_video = true;
3823
3824 // By default, only offer a new m= section if we have media to send with it.
3825 bool offer_new_audio_description = send_audio;
3826 bool offer_new_video_description = send_video;
3827 bool offer_new_data_description = HasDataChannels();
3828
3829 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08003830 if (offer_answer_options.offer_to_receive_audio !=
3831 RTCOfferAnswerOptions::kUndefined) {
3832 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003833 offer_new_audio_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003834 offer_new_audio_description ||
3835 (offer_answer_options.offer_to_receive_audio > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003836 }
Steve Antondcc3c022017-12-22 16:02:54 -08003837 if (offer_answer_options.offer_to_receive_video !=
3838 RTCOfferAnswerOptions::kUndefined) {
3839 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003840 offer_new_video_description =
Steve Antondcc3c022017-12-22 16:02:54 -08003841 offer_new_video_description ||
3842 (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07003843 }
3844
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02003845 absl::optional<size_t> audio_index;
3846 absl::optional<size_t> video_index;
3847 absl::optional<size_t> data_index;
zhihuang1c378ed2017-08-17 14:10:50 -07003848 // If a current description exists, generate m= sections in the same order,
3849 // using the first audio/video/data section that appears and rejecting
3850 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08003851 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07003852 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08003853 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08003854 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3855 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3856 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07003857 }
3858
zhihuang1c378ed2017-08-17 14:10:50 -07003859 // Add audio/video/data m= sections to the end if needed.
3860 if (!audio_index && offer_new_audio_description) {
3861 session_options->media_description_options.push_back(
3862 cricket::MediaDescriptionOptions(
3863 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08003864 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
3865 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003866 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003867 }
zhihuang1c378ed2017-08-17 14:10:50 -07003868 if (!video_index && offer_new_video_description) {
3869 session_options->media_description_options.push_back(
3870 cricket::MediaDescriptionOptions(
3871 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08003872 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
3873 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003874 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07003875 }
zhihuang1c378ed2017-08-17 14:10:50 -07003876 if (!data_index && offer_new_data_description) {
3877 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08003878 GetMediaDescriptionOptionsForActiveData(cricket::CN_DATA));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003879 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07003880 }
3881
3882 cricket::MediaDescriptionOptions* audio_media_description_options =
3883 !audio_index ? nullptr
3884 : &session_options->media_description_options[*audio_index];
3885 cricket::MediaDescriptionOptions* video_media_description_options =
3886 !video_index ? nullptr
3887 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07003888
Steve Anton4171afb2017-11-20 10:20:22 -08003889 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02003890 video_media_description_options,
3891 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08003892}
3893
3894// Find a new MID that is not already in |used_mids|, then add it to |used_mids|
3895// and return a reference to it.
3896// Generated MIDs should be no more than 3 bytes long to take up less space in
3897// the RTP packet.
3898static const std::string& AllocateMid(std::set<std::string>* used_mids) {
3899 RTC_DCHECK(used_mids);
3900 // We're boring: just generate MIDs 0, 1, 2, ...
3901 size_t i = 0;
3902 std::set<std::string>::iterator it;
3903 bool inserted;
3904 do {
3905 std::string mid = rtc::ToString(i++);
3906 auto insert_result = used_mids->insert(mid);
3907 it = insert_result.first;
3908 inserted = insert_result.second;
3909 } while (!inserted);
3910 return *it;
3911}
3912
3913static cricket::MediaDescriptionOptions
3914GetMediaDescriptionOptionsForTransceiver(
3915 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3916 transceiver,
3917 const std::string& mid) {
3918 cricket::MediaDescriptionOptions media_description_options(
Steve Anton69470252018-02-09 11:43:08 -08003919 transceiver->media_type(), mid, transceiver->direction(),
Steve Antondcc3c022017-12-22 16:02:54 -08003920 transceiver->stopped());
Steve Anton5f94aa22018-02-01 10:58:30 -08003921 // This behavior is specified in JSEP. The gist is that:
3922 // 1. The MSID is included if the RtpTransceiver's direction is sendonly or
3923 // sendrecv.
3924 // 2. If the MSID is included, then it must be included in any subsequent
3925 // offer/answer exactly the same until the RtpTransceiver is stopped.
3926 if (!transceiver->stopped() &&
3927 (RtpTransceiverDirectionHasSend(transceiver->direction()) ||
3928 transceiver->internal()->has_ever_been_used_to_send())) {
3929 cricket::SenderOptions sender_options;
3930 sender_options.track_id = transceiver->sender()->id();
3931 sender_options.stream_ids = transceiver->sender()->stream_ids();
Florent Castelli892acf02018-10-01 22:47:20 +02003932 int num_send_encoding_layers =
3933 transceiver->sender()->init_send_encodings().size();
3934 sender_options.num_sim_layers =
3935 !num_send_encoding_layers ? 1 : num_send_encoding_layers;
Steve Anton5f94aa22018-02-01 10:58:30 -08003936 media_description_options.sender_options.push_back(sender_options);
3937 }
Steve Antondcc3c022017-12-22 16:02:54 -08003938 return media_description_options;
3939}
3940
3941void PeerConnection::GetOptionsForUnifiedPlanOffer(
3942 const RTCOfferAnswerOptions& offer_answer_options,
3943 cricket::MediaSessionOptions* session_options) {
3944 // Rules for generating an offer are dictated by JSEP sections 5.2.1 (Initial
3945 // Offers) and 5.2.2 (Subsequent Offers).
3946 RTC_DCHECK_EQ(session_options->media_description_options.size(), 0);
3947 const ContentInfos& local_contents =
3948 (local_description() ? local_description()->description()->contents()
3949 : ContentInfos());
3950 const ContentInfos& remote_contents =
3951 (remote_description() ? remote_description()->description()->contents()
3952 : ContentInfos());
3953 // The mline indices that can be recycled. New transceivers should reuse these
3954 // slots first.
3955 std::queue<size_t> recycleable_mline_indices;
3956 // Track the MIDs used in previous offer/answer exchanges and the current
3957 // offer so that new, unique MIDs are generated.
3958 std::set<std::string> used_mids = seen_mids_;
3959 // First, go through each media section that exists in either the local or
3960 // remote description and generate a media section in this offer for the
3961 // associated transceiver. If a media section can be recycled, generate a
3962 // default, rejected media section here that can be later overwritten.
3963 for (size_t i = 0;
3964 i < std::max(local_contents.size(), remote_contents.size()); ++i) {
3965 // Either |local_content| or |remote_content| is non-null.
3966 const ContentInfo* local_content =
3967 (i < local_contents.size() ? &local_contents[i] : nullptr);
3968 const ContentInfo* remote_content =
3969 (i < remote_contents.size() ? &remote_contents[i] : nullptr);
3970 bool had_been_rejected = (local_content && local_content->rejected) ||
3971 (remote_content && remote_content->rejected);
3972 const std::string& mid =
3973 (local_content ? local_content->name : remote_content->name);
3974 cricket::MediaType media_type =
3975 (local_content ? local_content->media_description()->type()
3976 : remote_content->media_description()->type());
3977 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
3978 media_type == cricket::MEDIA_TYPE_VIDEO) {
3979 auto transceiver = GetAssociatedTransceiver(mid);
3980 RTC_CHECK(transceiver);
3981 // A media section is considered eligible for recycling if it is marked as
3982 // rejected in either the local or remote description.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08003983 if (had_been_rejected && transceiver->stopped()) {
Steve Antondcc3c022017-12-22 16:02:54 -08003984 session_options->media_description_options.push_back(
Steve Anton69470252018-02-09 11:43:08 -08003985 cricket::MediaDescriptionOptions(transceiver->media_type(), mid,
3986 RtpTransceiverDirection::kInactive,
3987 /*stopped=*/true));
Steve Antondcc3c022017-12-22 16:02:54 -08003988 recycleable_mline_indices.push(i);
3989 } else {
3990 session_options->media_description_options.push_back(
3991 GetMediaDescriptionOptionsForTransceiver(transceiver, mid));
3992 // CreateOffer shouldn't really cause any state changes in
3993 // PeerConnection, but we need a way to match new transceivers to new
3994 // media sections in SetLocalDescription and JSEP specifies this is done
3995 // by recording the index of the media section generated for the
3996 // transceiver in the offer.
3997 transceiver->internal()->set_mline_index(i);
3998 }
3999 } else {
4000 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antonfa2260d2017-12-28 16:38:23 -08004001 RTC_CHECK(GetDataMid());
4002 if (had_been_rejected || mid != *GetDataMid()) {
4003 session_options->media_description_options.push_back(
4004 GetMediaDescriptionOptionsForRejectedData(mid));
4005 } else {
4006 session_options->media_description_options.push_back(
4007 GetMediaDescriptionOptionsForActiveData(mid));
4008 }
Steve Antondcc3c022017-12-22 16:02:54 -08004009 }
4010 }
4011 // Next, look for transceivers that are newly added (that is, are not stopped
4012 // and not associated). Reuse media sections marked as recyclable first,
4013 // otherwise append to the end of the offer. New media sections should be
4014 // added in the order they were added to the PeerConnection.
4015 for (auto transceiver : transceivers_) {
4016 if (transceiver->mid() || transceiver->stopped()) {
4017 continue;
4018 }
4019 size_t mline_index;
4020 if (!recycleable_mline_indices.empty()) {
4021 mline_index = recycleable_mline_indices.front();
4022 recycleable_mline_indices.pop();
4023 session_options->media_description_options[mline_index] =
4024 GetMediaDescriptionOptionsForTransceiver(transceiver,
4025 AllocateMid(&used_mids));
4026 } else {
4027 mline_index = session_options->media_description_options.size();
4028 session_options->media_description_options.push_back(
4029 GetMediaDescriptionOptionsForTransceiver(transceiver,
4030 AllocateMid(&used_mids)));
4031 }
4032 // See comment above for why CreateOffer changes the transceiver's state.
4033 transceiver->internal()->set_mline_index(mline_index);
4034 }
Steve Antonfa2260d2017-12-28 16:38:23 -08004035 // Lastly, add a m-section if we have local data channels and an m section
4036 // does not already exist.
4037 if (!GetDataMid() && HasDataChannels()) {
4038 session_options->media_description_options.push_back(
4039 GetMediaDescriptionOptionsForActiveData(AllocateMid(&used_mids)));
4040 }
Steve Antondcc3c022017-12-22 16:02:54 -08004041}
4042
4043void PeerConnection::GetOptionsForAnswer(
4044 const RTCOfferAnswerOptions& offer_answer_options,
4045 cricket::MediaSessionOptions* session_options) {
4046 ExtractSharedMediaSessionOptions(offer_answer_options, session_options);
4047
4048 if (IsUnifiedPlan()) {
4049 GetOptionsForUnifiedPlanAnswer(offer_answer_options, session_options);
4050 } else {
4051 GetOptionsForPlanBAnswer(offer_answer_options, session_options);
4052 }
4053
Steve Antonfa2260d2017-12-28 16:38:23 -08004054 // Intentionally unset the data channel type for RTP data channel. Otherwise
4055 // the RTP data channels would be successfully negotiated by default and the
4056 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
4057 // We want to leave RTP data channels broken, so people won't try to use them.
4058 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
4059 session_options->data_channel_type = data_channel_type();
4060 }
4061
Steve Antondcc3c022017-12-22 16:02:54 -08004062 // Apply ICE renomination flag.
4063 for (auto& options : session_options->media_description_options) {
4064 options.transport_options.enable_ice_renomination =
4065 configuration_.enable_ice_renomination;
4066 }
zhihuang8f65cdf2016-05-06 18:40:30 -07004067
4068 session_options->rtcp_cname = rtcp_cname_;
Benjamin Wright8c27cca2018-10-25 10:16:44 -07004069 session_options->crypto_options = GetCryptoOptions();
Steve Antone831b8c2018-02-01 12:22:16 -08004070 session_options->is_unified_plan = IsUnifiedPlan();
Jonas Oreland1cd39fa2018-10-11 07:47:12 +02004071 session_options->pooled_ice_credentials =
4072 network_thread()->Invoke<std::vector<cricket::IceParameters>>(
4073 RTC_FROM_HERE,
4074 rtc::Bind(&cricket::PortAllocator::GetPooledIceCredentials,
4075 port_allocator_.get()));
deadbeefab9b2d12015-10-14 11:33:11 -07004076}
4077
Steve Antondcc3c022017-12-22 16:02:54 -08004078void PeerConnection::GetOptionsForPlanBAnswer(
4079 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07004080 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004081 // Figure out transceiver directional preferences.
4082 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
4083 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
4084
4085 // By default, generate sendrecv/recvonly m= sections. The direction is also
4086 // restricted by the direction in the offer.
4087 bool recv_audio = true;
4088 bool recv_video = true;
4089
4090 // The "offer_to_receive_X" options allow those defaults to be overridden.
Steve Antondcc3c022017-12-22 16:02:54 -08004091 if (offer_answer_options.offer_to_receive_audio !=
4092 RTCOfferAnswerOptions::kUndefined) {
4093 recv_audio = (offer_answer_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08004094 }
Steve Antondcc3c022017-12-22 16:02:54 -08004095 if (offer_answer_options.offer_to_receive_video !=
4096 RTCOfferAnswerOptions::kUndefined) {
4097 recv_video = (offer_answer_options.offer_to_receive_video > 0);
zhihuang1c378ed2017-08-17 14:10:50 -07004098 }
4099
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004100 absl::optional<size_t> audio_index;
4101 absl::optional<size_t> video_index;
4102 absl::optional<size_t> data_index;
Steve Antondffead82018-02-06 10:31:29 -08004103
4104 // Generate m= sections that match those in the offer.
4105 // Note that mediasession.cc will handle intersection our preferred
4106 // direction with the offered direction.
4107 GenerateMediaDescriptionOptions(
4108 remote_description(),
4109 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
4110 RtpTransceiverDirectionFromSendRecv(send_video, recv_video), &audio_index,
4111 &video_index, &data_index, session_options);
zhihuang1c378ed2017-08-17 14:10:50 -07004112
4113 cricket::MediaDescriptionOptions* audio_media_description_options =
4114 !audio_index ? nullptr
4115 : &session_options->media_description_options[*audio_index];
4116 cricket::MediaDescriptionOptions* video_media_description_options =
4117 !video_index ? nullptr
4118 : &session_options->media_description_options[*video_index];
zhihuang1c378ed2017-08-17 14:10:50 -07004119
Steve Anton4171afb2017-11-20 10:20:22 -08004120 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
Jonas Orelandfc1acd22018-08-24 10:58:37 +02004121 video_media_description_options,
4122 offer_answer_options.num_simulcast_layers);
Steve Antondcc3c022017-12-22 16:02:54 -08004123}
zhihuangaf388472016-11-02 16:49:48 -07004124
Steve Antondcc3c022017-12-22 16:02:54 -08004125void PeerConnection::GetOptionsForUnifiedPlanAnswer(
4126 const PeerConnectionInterface::RTCOfferAnswerOptions& offer_answer_options,
4127 cricket::MediaSessionOptions* session_options) {
4128 // Rules for generating an answer are dictated by JSEP sections 5.3.1 (Initial
4129 // Answers) and 5.3.2 (Subsequent Answers).
4130 RTC_DCHECK(remote_description());
4131 RTC_DCHECK(remote_description()->GetType() == SdpType::kOffer);
4132 for (const ContentInfo& content :
4133 remote_description()->description()->contents()) {
4134 cricket::MediaType media_type = content.media_description()->type();
4135 if (media_type == cricket::MEDIA_TYPE_AUDIO ||
4136 media_type == cricket::MEDIA_TYPE_VIDEO) {
4137 auto transceiver = GetAssociatedTransceiver(content.name);
4138 RTC_CHECK(transceiver);
4139 session_options->media_description_options.push_back(
4140 GetMediaDescriptionOptionsForTransceiver(transceiver, content.name));
4141 } else {
4142 RTC_CHECK_EQ(cricket::MEDIA_TYPE_DATA, media_type);
Steve Antondbf9d032018-01-19 15:23:40 -08004143 // Reject all data sections if data channels are disabled.
4144 // Reject a data section if it has already been rejected.
4145 // Reject all data sections except for the first one.
4146 if (data_channel_type_ == cricket::DCT_NONE || content.rejected ||
4147 content.name != *GetDataMid()) {
Steve Antonfa2260d2017-12-28 16:38:23 -08004148 session_options->media_description_options.push_back(
4149 GetMediaDescriptionOptionsForRejectedData(content.name));
4150 } else {
4151 session_options->media_description_options.push_back(
4152 GetMediaDescriptionOptionsForActiveData(content.name));
4153 }
Steve Antondcc3c022017-12-22 16:02:54 -08004154 }
4155 }
htaa2a49d92016-03-04 02:51:39 -08004156}
4157
zhihuang1c378ed2017-08-17 14:10:50 -07004158void PeerConnection::GenerateMediaDescriptionOptions(
4159 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08004160 RtpTransceiverDirection audio_direction,
4161 RtpTransceiverDirection video_direction,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004162 absl::optional<size_t>* audio_index,
4163 absl::optional<size_t>* video_index,
4164 absl::optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08004165 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07004166 for (const cricket::ContentInfo& content :
4167 session_desc->description()->contents()) {
4168 if (IsAudioContent(&content)) {
4169 // If we already have an audio m= section, reject this extra one.
4170 if (*audio_index) {
4171 session_options->media_description_options.push_back(
4172 cricket::MediaDescriptionOptions(
4173 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004174 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004175 } else {
4176 session_options->media_description_options.push_back(
4177 cricket::MediaDescriptionOptions(
4178 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004179 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004180 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004181 }
4182 } else if (IsVideoContent(&content)) {
4183 // If we already have an video m= section, reject this extra one.
4184 if (*video_index) {
4185 session_options->media_description_options.push_back(
4186 cricket::MediaDescriptionOptions(
4187 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08004188 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07004189 } else {
4190 session_options->media_description_options.push_back(
4191 cricket::MediaDescriptionOptions(
4192 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08004193 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004194 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004195 }
4196 } else {
4197 RTC_DCHECK(IsDataContent(&content));
4198 // If we already have an data m= section, reject this extra one.
4199 if (*data_index) {
4200 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004201 GetMediaDescriptionOptionsForRejectedData(content.name));
zhihuang1c378ed2017-08-17 14:10:50 -07004202 } else {
4203 session_options->media_description_options.push_back(
Steve Antonfa2260d2017-12-28 16:38:23 -08004204 GetMediaDescriptionOptionsForActiveData(content.name));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004205 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07004206 }
4207 }
htaa2a49d92016-03-04 02:51:39 -08004208 }
deadbeefab9b2d12015-10-14 11:33:11 -07004209}
4210
Steve Antonfa2260d2017-12-28 16:38:23 -08004211cricket::MediaDescriptionOptions
4212PeerConnection::GetMediaDescriptionOptionsForActiveData(
4213 const std::string& mid) const {
4214 // Direction for data sections is meaningless, but legacy endpoints might
4215 // expect sendrecv.
4216 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4217 RtpTransceiverDirection::kSendRecv,
4218 /*stopped=*/false);
4219 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4220 return options;
4221}
4222
4223cricket::MediaDescriptionOptions
4224PeerConnection::GetMediaDescriptionOptionsForRejectedData(
4225 const std::string& mid) const {
4226 cricket::MediaDescriptionOptions options(cricket::MEDIA_TYPE_DATA, mid,
4227 RtpTransceiverDirection::kInactive,
4228 /*stopped=*/true);
4229 AddRtpDataChannelOptions(rtp_data_channels_, &options);
4230 return options;
4231}
4232
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004233absl::optional<std::string> PeerConnection::GetDataMid() const {
Steve Antonfa2260d2017-12-28 16:38:23 -08004234 switch (data_channel_type_) {
4235 case cricket::DCT_RTP:
4236 if (!rtp_data_channel_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004237 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004238 }
4239 return rtp_data_channel_->content_name();
4240 case cricket::DCT_SCTP:
Zhi Huange830e682018-03-30 10:48:35 -07004241 return sctp_mid_;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004242 case cricket::DCT_MEDIA_TRANSPORT:
4243 return media_transport_data_mid_;
Steve Antonfa2260d2017-12-28 16:38:23 -08004244 default:
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004245 return absl::nullopt;
Steve Antonfa2260d2017-12-28 16:38:23 -08004246 }
4247}
4248
Steve Anton4171afb2017-11-20 10:20:22 -08004249void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
4250 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
4251 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08004252 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08004253}
4254
Steve Anton4171afb2017-11-20 10:20:22 -08004255void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07004256 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08004257 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07004258 cricket::MediaType media_type,
4259 StreamCollection* new_streams) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004260 RTC_DCHECK(!IsUnifiedPlan());
4261
Steve Anton4171afb2017-11-20 10:20:22 -08004262 std::vector<RtpSenderInfo>* current_senders =
4263 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004264
Steve Anton4171afb2017-11-20 10:20:22 -08004265 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08004266 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004267 for (auto sender_it = current_senders->begin();
4268 sender_it != current_senders->end();
4269 /* incremented manually */) {
4270 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004271 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004272 cricket::GetStreamBySsrc(streams, info.first_ssrc);
Seth Hampson83d676b2018-04-05 18:12:09 -07004273 std::string params_stream_id;
4274 if (params) {
4275 params_stream_id =
4276 (!params->first_stream_id().empty() ? params->first_stream_id()
4277 : kDefaultStreamId);
4278 }
Seth Hampson5b4f0752018-04-02 16:31:36 -07004279 bool sender_exists = params && params->id == info.sender_id &&
Seth Hampson83d676b2018-04-05 18:12:09 -07004280 params_stream_id == info.stream_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08004281 // If this is a default track, and we still need it, don't remove it.
Seth Hampson845e8782018-03-02 11:34:10 -08004282 if ((info.stream_id == kDefaultStreamId && default_sender_needed) ||
Steve Anton4171afb2017-11-20 10:20:22 -08004283 sender_exists) {
4284 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08004285 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004286 OnRemoteSenderRemoved(info, media_type);
4287 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004288 }
4289 }
4290
Steve Anton4171afb2017-11-20 10:20:22 -08004291 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004292 for (const cricket::StreamParams& params : streams) {
Seth Hampson5897a6e2018-04-03 11:16:33 -07004293 if (!params.has_ssrcs()) {
4294 // The remote endpoint has streams, but didn't signal ssrcs. For an active
4295 // sender, this means it is coming from a Unified Plan endpoint,so we just
4296 // create a default.
4297 default_sender_needed = true;
4298 break;
4299 }
4300
Seth Hampson845e8782018-03-02 11:34:10 -08004301 // |params.id| is the sender id and the stream id uses the first of
Seth Hampson5b4f0752018-04-02 16:31:36 -07004302 // |params.stream_ids|. The remote description could come from a Unified
Seth Hampson5897a6e2018-04-03 11:16:33 -07004303 // Plan endpoint, with multiple or no stream_ids() signaled. Since this is
4304 // not supported in Plan B, we just take the first here and create the
4305 // default stream ID if none is specified.
Seth Hampson845e8782018-03-02 11:34:10 -08004306 const std::string& stream_id =
Seth Hampson83d676b2018-04-05 18:12:09 -07004307 (!params.first_stream_id().empty() ? params.first_stream_id()
4308 : kDefaultStreamId);
Steve Anton4171afb2017-11-20 10:20:22 -08004309 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004310 uint32_t ssrc = params.first_ssrc();
4311
4312 rtc::scoped_refptr<MediaStreamInterface> stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004313 remote_streams_->find(stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004314 if (!stream) {
4315 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004316 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
Seth Hampson845e8782018-03-02 11:34:10 -08004317 MediaStream::Create(stream_id));
deadbeefab9b2d12015-10-14 11:33:11 -07004318 remote_streams_->AddStream(stream);
4319 new_streams->AddStream(stream);
4320 }
4321
Steve Anton4171afb2017-11-20 10:20:22 -08004322 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004323 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004324 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004325 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004326 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004327 }
4328 }
deadbeefbda7e0b2015-12-08 17:13:40 -08004329
Steve Anton4171afb2017-11-20 10:20:22 -08004330 // Add default sender if necessary.
4331 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08004332 rtc::scoped_refptr<MediaStreamInterface> default_stream =
Seth Hampson845e8782018-03-02 11:34:10 -08004333 remote_streams_->find(kDefaultStreamId);
deadbeefbda7e0b2015-12-08 17:13:40 -08004334 if (!default_stream) {
4335 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07004336 default_stream = MediaStreamProxy::Create(
Seth Hampson845e8782018-03-02 11:34:10 -08004337 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamId));
deadbeefbda7e0b2015-12-08 17:13:40 -08004338 remote_streams_->AddStream(default_stream);
4339 new_streams->AddStream(default_stream);
4340 }
Steve Anton4171afb2017-11-20 10:20:22 -08004341 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
4342 ? kDefaultAudioSenderId
4343 : kDefaultVideoSenderId;
Seth Hampson845e8782018-03-02 11:34:10 -08004344 const RtpSenderInfo* default_sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004345 FindSenderInfo(*current_senders, kDefaultStreamId, default_sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004346 if (!default_sender_info) {
4347 current_senders->push_back(
Seth Hampson845e8782018-03-02 11:34:10 -08004348 RtpSenderInfo(kDefaultStreamId, default_sender_id, 0));
Steve Anton4171afb2017-11-20 10:20:22 -08004349 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08004350 }
4351 }
deadbeefab9b2d12015-10-14 11:33:11 -07004352}
4353
Steve Anton4171afb2017-11-20 10:20:22 -08004354void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
4355 cricket::MediaType media_type) {
Steve Anton3d954a62018-04-02 11:27:23 -07004356 RTC_LOG(LS_INFO) << "Creating " << cricket::MediaTypeToString(media_type)
4357 << " receiver for track_id=" << sender_info.sender_id
4358 << " and stream_id=" << sender_info.stream_id;
deadbeefab9b2d12015-10-14 11:33:11 -07004359
Steve Anton3d954a62018-04-02 11:27:23 -07004360 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004361 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004362 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004363 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004364 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004365 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08004366 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004367 }
4368}
4369
Steve Anton4171afb2017-11-20 10:20:22 -08004370void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
4371 cricket::MediaType media_type) {
Seth Hampson83d676b2018-04-05 18:12:09 -07004372 RTC_LOG(LS_INFO) << "Removing " << cricket::MediaTypeToString(media_type)
4373 << " receiver for track_id=" << sender_info.sender_id
4374 << " and stream_id=" << sender_info.stream_id;
4375
Seth Hampson845e8782018-03-02 11:34:10 -08004376 MediaStreamInterface* stream = remote_streams_->find(sender_info.stream_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004377
Henrik Boström933d8b02017-10-10 10:05:16 -07004378 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07004379 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07004380 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
4381 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004382 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004383 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004384 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004385 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07004386 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004387 }
4388 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07004389 // Stopping or destroying a VideoRtpReceiver will end the
4390 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08004391 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07004392 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08004393 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07004394 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07004395 // There's no guarantee the track is still available, e.g. the track may
4396 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07004397 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07004398 }
4399 } else {
nisseede5da42017-01-12 05:15:36 -08004400 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07004401 }
Henrik Boström933d8b02017-10-10 10:05:16 -07004402 if (receiver) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004403 Observer()->OnRemoveTrack(receiver);
Henrik Boström933d8b02017-10-10 10:05:16 -07004404 }
deadbeefab9b2d12015-10-14 11:33:11 -07004405}
4406
4407void PeerConnection::UpdateEndedRemoteMediaStreams() {
4408 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
4409 for (size_t i = 0; i < remote_streams_->count(); ++i) {
4410 MediaStreamInterface* stream = remote_streams_->at(i);
4411 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
4412 streams_to_remove.push_back(stream);
4413 }
4414 }
4415
Taylor Brandstetter98cde262016-05-31 13:02:21 -07004416 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07004417 remote_streams_->RemoveStream(stream);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004418 Observer()->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07004419 }
4420}
4421
Steve Anton4171afb2017-11-20 10:20:22 -08004422void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07004423 const std::vector<cricket::StreamParams>& streams,
4424 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08004425 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004426
Seth Hampson845e8782018-03-02 11:34:10 -08004427 // Find removed tracks. I.e., tracks where the track id, stream id or ssrc
deadbeefab9b2d12015-10-14 11:33:11 -07004428 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08004429 for (auto sender_it = current_senders->begin();
4430 sender_it != current_senders->end();
4431 /* incremented manually */) {
4432 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004433 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08004434 cricket::GetStreamBySsrc(streams, info.first_ssrc);
4435 if (!params || params->id != info.sender_id ||
Seth Hampson845e8782018-03-02 11:34:10 -08004436 params->first_stream_id() != info.stream_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004437 OnLocalSenderRemoved(info, media_type);
4438 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07004439 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08004440 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07004441 }
4442 }
4443
Steve Anton4171afb2017-11-20 10:20:22 -08004444 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07004445 for (const cricket::StreamParams& params : streams) {
4446 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08004447 // sender id.
Seth Hampson845e8782018-03-02 11:34:10 -08004448 const std::string& stream_id = params.first_stream_id();
Steve Anton4171afb2017-11-20 10:20:22 -08004449 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07004450 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08004451 const RtpSenderInfo* sender_info =
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004452 FindSenderInfo(*current_senders, stream_id, sender_id);
Steve Anton4171afb2017-11-20 10:20:22 -08004453 if (!sender_info) {
Seth Hampson845e8782018-03-02 11:34:10 -08004454 current_senders->push_back(RtpSenderInfo(stream_id, sender_id, ssrc));
Steve Anton4171afb2017-11-20 10:20:22 -08004455 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07004456 }
4457 }
4458}
4459
Steve Anton4171afb2017-11-20 10:20:22 -08004460void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
4461 cricket::MediaType media_type) {
Seth Hampson5b4f0752018-04-02 16:31:36 -07004462 RTC_DCHECK(!IsUnifiedPlan());
Steve Anton4171afb2017-11-20 10:20:22 -08004463 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004464 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08004465 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
4466 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01004467 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07004468 return;
4469 }
4470
deadbeeffac06552015-11-25 11:26:01 -08004471 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004472 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004473 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004474 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004475 }
deadbeeffac06552015-11-25 11:26:01 -08004476
Seth Hampson5b4f0752018-04-02 16:31:36 -07004477 sender->internal()->set_stream_ids({sender_info.stream_id});
Steve Anton4171afb2017-11-20 10:20:22 -08004478 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07004479}
4480
Steve Anton4171afb2017-11-20 10:20:22 -08004481void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
4482 cricket::MediaType media_type) {
4483 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08004484 if (!sender) {
4485 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07004486 // SessionDescriptions has been renegotiated.
4487 return;
4488 }
deadbeeffac06552015-11-25 11:26:01 -08004489
4490 // A sender has been removed from the SessionDescription but it's still
4491 // associated with the PeerConnection. This only occurs if the SDP doesn't
4492 // match with the calls to CreateSender, AddStream and RemoveStream.
4493 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004494 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004495 " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08004496 return;
deadbeefab9b2d12015-10-14 11:33:11 -07004497 }
deadbeeffac06552015-11-25 11:26:01 -08004498
Steve Anton4171afb2017-11-20 10:20:22 -08004499 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07004500}
4501
4502void PeerConnection::UpdateLocalRtpDataChannels(
4503 const cricket::StreamParamsVec& streams) {
4504 std::vector<std::string> existing_channels;
4505
4506 // Find new and active data channels.
4507 for (const cricket::StreamParams& params : streams) {
4508 // |it->sync_label| is actually the data channel label. The reason is that
4509 // we use the same naming of data channels as we do for
4510 // MediaStreams and Tracks.
4511 // For MediaStreams, the sync_label is the MediaStream label and the
4512 // track label is the same as |streamid|.
Seth Hampson845e8782018-03-02 11:34:10 -08004513 const std::string& channel_label = params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004514 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08004515 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004516 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07004517 continue;
4518 }
4519 // Set the SSRC the data channel should use for sending.
4520 data_channel_it->second->SetSendSsrc(params.first_ssrc());
4521 existing_channels.push_back(data_channel_it->first);
4522 }
4523
4524 UpdateClosingRtpDataChannels(existing_channels, true);
4525}
4526
4527void PeerConnection::UpdateRemoteRtpDataChannels(
4528 const cricket::StreamParamsVec& streams) {
4529 std::vector<std::string> existing_channels;
4530
4531 // Find new and active data channels.
4532 for (const cricket::StreamParams& params : streams) {
4533 // The data channel label is either the mslabel or the SSRC if the mslabel
4534 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
Seth Hampson845e8782018-03-02 11:34:10 -08004535 std::string label = params.first_stream_id().empty()
deadbeefab9b2d12015-10-14 11:33:11 -07004536 ? rtc::ToString(params.first_ssrc())
Seth Hampson845e8782018-03-02 11:34:10 -08004537 : params.first_stream_id();
deadbeefab9b2d12015-10-14 11:33:11 -07004538 auto data_channel_it = rtp_data_channels_.find(label);
4539 if (data_channel_it == rtp_data_channels_.end()) {
4540 // This is a new data channel.
4541 CreateRemoteRtpDataChannel(label, params.first_ssrc());
4542 } else {
4543 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
4544 }
4545 existing_channels.push_back(label);
4546 }
4547
4548 UpdateClosingRtpDataChannels(existing_channels, false);
4549}
4550
4551void PeerConnection::UpdateClosingRtpDataChannels(
4552 const std::vector<std::string>& active_channels,
4553 bool is_local_update) {
4554 auto it = rtp_data_channels_.begin();
4555 while (it != rtp_data_channels_.end()) {
4556 DataChannel* data_channel = it->second;
4557 if (std::find(active_channels.begin(), active_channels.end(),
4558 data_channel->label()) != active_channels.end()) {
4559 ++it;
4560 continue;
4561 }
4562
4563 if (is_local_update) {
4564 data_channel->SetSendSsrc(0);
4565 } else {
4566 data_channel->RemotePeerRequestClose();
4567 }
4568
4569 if (data_channel->state() == DataChannel::kClosed) {
4570 rtp_data_channels_.erase(it);
4571 it = rtp_data_channels_.begin();
4572 } else {
4573 ++it;
4574 }
4575 }
4576}
4577
4578void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
4579 uint32_t remote_ssrc) {
4580 rtc::scoped_refptr<DataChannel> channel(
4581 InternalCreateDataChannel(label, nullptr));
4582 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004583 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
Jonas Olsson45cc8902018-02-13 10:37:07 +01004584 "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07004585 return;
4586 }
4587 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07004588 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4589 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004590 Observer()->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07004591}
4592
4593rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
4594 const std::string& label,
4595 const InternalDataChannelInit* config) {
4596 if (IsClosed()) {
4597 return nullptr;
4598 }
Steve Anton75737c02017-11-06 10:37:17 -08004599 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004600 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07004601 << "InternalCreateDataChannel: Data is not supported in this call.";
4602 return nullptr;
4603 }
4604 InternalDataChannelInit new_config =
4605 config ? (*config) : InternalDataChannelInit();
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004606 if (DataChannel::IsSctpLike(data_channel_type_)) {
deadbeefab9b2d12015-10-14 11:33:11 -07004607 if (new_config.id < 0) {
4608 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08004609 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07004610 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004611 RTC_LOG(LS_ERROR)
4612 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07004613 return nullptr;
4614 }
4615 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004616 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004617 "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07004618 return nullptr;
4619 }
4620 }
4621
Steve Anton75737c02017-11-06 10:37:17 -08004622 rtc::scoped_refptr<DataChannel> channel(
4623 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07004624 if (!channel) {
4625 sid_allocator_.ReleaseSid(new_config.id);
4626 return nullptr;
4627 }
4628
4629 if (channel->data_channel_type() == cricket::DCT_RTP) {
4630 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004631 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
4632 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07004633 return nullptr;
4634 }
4635 rtp_data_channels_[channel->label()] = channel;
4636 } else {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004637 RTC_DCHECK(DataChannel::IsSctpLike(data_channel_type_));
deadbeefab9b2d12015-10-14 11:33:11 -07004638 sctp_data_channels_.push_back(channel);
4639 channel->SignalClosed.connect(this,
4640 &PeerConnection::OnSctpDataChannelClosed);
4641 }
4642
Steve Anton2d8609c2018-01-23 16:38:46 -08004643 SignalDataChannelCreated_(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07004644 return channel;
4645}
4646
4647bool PeerConnection::HasDataChannels() const {
4648 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
4649}
4650
4651void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
4652 for (const auto& channel : sctp_data_channels_) {
4653 if (channel->id() < 0) {
4654 int sid;
4655 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004656 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07004657 continue;
4658 }
4659 channel->SetSctpSid(sid);
4660 }
4661 }
4662}
4663
4664void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08004665 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07004666 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
4667 ++it) {
4668 if (it->get() == channel) {
4669 if (channel->id() >= 0) {
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07004670 // After the closing procedure is done, it's safe to use this ID for
4671 // another data channel.
deadbeefab9b2d12015-10-14 11:33:11 -07004672 sid_allocator_.ReleaseSid(channel->id());
4673 }
deadbeefbd292462015-12-14 18:15:29 -08004674 // Since this method is triggered by a signal from the DataChannel,
4675 // we can't free it directly here; we need to free it asynchronously.
4676 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07004677 sctp_data_channels_.erase(it);
Steve Antonad182762018-09-05 20:22:40 +00004678 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
4679 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07004680 return;
4681 }
4682 }
4683}
4684
deadbeefab9b2d12015-10-14 11:33:11 -07004685void PeerConnection::OnDataChannelDestroyed() {
4686 // Use a temporary copy of the RTP/SCTP DataChannel list because the
4687 // DataChannel may callback to us and try to modify the list.
4688 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
4689 temp_rtp_dcs.swap(rtp_data_channels_);
4690 for (const auto& kv : temp_rtp_dcs) {
4691 kv.second->OnTransportChannelDestroyed();
4692 }
4693
4694 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
4695 temp_sctp_dcs.swap(sctp_data_channels_);
4696 for (const auto& channel : temp_sctp_dcs) {
4697 channel->OnTransportChannelDestroyed();
4698 }
4699}
4700
4701void PeerConnection::OnDataChannelOpenMessage(
4702 const std::string& label,
4703 const InternalDataChannelInit& config) {
4704 rtc::scoped_refptr<DataChannel> channel(
4705 InternalCreateDataChannel(label, &config));
4706 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004707 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07004708 return;
4709 }
4710
deadbeefa601f5c2016-06-06 14:27:39 -07004711 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
4712 DataChannelProxy::Create(signaling_thread(), channel);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02004713 Observer()->OnDataChannel(std::move(proxy_channel));
Harald Alvestrand183e09d2018-06-28 12:04:41 +02004714 NoteUsageEvent(UsageEvent::DATA_ADDED);
deadbeefab9b2d12015-10-14 11:33:11 -07004715}
4716
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004717bool PeerConnection::HandleOpenMessage_s(
4718 const cricket::ReceiveDataParams& params,
4719 const rtc::CopyOnWriteBuffer& buffer) {
4720 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(buffer)) {
4721 // Received OPEN message; parse and signal that a new data channel should
4722 // be created.
4723 std::string label;
4724 InternalDataChannelInit config;
4725 config.id = params.ssrc;
4726 if (!ParseDataChannelOpenMessage(buffer, &label, &config)) {
4727 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for ssrc "
4728 << params.ssrc;
4729 return true;
4730 }
4731 config.open_handshake_role = InternalDataChannelInit::kAcker;
4732 OnDataChannelOpenMessage(label, config);
4733 return true;
4734 }
4735 return false;
4736}
4737
Steve Anton4171afb2017-11-20 10:20:22 -08004738rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4739PeerConnection::GetAudioTransceiver() const {
4740 // This method only works with Plan B SDP, where there is a single
4741 // audio/video transceiver.
4742 RTC_DCHECK(!IsUnifiedPlan());
4743 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004744 if (transceiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004745 return transceiver;
4746 }
4747 }
4748 RTC_NOTREACHED();
4749 return nullptr;
4750}
4751
4752rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4753PeerConnection::GetVideoTransceiver() const {
4754 // This method only works with Plan B SDP, where there is a single
4755 // audio/video transceiver.
4756 RTC_DCHECK(!IsUnifiedPlan());
4757 for (auto transceiver : transceivers_) {
Steve Anton69470252018-02-09 11:43:08 -08004758 if (transceiver->media_type() == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08004759 return transceiver;
4760 }
4761 }
4762 RTC_NOTREACHED();
4763 return nullptr;
4764}
4765
4766// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
4767// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07004768bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08004769 switch (type) {
4770 case cricket::MEDIA_TYPE_AUDIO:
4771 return !GetAudioTransceiver()->internal()->senders().empty();
4772 case cricket::MEDIA_TYPE_VIDEO:
4773 return !GetVideoTransceiver()->internal()->senders().empty();
4774 case cricket::MEDIA_TYPE_DATA:
4775 return false;
4776 }
4777 RTC_NOTREACHED();
4778 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07004779}
4780
Steve Anton4171afb2017-11-20 10:20:22 -08004781rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4782PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
4783 for (auto transceiver : transceivers_) {
4784 for (auto sender : transceiver->internal()->senders()) {
4785 if (sender->track() == track) {
4786 return sender;
4787 }
4788 }
4789 }
4790 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08004791}
4792
Steve Anton4171afb2017-11-20 10:20:22 -08004793rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
4794PeerConnection::FindSenderById(const std::string& sender_id) const {
4795 for (auto transceiver : transceivers_) {
4796 for (auto sender : transceiver->internal()->senders()) {
4797 if (sender->id() == sender_id) {
4798 return sender;
4799 }
4800 }
4801 }
4802 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004803}
4804
Steve Anton4171afb2017-11-20 10:20:22 -08004805rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
4806PeerConnection::FindReceiverById(const std::string& receiver_id) const {
4807 for (auto transceiver : transceivers_) {
4808 for (auto receiver : transceiver->internal()->receivers()) {
4809 if (receiver->id() == receiver_id) {
4810 return receiver;
4811 }
4812 }
4813 }
4814 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07004815}
4816
Steve Anton4171afb2017-11-20 10:20:22 -08004817std::vector<PeerConnection::RtpSenderInfo>*
4818PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
4819 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4820 media_type == cricket::MEDIA_TYPE_VIDEO);
4821 return (media_type == cricket::MEDIA_TYPE_AUDIO)
4822 ? &remote_audio_sender_infos_
4823 : &remote_video_sender_infos_;
4824}
4825
4826std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07004827 cricket::MediaType media_type) {
4828 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
4829 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08004830 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
4831 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07004832}
4833
Steve Anton4171afb2017-11-20 10:20:22 -08004834const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
4835 const std::vector<PeerConnection::RtpSenderInfo>& infos,
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004836 const std::string& stream_id,
Steve Anton4171afb2017-11-20 10:20:22 -08004837 const std::string sender_id) const {
4838 for (const RtpSenderInfo& sender_info : infos) {
Emircan Uysalerbc609ea2018-03-27 21:57:18 +00004839 if (sender_info.stream_id == stream_id &&
4840 sender_info.sender_id == sender_id) {
Steve Anton4171afb2017-11-20 10:20:22 -08004841 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07004842 }
4843 }
4844 return nullptr;
4845}
4846
4847DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
4848 for (const auto& channel : sctp_data_channels_) {
4849 if (channel->id() == sid) {
4850 return channel;
4851 }
4852 }
4853 return nullptr;
4854}
4855
deadbeef91dd5672016-05-18 16:55:30 -07004856bool PeerConnection::InitializePortAllocator_n(
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004857 const cricket::ServerAddresses& stun_servers,
4858 const std::vector<cricket::RelayServerConfig>& turn_servers,
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004859 const RTCConfiguration& configuration) {
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07004860 port_allocator_->Initialize();
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004861 // To handle both internal and externally created port allocator, we will
4862 // enable BUNDLE here.
Qingsi Wanga2d60672018-04-11 16:57:45 -07004863 port_allocator_flags_ = port_allocator_->flags();
4864 port_allocator_flags_ |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
4865 cricket::PORTALLOCATOR_ENABLE_IPV6 |
4866 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004867 // If the disable-IPv6 flag was specified, we'll not override it
4868 // by experiment.
4869 if (configuration.disable_ipv6) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004870 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08004871 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
4872 .find("Disabled") == 0) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004873 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004874 }
4875
zhihuangb09b3f92017-03-07 14:40:51 -08004876 if (configuration.disable_ipv6_on_wifi) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004877 port_allocator_flags_ &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01004878 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08004879 }
4880
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004881 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004882 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004883 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004884 }
4885
honghaiz60347052016-05-31 18:29:12 -07004886 if (configuration.candidate_network_policy ==
4887 kCandidateNetworkPolicyLowCost) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004888 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01004889 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07004890 }
4891
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004892 if (configuration.disable_link_local_networks) {
Qingsi Wanga2d60672018-04-11 16:57:45 -07004893 port_allocator_flags_ |= cricket::PORTALLOCATOR_DISABLE_LINK_LOCAL_NETWORKS;
Daniel Lazarenko2870b0a2018-01-25 10:30:22 +01004894 RTC_LOG(LS_INFO) << "Disable candidates on link-local network interfaces.";
4895 }
4896
Qingsi Wanga2d60672018-04-11 16:57:45 -07004897 port_allocator_->set_flags(port_allocator_flags_);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004898 // No step delay is used while allocating ports.
4899 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
4900 port_allocator_->set_candidate_filter(
4901 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07004902 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004903
Harald Alvestrandb2a74782018-06-28 13:54:07 +02004904 auto turn_servers_copy = turn_servers;
Benjamin Wright6f80f092018-08-13 17:06:26 -07004905 for (auto& turn_server : turn_servers_copy) {
4906 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
Benjamin Wrightd6f86e82018-05-08 13:12:25 -07004907 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004908 // Call this last since it may create pooled allocator sessions using the
4909 // properties set above.
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004910 port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004911 stun_servers, std::move(turn_servers_copy),
4912 configuration.ice_candidate_pool_size, configuration.prune_turn_ports,
4913 configuration.turn_customizer,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004914 configuration.stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004915 return true;
4916}
4917
deadbeef91dd5672016-05-18 16:55:30 -07004918bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08004919 const cricket::ServerAddresses& stun_servers,
4920 const std::vector<cricket::RelayServerConfig>& turn_servers,
4921 IceTransportsType type,
4922 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02004923 bool prune_turn_ports,
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08004924 webrtc::TurnCustomizer* turn_customizer,
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02004925 absl::optional<int> stun_candidate_keepalive_interval) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004926 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08004927 ConvertIceTransportTypeToCandidateFilter(type));
Qingsi Wanga2d60672018-04-11 16:57:45 -07004928 // According to JSEP, after setLocalDescription, changing the candidate pool
4929 // size is not allowed, and changing the set of ICE servers will not result
4930 // in new candidates being gathered.
4931 if (local_description()) {
4932 port_allocator_->FreezeCandidatePool();
4933 }
Benjamin Wright6f80f092018-08-13 17:06:26 -07004934 // Add the custom tls turn servers if they exist.
4935 auto turn_servers_copy = turn_servers;
4936 for (auto& turn_server : turn_servers_copy) {
4937 turn_server.tls_cert_verifier = tls_cert_verifier_.get();
4938 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004939 // Call this last since it may create pooled allocator sessions using the
4940 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08004941 return port_allocator_->SetConfiguration(
Benjamin Wright6f80f092018-08-13 17:06:26 -07004942 stun_servers, std::move(turn_servers_copy), candidate_pool_size,
4943 prune_turn_ports, turn_customizer, stun_candidate_keepalive_interval);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07004944}
4945
Steve Antonba818672017-11-06 10:21:57 -08004946cricket::ChannelManager* PeerConnection::channel_manager() const {
4947 return factory_->channel_manager();
4948}
4949
Elad Alon99c3fe52017-10-13 16:29:40 +02004950bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01004951 std::unique_ptr<RtcEventLogOutput> output,
4952 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08004953 if (!event_log_) {
4954 return false;
4955 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01004956 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07004957}
4958
4959void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08004960 if (event_log_) {
4961 event_log_->StopLogging();
4962 }
ivoc14d5dbe2016-07-04 07:06:55 -07004963}
nisseeaabdf62017-05-05 02:23:02 -07004964
Steve Anton75737c02017-11-06 10:37:17 -08004965cricket::BaseChannel* PeerConnection::GetChannel(
4966 const std::string& content_name) {
Steve Antondcc3c022017-12-22 16:02:54 -08004967 for (auto transceiver : transceivers_) {
4968 cricket::BaseChannel* channel = transceiver->internal()->channel();
4969 if (channel && channel->content_name() == content_name) {
4970 return channel;
4971 }
Steve Anton75737c02017-11-06 10:37:17 -08004972 }
4973 if (rtp_data_channel() &&
4974 rtp_data_channel()->content_name() == content_name) {
4975 return rtp_data_channel();
4976 }
4977 return nullptr;
4978}
4979
4980bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004981 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08004982 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004983 RTC_LOG(LS_INFO)
4984 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004985 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004986 return false;
4987 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004988 if (!sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004989 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01004990 "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08004991 return false;
4992 }
4993
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08004994 absl::optional<rtc::SSLRole> dtls_role;
4995 if (sctp_mid_) {
4996 dtls_role = transport_controller_->GetDtlsRole(*sctp_mid_);
4997 } else if (is_caller_) {
4998 dtls_role = *is_caller_ ? rtc::SSL_SERVER : rtc::SSL_CLIENT;
4999 }
Zhi Huange830e682018-03-30 10:48:35 -07005000 if (dtls_role) {
5001 *role = *dtls_role;
5002 return true;
5003 }
5004 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005005}
5006
5007bool PeerConnection::GetSslRole(const std::string& content_name,
5008 rtc::SSLRole* role) {
5009 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005010 RTC_LOG(LS_INFO)
5011 << "Local and Remote descriptions must be applied to get the "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005012 "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08005013 return false;
5014 }
5015
Zhi Huange830e682018-03-30 10:48:35 -07005016 auto dtls_role = transport_controller_->GetDtlsRole(content_name);
5017 if (dtls_role) {
5018 *role = *dtls_role;
5019 return true;
5020 }
5021 return false;
Steve Anton75737c02017-11-06 10:37:17 -08005022}
5023
Steve Antonf8470812017-12-04 10:46:21 -08005024void PeerConnection::SetSessionError(SessionError error,
5025 const std::string& error_desc) {
5026 RTC_DCHECK_RUN_ON(signaling_thread());
5027 if (error != session_error_) {
5028 session_error_ = error;
5029 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08005030 }
5031}
5032
Zhi Huange830e682018-03-30 10:48:35 -07005033RTCError PeerConnection::UpdateSessionState(
5034 SdpType type,
5035 cricket::ContentSource source,
5036 const cricket::SessionDescription* description) {
Steve Anton8a006912017-12-04 15:25:56 -08005037 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005038
5039 // If there's already a pending error then no state transition should happen.
5040 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08005041 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005042
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005043 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08005044 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08005045 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005046 }
5047
5048 // Update the signaling state according to the specified state machine (see
5049 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08005050 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005051 ChangeSignalingState(source == cricket::CS_LOCAL
5052 ? PeerConnectionInterface::kHaveLocalOffer
5053 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08005054 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005055 ChangeSignalingState(source == cricket::CS_LOCAL
5056 ? PeerConnectionInterface::kHaveLocalPrAnswer
5057 : PeerConnectionInterface::kHaveRemotePrAnswer);
5058 } else {
Steve Anton3828c062017-12-06 10:34:51 -08005059 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005060 ChangeSignalingState(PeerConnectionInterface::kStable);
5061 }
5062
5063 // Update internal objects according to the session description's media
5064 // descriptions.
Zhi Huange830e682018-03-30 10:48:35 -07005065 RTCError error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005066 if (!error.ok()) {
Steve Anton80dd7b52018-02-16 17:08:42 -08005067 return error;
Steve Anton6d6a2ae2017-12-04 17:19:47 -08005068 }
5069
Steve Anton8a006912017-12-04 15:25:56 -08005070 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005071}
5072
Steve Anton8a006912017-12-04 15:25:56 -08005073RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08005074 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08005075 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08005076 const SessionDescriptionInterface* sdesc =
5077 (source == cricket::CS_LOCAL ? local_description()
5078 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08005079 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08005080
5081 // Push down the new SDP media section for each audio/video transceiver.
5082 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08005083 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08005084 FindMediaSectionForTransceiver(transceiver, sdesc);
5085 cricket::BaseChannel* channel = transceiver->internal()->channel();
5086 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08005087 continue;
5088 }
5089 const MediaContentDescription* content_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005090 content_info->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005091 if (!content_desc) {
5092 continue;
5093 }
5094 std::string error;
Yves Gerey665174f2018-06-19 15:03:05 +02005095 bool success = (source == cricket::CS_LOCAL)
5096 ? channel->SetLocalContent(content_desc, type, &error)
5097 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005098 if (!success) {
5099 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
5100 }
5101 }
5102
5103 // If using the RtpDataChannel, push down the new SDP section for it too.
5104 if (rtp_data_channel_) {
5105 const ContentInfo* data_content =
5106 cricket::GetFirstDataContent(sdesc->description());
5107 if (data_content && !data_content->rejected) {
5108 const MediaContentDescription* data_desc =
Steve Antonb1c1de12017-12-21 15:14:30 -08005109 data_content->media_description();
Steve Antoned10bd92017-12-05 10:52:59 -08005110 if (data_desc) {
5111 std::string error;
5112 bool success =
5113 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08005114 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
Yves Gerey665174f2018-06-19 15:03:05 +02005115 : rtp_data_channel_->SetRemoteContent(data_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08005116 if (!success) {
5117 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5118 std::move(error));
5119 }
Steve Anton75737c02017-11-06 10:37:17 -08005120 }
5121 }
5122 }
Steve Antoned10bd92017-12-05 10:52:59 -08005123
Steve Anton75737c02017-11-06 10:37:17 -08005124 // Need complete offer/answer with an SCTP m= section before starting SCTP,
5125 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
5126 if (sctp_transport_ && local_description() && remote_description() &&
5127 cricket::GetFirstDataContent(local_description()->description()) &&
5128 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08005129 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08005130 RTC_FROM_HERE,
5131 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08005132 if (!success) {
5133 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5134 "Failed to push down SCTP parameters.");
5135 }
Steve Anton75737c02017-11-06 10:37:17 -08005136 }
Steve Antoned10bd92017-12-05 10:52:59 -08005137
Steve Anton8a006912017-12-04 15:25:56 -08005138 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005139}
5140
5141bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
5142 RTC_DCHECK(network_thread()->IsCurrent());
5143 RTC_DCHECK(local_description());
5144 RTC_DCHECK(remote_description());
5145 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
5146 // When we support "max-message-size", that would also be pushed down here.
5147 return sctp_transport_->Start(
5148 GetSctpPort(local_description()->description()),
5149 GetSctpPort(remote_description()->description()));
5150}
5151
Steve Anton8a006912017-12-04 15:25:56 -08005152RTCError PeerConnection::PushdownTransportDescription(
5153 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08005154 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08005155 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005156
Zhi Huange830e682018-03-30 10:48:35 -07005157 if (source == cricket::CS_LOCAL) {
5158 const SessionDescriptionInterface* sdesc = local_description();
5159 RTC_DCHECK(sdesc);
5160 return transport_controller_->SetLocalDescription(type,
5161 sdesc->description());
5162 } else {
5163 const SessionDescriptionInterface* sdesc = remote_description();
5164 RTC_DCHECK(sdesc);
5165 return transport_controller_->SetRemoteDescription(type,
5166 sdesc->description());
Steve Anton75737c02017-11-06 10:37:17 -08005167 }
Steve Anton75737c02017-11-06 10:37:17 -08005168}
5169
5170bool PeerConnection::GetTransportDescription(
5171 const SessionDescription* description,
5172 const std::string& content_name,
5173 cricket::TransportDescription* tdesc) {
5174 if (!description || !tdesc) {
5175 return false;
5176 }
5177 const TransportInfo* transport_info =
5178 description->GetTransportInfoByName(content_name);
5179 if (!transport_info) {
5180 return false;
5181 }
5182 *tdesc = transport_info->description;
5183 return true;
5184}
5185
Steve Anton75737c02017-11-06 10:37:17 -08005186cricket::IceConfig PeerConnection::ParseIceConfig(
5187 const PeerConnectionInterface::RTCConfiguration& config) const {
5188 cricket::ContinualGatheringPolicy gathering_policy;
Steve Anton75737c02017-11-06 10:37:17 -08005189 switch (config.continual_gathering_policy) {
5190 case PeerConnectionInterface::GATHER_ONCE:
5191 gathering_policy = cricket::GATHER_ONCE;
5192 break;
5193 case PeerConnectionInterface::GATHER_CONTINUALLY:
5194 gathering_policy = cricket::GATHER_CONTINUALLY;
5195 break;
5196 default:
5197 RTC_NOTREACHED();
5198 gathering_policy = cricket::GATHER_ONCE;
5199 }
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005200
Steve Anton75737c02017-11-06 10:37:17 -08005201 cricket::IceConfig ice_config;
Qingsi Wang866e08d2018-03-22 17:54:23 -07005202 ice_config.receiving_timeout = RTCConfigurationToIceConfigOptionalInt(
5203 config.ice_connection_receiving_timeout);
Steve Anton75737c02017-11-06 10:37:17 -08005204 ice_config.prioritize_most_likely_candidate_pairs =
5205 config.prioritize_most_likely_ice_candidate_pairs;
5206 ice_config.backup_connection_ping_interval =
Qingsi Wang866e08d2018-03-22 17:54:23 -07005207 RTCConfigurationToIceConfigOptionalInt(
5208 config.ice_backup_candidate_pair_ping_interval);
Steve Anton75737c02017-11-06 10:37:17 -08005209 ice_config.continual_gathering_policy = gathering_policy;
5210 ice_config.presume_writable_when_fully_relayed =
5211 config.presume_writable_when_fully_relayed;
Qingsi Wange6826d22018-03-08 14:55:14 -08005212 ice_config.ice_check_interval_strong_connectivity =
5213 config.ice_check_interval_strong_connectivity;
5214 ice_config.ice_check_interval_weak_connectivity =
5215 config.ice_check_interval_weak_connectivity;
Steve Anton75737c02017-11-06 10:37:17 -08005216 ice_config.ice_check_min_interval = config.ice_check_min_interval;
Qingsi Wangdb53f8e2018-02-20 14:45:49 -08005217 ice_config.stun_keepalive_interval = config.stun_candidate_keepalive_interval;
Steve Anton75737c02017-11-06 10:37:17 -08005218 ice_config.regather_all_networks_interval_range =
5219 config.ice_regather_interval_range;
Qingsi Wang9a5c6f82018-02-01 10:38:40 -08005220 ice_config.network_preference = config.network_preference;
Steve Anton75737c02017-11-06 10:37:17 -08005221 return ice_config;
5222}
5223
Steve Anton75737c02017-11-06 10:37:17 -08005224bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
5225 std::string* track_id) {
5226 if (!local_description()) {
5227 return false;
5228 }
5229 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
5230 track_id);
5231}
5232
5233bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
5234 std::string* track_id) {
5235 if (!remote_description()) {
5236 return false;
5237 }
5238 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
5239 track_id);
5240}
5241
5242bool PeerConnection::SendData(const cricket::SendDataParams& params,
5243 const rtc::CopyOnWriteBuffer& payload,
5244 cricket::SendDataResult* result) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005245 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
5246 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_, "
5247 "sctp_transport_, and media_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005248 return false;
5249 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005250 if (media_transport_) {
5251 SendDataParams send_params;
5252 send_params.type = ToWebrtcDataMessageType(params.type);
5253 send_params.ordered = params.ordered;
5254 if (params.max_rtx_count >= 0) {
5255 send_params.max_rtx_count = params.max_rtx_count;
5256 } else if (params.max_rtx_ms >= 0) {
5257 send_params.max_rtx_ms = params.max_rtx_ms;
5258 }
5259 return media_transport_->SendData(params.sid, send_params, payload).ok();
5260 }
Steve Anton75737c02017-11-06 10:37:17 -08005261 return rtp_data_channel_
5262 ? rtp_data_channel_->SendData(params, payload, result)
5263 : network_thread()->Invoke<bool>(
5264 RTC_FROM_HERE,
5265 Bind(&cricket::SctpTransportInternal::SendData,
5266 sctp_transport_.get(), params, payload, result));
5267}
5268
5269bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005270 RTC_DCHECK_RUN_ON(signaling_thread());
5271 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Steve Anton75737c02017-11-06 10:37:17 -08005272 // Don't log an error here, because DataChannels are expected to call
5273 // ConnectDataChannel in this state. It's the only way to initially tell
5274 // whether or not the underlying transport is ready.
5275 return false;
5276 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005277 if (media_transport_) {
5278 SignalMediaTransportWritable_s.connect(webrtc_data_channel,
5279 &DataChannel::OnChannelReady);
5280 SignalMediaTransportReceivedData_s.connect(webrtc_data_channel,
5281 &DataChannel::OnDataReceived);
5282 SignalMediaTransportChannelClosing_s.connect(
5283 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5284 SignalMediaTransportChannelClosed_s.connect(
5285 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
5286 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005287 rtp_data_channel_->SignalReadyToSendData.connect(
5288 webrtc_data_channel, &DataChannel::OnChannelReady);
5289 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
5290 &DataChannel::OnDataReceived);
5291 } else {
5292 SignalSctpReadyToSendData.connect(webrtc_data_channel,
5293 &DataChannel::OnChannelReady);
5294 SignalSctpDataReceived.connect(webrtc_data_channel,
5295 &DataChannel::OnDataReceived);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005296 SignalSctpClosingProcedureStartedRemotely.connect(
5297 webrtc_data_channel, &DataChannel::OnClosingProcedureStartedRemotely);
5298 SignalSctpClosingProcedureComplete.connect(
5299 webrtc_data_channel, &DataChannel::OnClosingProcedureComplete);
Steve Anton75737c02017-11-06 10:37:17 -08005300 }
5301 return true;
5302}
5303
5304void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005305 RTC_DCHECK_RUN_ON(signaling_thread());
5306 if (!rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005307 RTC_LOG(LS_ERROR)
5308 << "DisconnectDataChannel called when rtp_data_channel_ and "
5309 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005310 return;
5311 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005312 if (media_transport_) {
5313 SignalMediaTransportWritable_s.disconnect(webrtc_data_channel);
5314 SignalMediaTransportReceivedData_s.disconnect(webrtc_data_channel);
5315 SignalMediaTransportChannelClosing_s.disconnect(webrtc_data_channel);
5316 SignalMediaTransportChannelClosed_s.disconnect(webrtc_data_channel);
5317 } else if (rtp_data_channel_) {
Steve Anton75737c02017-11-06 10:37:17 -08005318 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
5319 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
5320 } else {
5321 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
5322 SignalSctpDataReceived.disconnect(webrtc_data_channel);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005323 SignalSctpClosingProcedureStartedRemotely.disconnect(webrtc_data_channel);
5324 SignalSctpClosingProcedureComplete.disconnect(webrtc_data_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005325 }
5326}
5327
5328void PeerConnection::AddSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005329 if (media_transport_) {
5330 // No-op. Media transport does not need to add streams.
5331 return;
5332 }
Steve Anton75737c02017-11-06 10:37:17 -08005333 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005334 RTC_LOG(LS_ERROR)
5335 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005336 return;
5337 }
5338 network_thread()->Invoke<void>(
5339 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
5340 sctp_transport_.get(), sid));
5341}
5342
5343void PeerConnection::RemoveSctpDataStream(int sid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005344 if (media_transport_) {
5345 media_transport_->CloseChannel(sid);
5346 return;
5347 }
Steve Anton75737c02017-11-06 10:37:17 -08005348 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005349 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005350 "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08005351 return;
5352 }
5353 network_thread()->Invoke<void>(
5354 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
5355 sctp_transport_.get(), sid));
5356}
5357
5358bool PeerConnection::ReadyToSendData() const {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005359 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08005360 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005361 (media_transport_ && media_transport_ready_to_send_data_) ||
Steve Anton75737c02017-11-06 10:37:17 -08005362 sctp_ready_to_send_data_;
5363}
5364
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005365void PeerConnection::OnDataReceived(int channel_id,
5366 DataMessageType type,
5367 const rtc::CopyOnWriteBuffer& buffer) {
5368 cricket::ReceiveDataParams params;
5369 params.sid = channel_id;
5370 params.type = ToCricketDataMessageType(type);
5371 media_transport_invoker_->AsyncInvoke<void>(
5372 RTC_FROM_HERE, signaling_thread(), [this, params, buffer] {
5373 RTC_DCHECK_RUN_ON(signaling_thread());
5374 if (!HandleOpenMessage_s(params, buffer)) {
5375 SignalMediaTransportReceivedData_s(params, buffer);
5376 }
5377 });
5378}
5379
5380void PeerConnection::OnChannelClosing(int channel_id) {
5381 media_transport_invoker_->AsyncInvoke<void>(
5382 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5383 RTC_DCHECK_RUN_ON(signaling_thread());
5384 SignalMediaTransportChannelClosing_s(channel_id);
5385 });
5386}
5387
5388void PeerConnection::OnChannelClosed(int channel_id) {
5389 media_transport_invoker_->AsyncInvoke<void>(
5390 RTC_FROM_HERE, signaling_thread(), [this, channel_id] {
5391 RTC_DCHECK_RUN_ON(signaling_thread());
5392 SignalMediaTransportChannelClosed_s(channel_id);
5393 });
5394}
5395
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005396absl::optional<std::string> PeerConnection::sctp_transport_name() const {
Zhi Huange830e682018-03-30 10:48:35 -07005397 if (sctp_mid_ && transport_controller_) {
5398 auto dtls_transport = transport_controller_->GetDtlsTransport(*sctp_mid_);
5399 if (dtls_transport) {
5400 return dtls_transport->transport_name();
5401 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005402 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005403 }
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005404 return absl::optional<std::string>();
Zhi Huange830e682018-03-30 10:48:35 -07005405}
5406
Qingsi Wang72a43a12018-02-20 16:03:18 -08005407cricket::CandidateStatsList PeerConnection::GetPooledCandidateStats() const {
5408 cricket::CandidateStatsList candidate_states_list;
Qingsi Wanga2d60672018-04-11 16:57:45 -07005409 network_thread()->Invoke<void>(
5410 RTC_FROM_HERE,
5411 rtc::Bind(&cricket::PortAllocator::GetCandidateStatsFromPooledSessions,
5412 port_allocator_.get(), &candidate_states_list));
Qingsi Wang72a43a12018-02-20 16:03:18 -08005413 return candidate_states_list;
5414}
5415
Steve Anton5dfde182018-02-06 10:34:40 -08005416std::map<std::string, std::string> PeerConnection::GetTransportNamesByMid()
5417 const {
5418 std::map<std::string, std::string> transport_names_by_mid;
5419 for (auto transceiver : transceivers_) {
5420 cricket::BaseChannel* channel = transceiver->internal()->channel();
5421 if (channel) {
5422 transport_names_by_mid[channel->content_name()] =
5423 channel->transport_name();
5424 }
Steve Anton75737c02017-11-06 10:37:17 -08005425 }
Steve Anton5dfde182018-02-06 10:34:40 -08005426 if (rtp_data_channel_) {
5427 transport_names_by_mid[rtp_data_channel_->content_name()] =
5428 rtp_data_channel_->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08005429 }
5430 if (sctp_transport_) {
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02005431 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07005432 RTC_DCHECK(transport_name);
5433 transport_names_by_mid[*sctp_mid_] = *transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08005434 }
Steve Anton5dfde182018-02-06 10:34:40 -08005435 return transport_names_by_mid;
Steve Anton75737c02017-11-06 10:37:17 -08005436}
5437
Steve Anton5dfde182018-02-06 10:34:40 -08005438std::map<std::string, cricket::TransportStats>
5439PeerConnection::GetTransportStatsByNames(
5440 const std::set<std::string>& transport_names) {
5441 if (!network_thread()->IsCurrent()) {
5442 return network_thread()
5443 ->Invoke<std::map<std::string, cricket::TransportStats>>(
5444 RTC_FROM_HERE,
5445 [&] { return GetTransportStatsByNames(transport_names); });
Steve Anton75737c02017-11-06 10:37:17 -08005446 }
Steve Anton5dfde182018-02-06 10:34:40 -08005447 std::map<std::string, cricket::TransportStats> transport_stats_by_name;
5448 for (const std::string& transport_name : transport_names) {
5449 cricket::TransportStats transport_stats;
5450 bool success =
5451 transport_controller_->GetStats(transport_name, &transport_stats);
5452 if (success) {
5453 transport_stats_by_name[transport_name] = std::move(transport_stats);
5454 } else {
5455 RTC_LOG(LS_ERROR) << "Failed to get transport stats for transport_name="
5456 << transport_name;
5457 }
5458 }
5459 return transport_stats_by_name;
Steve Anton75737c02017-11-06 10:37:17 -08005460}
5461
5462bool PeerConnection::GetLocalCertificate(
5463 const std::string& transport_name,
5464 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
Zhi Huange830e682018-03-30 10:48:35 -07005465 if (!certificate) {
5466 return false;
5467 }
5468 *certificate = transport_controller_->GetLocalCertificate(transport_name);
5469 return *certificate != nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005470}
5471
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005472std::unique_ptr<rtc::SSLCertChain> PeerConnection::GetRemoteSSLCertChain(
Steve Anton75737c02017-11-06 10:37:17 -08005473 const std::string& transport_name) {
Taylor Brandstetterc3928662018-02-23 13:04:51 -08005474 return transport_controller_->GetRemoteSSLCertChain(transport_name);
Steve Anton75737c02017-11-06 10:37:17 -08005475}
5476
5477cricket::DataChannelType PeerConnection::data_channel_type() const {
5478 return data_channel_type_;
5479}
5480
5481bool PeerConnection::IceRestartPending(const std::string& content_name) const {
5482 return pending_ice_restarts_.find(content_name) !=
5483 pending_ice_restarts_.end();
5484}
5485
Steve Anton75737c02017-11-06 10:37:17 -08005486bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
5487 return transport_controller_->NeedsIceRestart(content_name);
5488}
5489
5490void PeerConnection::OnCertificateReady(
5491 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
5492 transport_controller_->SetLocalCertificate(certificate);
5493}
5494
5495void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08005496 SetSessionError(SessionError::kTransport,
5497 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08005498}
5499
5500void PeerConnection::OnTransportControllerConnectionState(
5501 cricket::IceConnectionState state) {
5502 switch (state) {
5503 case cricket::kIceConnectionConnecting:
5504 // If the current state is Connected or Completed, then there were
5505 // writable channels but now there are not, so the next state must
5506 // be Disconnected.
5507 // kIceConnectionConnecting is currently used as the default,
5508 // un-connected state by the TransportController, so its only use is
5509 // detecting disconnections.
5510 if (ice_connection_state_ ==
5511 PeerConnectionInterface::kIceConnectionConnected ||
5512 ice_connection_state_ ==
5513 PeerConnectionInterface::kIceConnectionCompleted) {
5514 SetIceConnectionState(
5515 PeerConnectionInterface::kIceConnectionDisconnected);
5516 }
5517 break;
5518 case cricket::kIceConnectionFailed:
5519 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
5520 break;
5521 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005522 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005523 "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08005524 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005525 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Steve Anton75737c02017-11-06 10:37:17 -08005526 break;
5527 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01005528 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005529 "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08005530 if (ice_connection_state_ !=
5531 PeerConnectionInterface::kIceConnectionConnected) {
5532 // If jumping directly from "checking" to "connected",
5533 // signal "connected" first.
5534 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
5535 }
5536 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
Harald Alvestrand8ebba742018-05-31 14:00:34 +02005537 NoteUsageEvent(UsageEvent::ICE_STATE_CONNECTED);
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005538 ReportTransportStats();
Steve Anton75737c02017-11-06 10:37:17 -08005539 break;
5540 default:
5541 RTC_NOTREACHED();
5542 }
5543}
5544
5545void PeerConnection::OnTransportControllerCandidatesGathered(
5546 const std::string& transport_name,
5547 const cricket::Candidates& candidates) {
5548 RTC_DCHECK(signaling_thread()->IsCurrent());
5549 int sdp_mline_index;
5550 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005551 RTC_LOG(LS_ERROR)
5552 << "OnTransportControllerCandidatesGathered: content name "
5553 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08005554 return;
5555 }
5556
5557 for (cricket::Candidates::const_iterator citer = candidates.begin();
5558 citer != candidates.end(); ++citer) {
5559 // Use transport_name as the candidate media id.
5560 std::unique_ptr<JsepIceCandidate> candidate(
5561 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
5562 if (local_description()) {
5563 mutable_local_description()->AddCandidate(candidate.get());
5564 }
5565 OnIceCandidate(std::move(candidate));
5566 }
5567}
5568
5569void PeerConnection::OnTransportControllerCandidatesRemoved(
5570 const std::vector<cricket::Candidate>& candidates) {
5571 RTC_DCHECK(signaling_thread()->IsCurrent());
5572 // Sanity check.
5573 for (const cricket::Candidate& candidate : candidates) {
5574 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005575 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005576 "empty content name in candidate "
Mirko Bonadei675513b2017-11-09 11:09:25 +01005577 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08005578 return;
5579 }
5580 }
5581
5582 if (local_description()) {
5583 mutable_local_description()->RemoveCandidates(candidates);
5584 }
5585 OnIceCandidatesRemoved(candidates);
5586}
5587
5588void PeerConnection::OnTransportControllerDtlsHandshakeError(
5589 rtc::SSLHandshakeError error) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07005590 RTC_HISTOGRAM_ENUMERATION(
5591 "WebRTC.PeerConnection.DtlsHandshakeError", static_cast<int>(error),
5592 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
Steve Anton75737c02017-11-06 10:37:17 -08005593}
5594
Steve Antoned10bd92017-12-05 10:52:59 -08005595void PeerConnection::EnableSending() {
5596 for (auto transceiver : transceivers_) {
5597 cricket::BaseChannel* channel = transceiver->internal()->channel();
5598 if (channel && !channel->enabled()) {
5599 channel->Enable(true);
5600 }
Steve Anton75737c02017-11-06 10:37:17 -08005601 }
5602
Steve Anton4171afb2017-11-20 10:20:22 -08005603 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08005604 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08005605 }
Steve Anton75737c02017-11-06 10:37:17 -08005606}
5607
5608// Returns the media index for a local ice candidate given the content name.
5609bool PeerConnection::GetLocalCandidateMediaIndex(
5610 const std::string& content_name,
5611 int* sdp_mline_index) {
5612 if (!local_description() || !sdp_mline_index) {
5613 return false;
5614 }
5615
5616 bool content_found = false;
5617 const ContentInfos& contents = local_description()->description()->contents();
5618 for (size_t index = 0; index < contents.size(); ++index) {
5619 if (contents[index].name == content_name) {
5620 *sdp_mline_index = static_cast<int>(index);
5621 content_found = true;
5622 break;
5623 }
5624 }
5625 return content_found;
5626}
5627
5628bool PeerConnection::UseCandidatesInSessionDescription(
5629 const SessionDescriptionInterface* remote_desc) {
5630 if (!remote_desc) {
5631 return true;
5632 }
5633 bool ret = true;
5634
5635 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
5636 const IceCandidateCollection* candidates = remote_desc->candidates(m);
5637 for (size_t n = 0; n < candidates->count(); ++n) {
5638 const IceCandidateInterface* candidate = candidates->at(n);
5639 bool valid = false;
5640 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
5641 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005642 RTC_LOG(LS_INFO)
5643 << "UseCandidatesInSessionDescription: Not ready to use "
Jonas Olsson45cc8902018-02-13 10:37:07 +01005644 "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08005645 }
5646 continue;
5647 }
5648 ret = UseCandidate(candidate);
5649 if (!ret) {
5650 break;
5651 }
5652 }
5653 }
5654 return ret;
5655}
5656
5657bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
5658 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
5659 size_t remote_content_size =
5660 remote_description()->description()->contents().size();
5661 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01005662 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08005663 return false;
5664 }
5665
5666 cricket::ContentInfo content =
5667 remote_description()->description()->contents()[mediacontent_index];
5668 std::vector<cricket::Candidate> candidates;
5669 candidates.push_back(candidate->candidate());
5670 // Invoking BaseSession method to handle remote candidates.
Zhi Huange830e682018-03-30 10:48:35 -07005671 RTCError error =
5672 transport_controller_->AddRemoteCandidates(content.name, candidates);
Henrik Boström5d8f8fa2018-04-13 15:22:50 +00005673 if (error.ok()) {
5674 // Candidates successfully submitted for checking.
5675 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
5676 ice_connection_state_ ==
5677 PeerConnectionInterface::kIceConnectionDisconnected) {
5678 // If state is New, then the session has just gotten its first remote ICE
5679 // candidates, so go to Checking.
5680 // If state is Disconnected, the session is re-using old candidates or
5681 // receiving additional ones, so go to Checking.
5682 // If state is Connected, stay Connected.
5683 // TODO(bemasc): If state is Connected, and the new candidates are for a
5684 // newly added transport, then the state actually _should_ move to
5685 // checking. Add a way to distinguish that case.
5686 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
5687 }
5688 // TODO(bemasc): If state is Completed, go back to Connected.
Jonas Olsson941a07c2018-09-13 10:07:07 +02005689 } else {
Zhi Huange830e682018-03-30 10:48:35 -07005690 RTC_LOG(LS_WARNING) << error.message();
Steve Anton75737c02017-11-06 10:37:17 -08005691 }
5692 return true;
5693}
5694
5695void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08005696 // Destroy video channel first since it may have a pointer to the
5697 // voice channel.
5698 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08005699 if (!video_info || video_info->rejected) {
5700 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005701 }
5702
Steve Anton6fec8802017-12-04 10:37:29 -08005703 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
5704 if (!audio_info || audio_info->rejected) {
5705 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08005706 }
5707
5708 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
5709 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08005710 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08005711 }
5712}
5713
Steve Antondcc3c022017-12-22 16:02:54 -08005714RTCErrorOr<const cricket::ContentGroup*> PeerConnection::GetEarlyBundleGroup(
5715 const SessionDescription& desc) const {
Steve Anton75737c02017-11-06 10:37:17 -08005716 const cricket::ContentGroup* bundle_group = nullptr;
5717 if (configuration_.bundle_policy ==
5718 PeerConnectionInterface::kBundlePolicyMaxBundle) {
Steve Antondcc3c022017-12-22 16:02:54 -08005719 bundle_group = desc.GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton75737c02017-11-06 10:37:17 -08005720 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08005721 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
5722 "max-bundle configured but session description "
5723 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08005724 }
5725 }
Steve Antondcc3c022017-12-22 16:02:54 -08005726 return std::move(bundle_group);
5727}
5728
5729RTCError PeerConnection::CreateChannels(const SessionDescription& desc) {
Zhi Huange830e682018-03-30 10:48:35 -07005730 // Creating the media channels. Transports should already have been created
5731 // at this point.
Steve Antondcc3c022017-12-22 16:02:54 -08005732 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005733 if (voice && !voice->rejected &&
5734 !GetAudioTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005735 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(voice->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005736 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005737 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5738 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08005739 }
5740 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
5741 }
5742
Steve Antondcc3c022017-12-22 16:02:54 -08005743 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(&desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005744 if (video && !video->rejected &&
5745 !GetVideoTransceiver()->internal()->channel()) {
Zhi Huange830e682018-03-30 10:48:35 -07005746 cricket::VideoChannel* video_channel = CreateVideoChannel(video->name);
Steve Antoneda6ccd2017-12-04 10:21:55 -08005747 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08005748 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5749 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005750 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08005751 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08005752 }
5753
Steve Antondcc3c022017-12-22 16:02:54 -08005754 const cricket::ContentInfo* data = cricket::GetFirstDataContent(&desc);
Steve Anton75737c02017-11-06 10:37:17 -08005755 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005756 !rtp_data_channel_ && !sctp_transport_ && !media_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07005757 if (!CreateDataChannel(data->name)) {
Steve Anton8a006912017-12-04 15:25:56 -08005758 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
5759 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08005760 }
5761 }
5762
Steve Anton8a006912017-12-04 15:25:56 -08005763 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08005764}
5765
Steve Anton4171afb2017-11-20 10:20:22 -08005766// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005767cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005768 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005769 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
Bjorn Mellema9bbd862018-11-02 09:07:48 -07005770 MediaTransportInterface* media_transport = nullptr;
5771 if (configuration_.use_media_transport) {
5772 media_transport = GetMediaTransport(mid);
5773 }
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005774
Steve Anton75737c02017-11-06 10:37:17 -08005775 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005776 call_.get(), configuration_.media_config, rtp_transport, media_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005777 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5778 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005779 if (!voice_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005780 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005781 }
Steve Anton75737c02017-11-06 10:37:17 -08005782 voice_channel->SignalDtlsSrtpSetupFailure.connect(
5783 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005784 voice_channel->SignalSentPacket.connect(this,
5785 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005786 voice_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005787
Steve Antoneda6ccd2017-12-04 10:21:55 -08005788 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005789}
5790
Steve Anton4171afb2017-11-20 10:20:22 -08005791// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08005792cricket::VideoChannel* PeerConnection::CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005793 const std::string& mid) {
Anton Sukhanov98a462c2018-10-17 13:15:42 -07005794 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5795
5796 // TODO(sukhanov): Propagate media_transport to video channel.
Steve Anton75737c02017-11-06 10:37:17 -08005797 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
Zhi Huange830e682018-03-30 10:48:35 -07005798 call_.get(), configuration_.media_config, rtp_transport,
Benjamin Wright8c27cca2018-10-25 10:16:44 -07005799 signaling_thread(), mid, SrtpRequired(), GetCryptoOptions(),
5800 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08005801 if (!video_channel) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08005802 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08005803 }
Steve Anton75737c02017-11-06 10:37:17 -08005804 video_channel->SignalDtlsSrtpSetupFailure.connect(
5805 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08005806 video_channel->SignalSentPacket.connect(this,
5807 &PeerConnection::OnSentPacket_w);
Zhi Huange830e682018-03-30 10:48:35 -07005808 video_channel->SetRtpTransport(rtp_transport);
Steve Anton4171afb2017-11-20 10:20:22 -08005809
Steve Antoneda6ccd2017-12-04 10:21:55 -08005810 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08005811}
5812
Zhi Huange830e682018-03-30 10:48:35 -07005813bool PeerConnection::CreateDataChannel(const std::string& mid) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005814 switch (data_channel_type_) {
5815 case cricket::DCT_MEDIA_TRANSPORT:
5816 if (network_thread()->Invoke<bool>(
5817 RTC_FROM_HERE,
5818 rtc::Bind(&PeerConnection::SetupMediaTransportForDataChannels_n,
5819 this, mid))) {
5820 for (const auto& channel : sctp_data_channels_) {
5821 channel->OnTransportChannelCreated();
5822 }
5823 return true;
5824 }
Steve Anton75737c02017-11-06 10:37:17 -08005825 return false;
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005826 case cricket::DCT_SCTP:
5827 if (!sctp_factory_) {
5828 RTC_LOG(LS_ERROR)
5829 << "Trying to create SCTP transport, but didn't compile with "
5830 "SCTP support (HAVE_SCTP)";
5831 return false;
5832 }
5833 if (!network_thread()->Invoke<bool>(
5834 RTC_FROM_HERE,
5835 rtc::Bind(&PeerConnection::CreateSctpTransport_n, this, mid))) {
5836 return false;
5837 }
5838 for (const auto& channel : sctp_data_channels_) {
5839 channel->OnTransportChannelCreated();
5840 }
5841 return true;
5842 case cricket::DCT_RTP:
5843 default:
5844 RtpTransportInternal* rtp_transport = GetRtpTransport(mid);
5845 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
5846 configuration_.media_config, rtp_transport, signaling_thread(), mid,
5847 SrtpRequired(), GetCryptoOptions());
5848 if (!rtp_data_channel_) {
5849 return false;
5850 }
5851 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
5852 this, &PeerConnection::OnDtlsSrtpSetupFailure);
5853 rtp_data_channel_->SignalSentPacket.connect(
5854 this, &PeerConnection::OnSentPacket_w);
5855 rtp_data_channel_->SetRtpTransport(rtp_transport);
5856 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005857 }
5858
Steve Anton75737c02017-11-06 10:37:17 -08005859 return true;
5860}
5861
5862Call::Stats PeerConnection::GetCallStats() {
5863 if (!worker_thread()->IsCurrent()) {
5864 return worker_thread()->Invoke<Call::Stats>(
5865 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
5866 }
5867 if (call_) {
5868 return call_->GetStats();
5869 } else {
5870 return Call::Stats();
5871 }
5872}
5873
Zhi Huange830e682018-03-30 10:48:35 -07005874bool PeerConnection::CreateSctpTransport_n(const std::string& mid) {
Steve Anton75737c02017-11-06 10:37:17 -08005875 RTC_DCHECK(network_thread()->IsCurrent());
5876 RTC_DCHECK(sctp_factory_);
Zhi Huang644fde42018-04-02 19:16:26 -07005877 cricket::DtlsTransportInternal* dtls_transport =
Zhi Huange830e682018-03-30 10:48:35 -07005878 transport_controller_->GetDtlsTransport(mid);
Zhi Huang644fde42018-04-02 19:16:26 -07005879 RTC_DCHECK(dtls_transport);
5880 sctp_transport_ = sctp_factory_->CreateSctpTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08005881 RTC_DCHECK(sctp_transport_);
5882 sctp_invoker_.reset(new rtc::AsyncInvoker());
5883 sctp_transport_->SignalReadyToSendData.connect(
5884 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
5885 sctp_transport_->SignalDataReceived.connect(
5886 this, &PeerConnection::OnSctpTransportDataReceived_n);
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005887 // TODO(deadbeef): All we do here is AsyncInvoke to fire the signal on
5888 // another thread. Would be nice if there was a helper class similar to
5889 // sigslot::repeater that did this for us, eliminating a bunch of boilerplate
5890 // code.
5891 sctp_transport_->SignalClosingProcedureStartedRemotely.connect(
5892 this, &PeerConnection::OnSctpClosingProcedureStartedRemotely_n);
5893 sctp_transport_->SignalClosingProcedureComplete.connect(
5894 this, &PeerConnection::OnSctpClosingProcedureComplete_n);
Zhi Huange830e682018-03-30 10:48:35 -07005895 sctp_mid_ = mid;
Zhi Huang644fde42018-04-02 19:16:26 -07005896 sctp_transport_->SetDtlsTransport(dtls_transport);
Zhi Huange830e682018-03-30 10:48:35 -07005897 return true;
Steve Anton75737c02017-11-06 10:37:17 -08005898}
5899
5900void PeerConnection::DestroySctpTransport_n() {
5901 RTC_DCHECK(network_thread()->IsCurrent());
5902 sctp_transport_.reset(nullptr);
Zhi Huange830e682018-03-30 10:48:35 -07005903 sctp_mid_.reset();
Steve Anton75737c02017-11-06 10:37:17 -08005904 sctp_invoker_.reset(nullptr);
5905 sctp_ready_to_send_data_ = false;
5906}
5907
5908void PeerConnection::OnSctpTransportReadyToSendData_n() {
5909 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5910 RTC_DCHECK(network_thread()->IsCurrent());
5911 // Note: Cannot use rtc::Bind here because it will grab a reference to
5912 // PeerConnection and potentially cause PeerConnection to live longer than
5913 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5914 // be destroyed before PeerConnection is destroyed, and at that point all
5915 // pending tasks will be cleared.
5916 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
5917 OnSctpTransportReadyToSendData_s(true);
5918 });
5919}
5920
5921void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
5922 RTC_DCHECK(signaling_thread()->IsCurrent());
5923 sctp_ready_to_send_data_ = ready;
5924 SignalSctpReadyToSendData(ready);
5925}
5926
5927void PeerConnection::OnSctpTransportDataReceived_n(
5928 const cricket::ReceiveDataParams& params,
5929 const rtc::CopyOnWriteBuffer& payload) {
5930 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5931 RTC_DCHECK(network_thread()->IsCurrent());
5932 // Note: Cannot use rtc::Bind here because it will grab a reference to
5933 // PeerConnection and potentially cause PeerConnection to live longer than
5934 // expected. It is safe not to grab a reference since the sctp_invoker_ will
5935 // be destroyed before PeerConnection is destroyed, and at that point all
5936 // pending tasks will be cleared.
5937 sctp_invoker_->AsyncInvoke<void>(
5938 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
5939 OnSctpTransportDataReceived_s(params, payload);
5940 });
5941}
5942
5943void PeerConnection::OnSctpTransportDataReceived_s(
5944 const cricket::ReceiveDataParams& params,
5945 const rtc::CopyOnWriteBuffer& payload) {
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005946 RTC_DCHECK_RUN_ON(signaling_thread());
5947 if (!HandleOpenMessage_s(params, payload)) {
Steve Anton75737c02017-11-06 10:37:17 -08005948 SignalSctpDataReceived(params, payload);
5949 }
5950}
5951
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005952void PeerConnection::OnSctpClosingProcedureStartedRemotely_n(int sid) {
Steve Anton75737c02017-11-06 10:37:17 -08005953 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5954 RTC_DCHECK(network_thread()->IsCurrent());
5955 sctp_invoker_->AsyncInvoke<void>(
5956 RTC_FROM_HERE, signaling_thread(),
5957 rtc::Bind(&sigslot::signal1<int>::operator(),
Taylor Brandstettercdd05f02018-05-31 13:23:32 -07005958 &SignalSctpClosingProcedureStartedRemotely, sid));
5959}
5960
5961void PeerConnection::OnSctpClosingProcedureComplete_n(int sid) {
5962 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
5963 RTC_DCHECK(network_thread()->IsCurrent());
5964 sctp_invoker_->AsyncInvoke<void>(
5965 RTC_FROM_HERE, signaling_thread(),
5966 rtc::Bind(&sigslot::signal1<int>::operator(),
5967 &SignalSctpClosingProcedureComplete, sid));
Steve Anton75737c02017-11-06 10:37:17 -08005968}
5969
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08005970bool PeerConnection::SetupMediaTransportForDataChannels_n(
5971 const std::string& mid) {
5972 media_transport_ = transport_controller_->GetMediaTransport(mid);
5973 if (!media_transport_) {
5974 RTC_LOG(LS_ERROR) << "Media transport is not available for data channels";
5975 return false;
5976 }
5977
5978 media_transport_invoker_ = absl::make_unique<rtc::AsyncInvoker>();
5979 media_transport_->SetDataSink(this);
5980 media_transport_data_mid_ = mid;
5981 transport_controller_->SignalMediaTransportStateChanged.connect(
5982 this, &PeerConnection::OnMediaTransportStateChanged_n);
5983 // Check the initial state right away, in case transport is already writable.
5984 OnMediaTransportStateChanged_n();
5985 return true;
5986}
5987
5988void PeerConnection::TeardownMediaTransportForDataChannels_n() {
5989 if (!media_transport_) {
5990 return;
5991 }
5992 transport_controller_->SignalMediaTransportStateChanged.disconnect(this);
5993 media_transport_data_mid_.reset();
5994 media_transport_->SetDataSink(nullptr);
5995 media_transport_invoker_ = nullptr;
5996 media_transport_ = nullptr;
5997}
5998
5999void PeerConnection::OnMediaTransportStateChanged_n() {
6000 if (!media_transport_data_mid_ ||
6001 transport_controller_->GetMediaTransportState(
6002 *media_transport_data_mid_) != MediaTransportState::kWritable) {
6003 return;
6004 }
6005 media_transport_invoker_->AsyncInvoke<void>(
6006 RTC_FROM_HERE, signaling_thread(), [this] {
6007 RTC_DCHECK_RUN_ON(signaling_thread());
6008 media_transport_ready_to_send_data_ = true;
6009 SignalMediaTransportWritable_s(media_transport_ready_to_send_data_);
6010 });
6011}
6012
Steve Anton75737c02017-11-06 10:37:17 -08006013// Returns false if bundle is enabled and rtcp_mux is disabled.
6014bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
6015 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
6016 if (!bundle_enabled)
6017 return true;
6018
6019 const cricket::ContentGroup* bundle_group =
6020 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
6021 RTC_DCHECK(bundle_group != NULL);
6022
6023 const cricket::ContentInfos& contents = desc->contents();
6024 for (cricket::ContentInfos::const_iterator citer = contents.begin();
6025 citer != contents.end(); ++citer) {
6026 const cricket::ContentInfo* content = (&*citer);
6027 RTC_DCHECK(content != NULL);
6028 if (bundle_group->HasContentName(content->name) && !content->rejected &&
Steve Anton5adfafd2017-12-20 16:34:00 -08006029 content->type == MediaProtocolType::kRtp) {
Steve Anton75737c02017-11-06 10:37:17 -08006030 if (!HasRtcpMuxEnabled(content))
6031 return false;
6032 }
6033 }
6034 // RTCP-MUX is enabled in all the contents.
6035 return true;
6036}
6037
6038bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
Steve Antonb1c1de12017-12-21 15:14:30 -08006039 return content->media_description()->rtcp_mux();
Steve Anton75737c02017-11-06 10:37:17 -08006040}
6041
Steve Anton8a006912017-12-04 15:25:56 -08006042RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08006043 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08006044 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08006045 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08006046 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08006047 }
6048
6049 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08006050 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08006051 }
6052
Steve Anton3828c062017-12-06 10:34:51 -08006053 SdpType type = sdesc->GetType();
6054 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
6055 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08006056 LOG_AND_RETURN_ERROR(
Harald Alvestrand5081c0c2018-03-09 15:18:03 +01006057 RTCErrorType::INVALID_STATE,
Steve Anton8a006912017-12-04 15:25:56 -08006058 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08006059 }
6060
6061 // Verify crypto settings.
6062 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08006063 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
6064 dtls_enabled_) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006065 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
Steve Anton8a006912017-12-04 15:25:56 -08006066 if (!crypto_error.ok()) {
6067 return crypto_error;
6068 }
Steve Anton75737c02017-11-06 10:37:17 -08006069 }
6070
6071 // Verify ice-ufrag and ice-pwd.
6072 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006073 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6074 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08006075 }
6076
6077 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08006078 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6079 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08006080 }
6081
6082 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
6083 // m-lines that do not rtcp-mux enabled.
6084
6085 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08006086 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006087 // With an answer we want to compare the new answer session description with
6088 // the offer's session description from the current negotiation.
Steve Anton75737c02017-11-06 10:37:17 -08006089 const cricket::SessionDescription* offer_desc =
6090 (source == cricket::CS_LOCAL) ? remote_description()->description()
6091 : local_description()->description();
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006092 if (!MediaSectionsHaveSameCount(*offer_desc, *sdesc->description()) ||
6093 !MediaSectionsInSameOrder(*offer_desc, nullptr, *sdesc->description(),
6094 type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006095 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6096 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006097 }
6098 } else {
Steve Anton75737c02017-11-06 10:37:17 -08006099 // The re-offers should respect the order of m= sections in current
6100 // description. See RFC3264 Section 8 paragraph 4 for more details.
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006101 // With a re-offer, either the current local or current remote descriptions
6102 // could be the most up to date, so we would like to check against both of
6103 // them if they exist. It could be the case that one of them has a 0 port
6104 // for a media section, but the other does not. This is important to check
6105 // against in the case that we are recycling an m= section.
6106 const cricket::SessionDescription* current_desc = nullptr;
6107 const cricket::SessionDescription* secondary_current_desc = nullptr;
6108 if (local_description()) {
6109 current_desc = local_description()->description();
6110 if (remote_description()) {
6111 secondary_current_desc = remote_description()->description();
6112 }
6113 } else if (remote_description()) {
6114 current_desc = remote_description()->description();
6115 }
Steve Anton75737c02017-11-06 10:37:17 -08006116 if (current_desc &&
Seth Hampsonae8a90a2018-02-13 15:33:48 -08006117 !MediaSectionsInSameOrder(*current_desc, secondary_current_desc,
6118 *sdesc->description(), type)) {
Steve Anton8a006912017-12-04 15:25:56 -08006119 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6120 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08006121 }
6122 }
6123
Steve Antonba42e992018-04-09 14:10:01 -07006124 if (IsUnifiedPlan()) {
6125 // Ensure that each audio and video media section has at most one
6126 // "StreamParams". This will return an error if receiving a session
6127 // description from a "Plan B" endpoint which adds multiple tracks of the
6128 // same type. With Unified Plan, there can only be at most one track per
6129 // media section.
6130 for (const ContentInfo& content : sdesc->description()->contents()) {
6131 const MediaContentDescription& desc = *content.description;
6132 if ((desc.type() == cricket::MEDIA_TYPE_AUDIO ||
6133 desc.type() == cricket::MEDIA_TYPE_VIDEO) &&
6134 desc.streams().size() > 1u) {
6135 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
6136 "Media section has more than one track specified "
6137 "with a=ssrc lines which is not supported with "
6138 "Unified Plan.");
6139 }
6140 }
6141 }
6142
Steve Anton8a006912017-12-04 15:25:56 -08006143 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08006144}
6145
Steve Anton3828c062017-12-06 10:34:51 -08006146bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006147 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006148 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006149 return (state == PeerConnectionInterface::kStable) ||
6150 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08006151 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006152 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006153 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
6154 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
6155 }
6156}
6157
Steve Anton3828c062017-12-06 10:34:51 -08006158bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08006159 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08006160 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08006161 return (state == PeerConnectionInterface::kStable) ||
6162 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08006163 } else {
Steve Anton3828c062017-12-06 10:34:51 -08006164 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08006165 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
6166 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
6167 }
6168}
6169
Steve Antonf8470812017-12-04 10:46:21 -08006170const char* PeerConnection::SessionErrorToString(SessionError error) const {
6171 switch (error) {
6172 case SessionError::kNone:
6173 return "ERROR_NONE";
6174 case SessionError::kContent:
6175 return "ERROR_CONTENT";
6176 case SessionError::kTransport:
6177 return "ERROR_TRANSPORT";
6178 }
6179 RTC_NOTREACHED();
6180 return "";
6181}
6182
Steve Anton75737c02017-11-06 10:37:17 -08006183std::string PeerConnection::GetSessionErrorMsg() {
Jonas Olsson366a50c2018-09-06 13:41:30 +02006184 rtc::StringBuilder desc;
Steve Antonf8470812017-12-04 10:46:21 -08006185 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
6186 desc << kSessionErrorDesc << session_error_desc() << ".";
Jonas Olsson84df1c72018-09-14 16:59:32 +02006187 return desc.Release();
Steve Anton75737c02017-11-06 10:37:17 -08006188}
6189
Steve Anton8e20f172018-03-06 10:55:04 -08006190void PeerConnection::ReportSdpFormatReceived(
6191 const SessionDescriptionInterface& remote_offer) {
Steve Anton8e20f172018-03-06 10:55:04 -08006192 int num_audio_mlines = 0;
6193 int num_video_mlines = 0;
6194 int num_audio_tracks = 0;
6195 int num_video_tracks = 0;
6196 for (const ContentInfo& content : remote_offer.description()->contents()) {
6197 cricket::MediaType media_type = content.media_description()->type();
6198 int num_tracks = std::max(
6199 1, static_cast<int>(content.media_description()->streams().size()));
6200 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
6201 num_audio_mlines += 1;
6202 num_audio_tracks += num_tracks;
6203 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
6204 num_video_mlines += 1;
6205 num_video_tracks += num_tracks;
6206 }
6207 }
6208 SdpFormatReceived format = kSdpFormatReceivedNoTracks;
6209 if (num_audio_mlines > 1 || num_video_mlines > 1) {
6210 format = kSdpFormatReceivedComplexUnifiedPlan;
6211 } else if (num_audio_tracks > 1 || num_video_tracks > 1) {
6212 format = kSdpFormatReceivedComplexPlanB;
6213 } else if (num_audio_tracks > 0 || num_video_tracks > 0) {
6214 format = kSdpFormatReceivedSimple;
6215 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006216 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpFormatReceived", format,
6217 kSdpFormatReceivedMax);
Steve Anton8e20f172018-03-06 10:55:04 -08006218}
6219
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006220void PeerConnection::NoteUsageEvent(UsageEvent event) {
6221 RTC_DCHECK_RUN_ON(signaling_thread());
6222 usage_event_accumulator_ |= static_cast<int>(event);
6223}
6224
6225void PeerConnection::ReportUsagePattern() const {
6226 RTC_DLOG(LS_INFO) << "Usage signature is " << usage_event_accumulator_;
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006227 RTC_HISTOGRAM_ENUMERATION_SPARSE("WebRTC.PeerConnection.UsagePattern",
6228 usage_event_accumulator_,
6229 static_cast<int>(UsageEvent::MAX_VALUE));
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006230 const int bad_bits =
6231 static_cast<int>(UsageEvent::SET_LOCAL_DESCRIPTION_CALLED) |
6232 static_cast<int>(UsageEvent::CANDIDATE_COLLECTED);
6233 const int good_bits =
6234 static_cast<int>(UsageEvent::SET_REMOTE_DESCRIPTION_CALLED) |
6235 static_cast<int>(UsageEvent::REMOTE_CANDIDATE_ADDED) |
6236 static_cast<int>(UsageEvent::ICE_STATE_CONNECTED);
6237 if ((usage_event_accumulator_ & bad_bits) == bad_bits &&
6238 (usage_event_accumulator_ & good_bits) == 0) {
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006239 // If called after close(), we can't report, because observer may have
6240 // been deallocated, and therefore pointer is null. Write to log instead.
6241 if (observer_) {
6242 Observer()->OnInterestingUsage(usage_event_accumulator_);
6243 } else {
6244 RTC_LOG(LS_INFO) << "Interesting usage signature "
6245 << usage_event_accumulator_
6246 << " observed after observer shutdown";
6247 }
Harald Alvestrandc0e97252018-07-26 10:39:55 +02006248 }
Harald Alvestrand8ebba742018-05-31 14:00:34 +02006249}
6250
Steve Anton0ffaaa22018-02-23 10:31:30 -08006251void PeerConnection::ReportNegotiatedSdpSemantics(
6252 const SessionDescriptionInterface& answer) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006253 SdpSemanticNegotiated semantics_negotiated;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006254 switch (answer.description()->msid_signaling()) {
6255 case 0:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006256 semantics_negotiated = kSdpSemanticNegotiatedNone;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006257 break;
6258 case cricket::kMsidSignalingMediaSection:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006259 semantics_negotiated = kSdpSemanticNegotiatedUnifiedPlan;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006260 break;
6261 case cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006262 semantics_negotiated = kSdpSemanticNegotiatedPlanB;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006263 break;
6264 case cricket::kMsidSignalingMediaSection |
6265 cricket::kMsidSignalingSsrcAttribute:
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006266 semantics_negotiated = kSdpSemanticNegotiatedMixed;
Steve Anton0ffaaa22018-02-23 10:31:30 -08006267 break;
6268 default:
6269 RTC_NOTREACHED();
6270 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006271 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.SdpSemanticNegotiated",
6272 semantics_negotiated, kSdpSemanticNegotiatedMax);
Steve Anton0ffaaa22018-02-23 10:31:30 -08006273}
6274
Steve Anton75737c02017-11-06 10:37:17 -08006275// We need to check the local/remote description for the Transport instead of
6276// the session, because a new Transport added during renegotiation may have
6277// them unset while the session has them set from the previous negotiation.
6278// Not doing so may trigger the auto generation of transport description and
6279// mess up DTLS identity information, ICE credential, etc.
6280bool PeerConnection::ReadyToUseRemoteCandidate(
6281 const IceCandidateInterface* candidate,
6282 const SessionDescriptionInterface* remote_desc,
6283 bool* valid) {
6284 *valid = true;
6285
6286 const SessionDescriptionInterface* current_remote_desc =
6287 remote_desc ? remote_desc : remote_description();
6288
6289 if (!current_remote_desc) {
6290 return false;
6291 }
6292
6293 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
6294 size_t remote_content_size =
6295 current_remote_desc->description()->contents().size();
6296 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01006297 RTC_LOG(LS_ERROR)
6298 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
6299 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08006300
6301 *valid = false;
6302 return false;
6303 }
6304
6305 cricket::ContentInfo content =
6306 current_remote_desc->description()->contents()[mediacontent_index];
6307
6308 const std::string transport_name = GetTransportName(content.name);
6309 if (transport_name.empty()) {
6310 return false;
6311 }
Zhi Huange830e682018-03-30 10:48:35 -07006312 return true;
Steve Anton75737c02017-11-06 10:37:17 -08006313}
6314
6315bool PeerConnection::SrtpRequired() const {
6316 return dtls_enabled_ ||
6317 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
6318}
6319
6320void PeerConnection::OnTransportControllerGatheringState(
6321 cricket::IceGatheringState state) {
6322 RTC_DCHECK(signaling_thread()->IsCurrent());
6323 if (state == cricket::kIceGatheringGathering) {
6324 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
6325 } else if (state == cricket::kIceGatheringComplete) {
6326 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
6327 }
6328}
6329
6330void PeerConnection::ReportTransportStats() {
Steve Antonc7b964c2018-02-01 14:39:45 -08006331 std::map<std::string, std::set<cricket::MediaType>>
6332 media_types_by_transport_name;
6333 for (auto transceiver : transceivers_) {
6334 if (transceiver->internal()->channel()) {
6335 const std::string& transport_name =
6336 transceiver->internal()->channel()->transport_name();
6337 media_types_by_transport_name[transport_name].insert(
Steve Anton69470252018-02-09 11:43:08 -08006338 transceiver->media_type());
Steve Antonc7b964c2018-02-01 14:39:45 -08006339 }
Steve Anton75737c02017-11-06 10:37:17 -08006340 }
6341 if (rtp_data_channel()) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006342 media_types_by_transport_name[rtp_data_channel()->transport_name()].insert(
6343 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006344 }
Zhi Huange830e682018-03-30 10:48:35 -07006345
Danil Chapovalov66cadcc2018-06-19 16:47:43 +02006346 absl::optional<std::string> transport_name = sctp_transport_name();
Zhi Huange830e682018-03-30 10:48:35 -07006347 if (transport_name) {
6348 media_types_by_transport_name[*transport_name].insert(
Steve Antonc7b964c2018-02-01 14:39:45 -08006349 cricket::MEDIA_TYPE_DATA);
Steve Anton75737c02017-11-06 10:37:17 -08006350 }
Zhi Huange830e682018-03-30 10:48:35 -07006351
Steve Antonc7b964c2018-02-01 14:39:45 -08006352 for (const auto& entry : media_types_by_transport_name) {
6353 const std::string& transport_name = entry.first;
6354 const std::set<cricket::MediaType> media_types = entry.second;
Steve Anton75737c02017-11-06 10:37:17 -08006355 cricket::TransportStats stats;
Steve Antonc7b964c2018-02-01 14:39:45 -08006356 if (transport_controller_->GetStats(transport_name, &stats)) {
Steve Anton75737c02017-11-06 10:37:17 -08006357 ReportBestConnectionState(stats);
Steve Antonc7b964c2018-02-01 14:39:45 -08006358 ReportNegotiatedCiphers(stats, media_types);
Steve Anton75737c02017-11-06 10:37:17 -08006359 }
6360 }
6361}
6362// Walk through the ConnectionInfos to gather best connection usage
6363// for IPv4 and IPv6.
6364void PeerConnection::ReportBestConnectionState(
6365 const cricket::TransportStats& stats) {
Steve Antonc7b964c2018-02-01 14:39:45 -08006366 for (const cricket::TransportChannelStats& channel_stats :
6367 stats.channel_stats) {
6368 for (const cricket::ConnectionInfo& connection_info :
6369 channel_stats.connection_infos) {
6370 if (!connection_info.best_connection) {
Steve Anton75737c02017-11-06 10:37:17 -08006371 continue;
6372 }
6373
Steve Antonc7b964c2018-02-01 14:39:45 -08006374 const cricket::Candidate& local = connection_info.local_candidate;
6375 const cricket::Candidate& remote = connection_info.remote_candidate;
Steve Anton75737c02017-11-06 10:37:17 -08006376
6377 // Increment the counter for IceCandidatePairType.
6378 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
6379 (local.type() == RELAY_PORT_TYPE &&
6380 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006381 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_TCP",
6382 GetIceCandidatePairCounter(local, remote),
6383 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006384 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006385 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.CandidatePairType_UDP",
6386 GetIceCandidatePairCounter(local, remote),
6387 kIceCandidatePairMax);
Steve Anton75737c02017-11-06 10:37:17 -08006388 } else {
6389 RTC_CHECK(0);
6390 }
Steve Anton75737c02017-11-06 10:37:17 -08006391
6392 // Increment the counter for IP type.
6393 if (local.address().family() == AF_INET) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006394 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6395 kBestConnections_IPv4,
6396 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006397 } else if (local.address().family() == AF_INET6) {
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006398 RTC_HISTOGRAM_ENUMERATION("WebRTC.PeerConnection.IPMetrics",
6399 kBestConnections_IPv6,
6400 kPeerConnectionAddressFamilyCounter_Max);
Steve Anton75737c02017-11-06 10:37:17 -08006401 } else {
6402 RTC_CHECK(0);
6403 }
6404
6405 return;
6406 }
6407 }
6408}
6409
6410void PeerConnection::ReportNegotiatedCiphers(
Steve Antonc7b964c2018-02-01 14:39:45 -08006411 const cricket::TransportStats& stats,
6412 const std::set<cricket::MediaType>& media_types) {
Steve Anton75737c02017-11-06 10:37:17 -08006413 if (!dtls_enabled_ || stats.channel_stats.empty()) {
6414 return;
6415 }
6416
6417 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
6418 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
6419 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
6420 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
6421 return;
6422 }
6423
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006424 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
6425 for (cricket::MediaType media_type : media_types) {
6426 switch (media_type) {
6427 case cricket::MEDIA_TYPE_AUDIO:
6428 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6429 "WebRTC.PeerConnection.SrtpCryptoSuite.Audio", srtp_crypto_suite,
6430 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6431 break;
6432 case cricket::MEDIA_TYPE_VIDEO:
6433 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6434 "WebRTC.PeerConnection.SrtpCryptoSuite.Video", srtp_crypto_suite,
6435 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6436 break;
6437 case cricket::MEDIA_TYPE_DATA:
6438 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6439 "WebRTC.PeerConnection.SrtpCryptoSuite.Data", srtp_crypto_suite,
6440 rtc::SRTP_CRYPTO_SUITE_MAX_VALUE);
6441 break;
6442 default:
6443 RTC_NOTREACHED();
6444 continue;
6445 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006446 }
Qingsi Wang7fc821d2018-07-12 12:54:53 -07006447 }
6448
6449 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
6450 for (cricket::MediaType media_type : media_types) {
6451 switch (media_type) {
6452 case cricket::MEDIA_TYPE_AUDIO:
6453 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6454 "WebRTC.PeerConnection.SslCipherSuite.Audio", ssl_cipher_suite,
6455 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6456 break;
6457 case cricket::MEDIA_TYPE_VIDEO:
6458 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6459 "WebRTC.PeerConnection.SslCipherSuite.Video", ssl_cipher_suite,
6460 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6461 break;
6462 case cricket::MEDIA_TYPE_DATA:
6463 RTC_HISTOGRAM_ENUMERATION_SPARSE(
6464 "WebRTC.PeerConnection.SslCipherSuite.Data", ssl_cipher_suite,
6465 rtc::SSL_CIPHER_SUITE_MAX_VALUE);
6466 break;
6467 default:
6468 RTC_NOTREACHED();
6469 continue;
6470 }
Steve Antonc7b964c2018-02-01 14:39:45 -08006471 }
Steve Anton75737c02017-11-06 10:37:17 -08006472 }
6473}
6474
6475void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
6476 RTC_DCHECK(worker_thread()->IsCurrent());
6477 RTC_DCHECK(call_);
6478 call_->OnSentPacket(sent_packet);
6479}
6480
6481const std::string PeerConnection::GetTransportName(
6482 const std::string& content_name) {
6483 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08006484 if (channel) {
6485 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08006486 }
Steve Anton6fec8802017-12-04 10:37:29 -08006487 if (sctp_transport_) {
Zhi Huange830e682018-03-30 10:48:35 -07006488 RTC_DCHECK(sctp_mid_);
6489 if (content_name == *sctp_mid_) {
6490 return *sctp_transport_name();
Steve Anton6fec8802017-12-04 10:37:29 -08006491 }
6492 }
6493 // Return an empty string if failed to retrieve the transport name.
6494 return "";
Steve Anton75737c02017-11-06 10:37:17 -08006495}
6496
Steve Anton6fec8802017-12-04 10:37:29 -08006497void PeerConnection::DestroyTransceiverChannel(
6498 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
6499 transceiver) {
6500 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08006501
Steve Anton6fec8802017-12-04 10:37:29 -08006502 cricket::BaseChannel* channel = transceiver->internal()->channel();
6503 if (channel) {
6504 transceiver->internal()->SetChannel(nullptr);
6505 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08006506 }
6507}
6508
6509void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08006510 if (rtp_data_channel_) {
6511 OnDataChannelDestroyed();
6512 DestroyBaseChannel(rtp_data_channel_);
6513 rtp_data_channel_ = nullptr;
6514 }
6515
6516 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
6517 // grab a reference to this PeerConnection. If this is called from the
6518 // PeerConnection destructor, the RefCountedObject vtable will have already
6519 // been destroyed (since it is a subclass of PeerConnection) and using
6520 // rtc::Bind will cause "Pure virtual function called" error to appear.
6521
6522 if (sctp_transport_) {
6523 OnDataChannelDestroyed();
6524 network_thread()->Invoke<void>(RTC_FROM_HERE,
6525 [this] { DestroySctpTransport_n(); });
6526 }
Bjorn Mellem175aa2e2018-11-08 11:23:22 -08006527
6528 if (media_transport_) {
6529 OnDataChannelDestroyed();
6530 network_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
6531 RTC_DCHECK_RUN_ON(network_thread());
6532 TeardownMediaTransportForDataChannels_n();
6533 });
6534 }
Steve Anton6fec8802017-12-04 10:37:29 -08006535}
6536
6537void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
6538 RTC_DCHECK(channel);
Steve Anton6fec8802017-12-04 10:37:29 -08006539 switch (channel->media_type()) {
6540 case cricket::MEDIA_TYPE_AUDIO:
6541 channel_manager()->DestroyVoiceChannel(
6542 static_cast<cricket::VoiceChannel*>(channel));
6543 break;
6544 case cricket::MEDIA_TYPE_VIDEO:
6545 channel_manager()->DestroyVideoChannel(
6546 static_cast<cricket::VideoChannel*>(channel));
6547 break;
6548 case cricket::MEDIA_TYPE_DATA:
6549 channel_manager()->DestroyRtpDataChannel(
6550 static_cast<cricket::RtpDataChannel*>(channel));
6551 break;
6552 default:
6553 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
6554 break;
6555 }
Zhi Huange830e682018-03-30 10:48:35 -07006556}
Steve Anton6fec8802017-12-04 10:37:29 -08006557
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006558bool PeerConnection::OnTransportChanged(
Zhi Huange830e682018-03-30 10:48:35 -07006559 const std::string& mid,
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006560 RtpTransportInternal* rtp_transport,
6561 cricket::DtlsTransportInternal* dtls_transport) {
6562 bool ret = true;
Zhi Huange830e682018-03-30 10:48:35 -07006563 auto base_channel = GetChannel(mid);
6564 if (base_channel) {
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006565 ret = base_channel->SetRtpTransport(rtp_transport);
Zhi Huange830e682018-03-30 10:48:35 -07006566 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006567 if (sctp_transport_ && mid == sctp_mid_) {
Zhi Huang644fde42018-04-02 19:16:26 -07006568 sctp_transport_->SetDtlsTransport(dtls_transport);
Steve Anton75737c02017-11-06 10:37:17 -08006569 }
Taylor Brandstettercbaa2542018-04-16 16:42:14 -07006570 return ret;
Steve Anton75737c02017-11-06 10:37:17 -08006571}
6572
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006573PeerConnectionObserver* PeerConnection::Observer() const {
6574 // In earlier production code, the pointer was not cleared on close,
6575 // which might have led to undefined behavior if the observer was not
6576 // deallocated, or strange crashes if it was.
6577 // We use CHECK in order to catch such behavior if it exists.
6578 // TODO(hta): Remove or replace with DCHECK if nothing is found.
6579 RTC_CHECK(observer_);
6580 return observer_;
6581}
6582
Benjamin Wright8c27cca2018-10-25 10:16:44 -07006583CryptoOptions PeerConnection::GetCryptoOptions() {
6584 // TODO(bugs.webrtc.org/9891) - Remove PeerConnectionFactory::CryptoOptions
6585 // after it has been removed.
6586 return configuration_.crypto_options.has_value()
6587 ? *configuration_.crypto_options
6588 : factory_->options().crypto_options;
6589}
6590
Harald Alvestrand89061872018-01-02 14:08:34 +01006591void PeerConnection::ClearStatsCache() {
6592 if (stats_collector_) {
6593 stats_collector_->ClearCachedStatsReport();
6594 }
6595}
6596
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006597void PeerConnection::RequestUsagePatternReportForTesting() {
Steve Antonad182762018-09-05 20:22:40 +00006598 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_REPORT_USAGE_PATTERN,
6599 nullptr);
Harald Alvestrand7a1c7f72018-08-01 10:50:16 +02006600}
6601
henrike@webrtc.org28e20752013-07-10 00:45:36 +00006602} // namespace webrtc